<commit_before>//****************************************************************************
// written by Anna Sajina and Noah Kurinsky, 2012
// updated by Noah Kurinsky 10/13
// The purpose of this program is to read-in the parameters set in the idl
// wrapper (simulation.pro) and to use MCMC to determine the best-fit set of
// parameters.
// Specifically it runs through a number of iterations (runs) in each stage
// calling on simulator.cpp to compute the chi2 for a given set of parameters
// then the metrop algorithm is invoked to decide whether or not a given trial
// run is accepted. If so it is added to a chain of mcmc values.
//****************************************************************************

#include "simulator.h"
#include "functions.h"
#include "mc_util.h"
#include <stdio.h>

//Array size definitions
#define BANDS 3

#define VERBOSE( ARG ) \
  if(q.oprint){	       \
    ARG;	       \
  }

#define TERSE( ARG )   \
  if(!q.oprint){       \
    ARG;	       \
  }

using namespace std;

int main(int argc,char** argv){

  printf("\nMCMC Fitting Code Compiled: %s\n\n",__DATE__);

  Configuration q(argc,argv);
  VERBOSE(q.print());
  RandomNumberGenerator rng;

  //general variable declarations
  bool accept,saved;
  unsigned long i,m;
  unsigned long pi;
  vector<int>::const_iterator p;
  double trial;

  //this array holds phi0,L0,alpha,beta,p, and q
  double lpars[LUMPARS];
  double lmin[LUMPARS];
  double lmax[LUMPARS];
  q.LFparameters(lpars);
  q.LFparameters(lmin,q.min);
  q.LFparameters(lmax,q.max);
  double CE = q.colorEvolution[q.value];
  double CEmin = q.colorEvolution[q.min];
  double CEmax = q.colorEvolution[q.max];

  //counts
  string countnames[]= {"dnds250","dnds350","dnds500"};

  lumfunct lf;
  lf.set_params(lpars);

  //initialize simulator
  simulator survey(q.filterfile,q.obsfile,q.sedfile);
  survey.set_color_exp(CE); //color evolution
  survey.set_lumfunct(&lf);

  //NON GENERAL COUNTS
  //the flux array is logarithmic in steps of 0.3dex
  q.ns=8;
  survey.set_size(q.areaSteradian(),q.dz,q.zmin,q.nz,q.ns);
  int bnum[]={16,13,10};
  products output(q.nz,bnum);

  MCChains mcchain(q.nchain,q.nparams,q.runs,q.conv_step);
  MCChains burnchain(q.nchain,q.nparams,q.runs,q.conv_step);
  mcchain.set_constraints(q.rmax,q.a_ci);
  burnchain.set_constraints(1.5,0.25);

  ResultChain counts(3,q.nchain*q.runs);

  MetropSampler metrop(q.nchain,q.tmax,q.idealpct,q.annrng);

  //mcmc variables and arrays
  double chi_min=1.0E+4;
  double ptemp[q.nchain][q.nparams];
  double pcurrent[q.nchain][q.nparams];
  double *setvars[q.nparams];
  ParameterSettings pset(q.nparams);

  for(pi=0, p = q.param_inds.begin(); p != q.param_inds.end(); ++p,++pi){
    setvars[pi] = &lpars[*p];
    pcurrent[0][pi] = *setvars[pi];
    pset.set(pi,lmin[*p],lmax[*p],(lmax[*p] - lmin[*p])/6.0,lpars[*p]);
  }
  if(q.vary_cexp){
    setvars[q.cind] = &CE;
    pcurrent[0][q.cind] = *setvars[pi];
    pset.set(q.cind,CEmin,CEmax,(CEmax - CEmin)/6.0,CE);
  }

  for(m=1;m<q.nchain;m++){
    for(pi=0;pi<q.nparams;pi++)
      pcurrent[m][pi] = rng.flat(lmin[*p],lmax[*p]);
  }

  VERBOSE(printf("\n ---------- Beginning MC Burn-in Phase ---------- \n"));
  TERSE(printf("\nBeginning MC Burn-in Phase...\n"));

  for (i=0;i<q.burn_num;i++){
    for (m=0;m<q.nchain;m++){

      for(pi = 0;pi<q.nparams;pi++)
	*(setvars[pi]) = ptemp[m][pi] = rng.gaussian(pcurrent[m][pi],pset.sigma[pi],pset.min[pi],pset.max[pi]);

      VERBOSE(printf("%lu %lu -",(i+1),(m+1)));
      for(pi=0;pi<LUMPARS;pi++)
	VERBOSE(printf(" %5.2lf",lpars[pi]));
      VERBOSE(printf(" %5.2lf : ",(q.vary_cexp ? ptemp[m][q.cind] : CE)));

      lf.set_params(lpars);
      survey.set_color_exp(CE);

      output=survey.simulate();
      trial=output.chisqr;

      VERBOSE(printf("Iteration Chi-Square: %lf",trial));
      if(trial < chi_min){
	VERBOSE(printf(" -- Current Best Trial"));
	chi_min=trial;
	for(pi=0;pi<q.nparams;pi++)
	  pset.best[pi]=ptemp[m][pi];
      }
      VERBOSE(printf("\n"));

      accept = metrop.accept(m,trial);
      if(accept)
	for(pi=0;pi<q.nparams;pi++)
	  pcurrent[m][pi]=ptemp[m][pi];

      burnchain.add_link(m,ptemp[m],trial,accept);
    }

    if(((i+1) % q.burn_step) == 0){
      if(not metrop.anneal())
	i = q.runs;
      if(burnchain.converged()){
	VERBOSE(printf("Burn Chain Converged\n"));
	i = q.runs;}
      burnchain.get_stdev(pset.sigma.data());
    }
  }

  for(m=0;m<q.nchain;m++)
    for(pi=0;pi<q.nparams;pi++)
      pcurrent[m][pi] = pset.best[pi];

  metrop.reset();

  VERBOSE(printf("\n\n ---------------- Fitting Start ---------------- \n Total Run Number: %ld\n\n",q.runs));
  TERSE(printf("\nBeginning Fitting, Run Maximum: %ld\n",q.runs));

  for (i=0;i<q.runs;i++){
    for (m=0;m<q.nchain;m++){

      for(pi = 0;pi<q.nparams;pi++)
	*(setvars[pi]) = ptemp[m][pi] = rng.gaussian(pcurrent[m][pi],pset.sigma[pi],pset.min[pi],pset.max[pi]);

      VERBOSE(printf("%lu %lu -",(i+1),(m+1)));
      for(pi=0;pi<q.nparams;pi++)
	VERBOSE(printf(" %lf",ptemp[m][pi]));
      VERBOSE(printf(" : "));

      lf.set_params(lpars);
      output=survey.simulate();
      trial=output.chisqr;
      VERBOSE(printf("Model Chi-Square: %lf",trial));

      accept = metrop.accept(m,trial);
      survey.set_color_exp(CE);

      mcchain.add_link(m,ptemp[m],trial,accept);
      counts.add_link(output.dnds,trial);

      if(accept){
	VERBOSE(printf(" -- Accepted\n"));
	for(pi=0;pi<q.nparams;pi++)
	  pcurrent[m][pi]=ptemp[m][pi];
      }
      VERBOSE(printf(" -- Rejected\n"));
    }

    if(((i+1) % q.conv_step) == 0){
      printf("Checking Convergence\n");
      if (i < q.burn_num)
	metrop.anneal();
      mcchain.get_stdev(pset.sigma.data());
      if(mcchain.converged()){
	printf("Chains Converged!\n");
	i = q.runs;}
      else
	printf("Chains Have Not Converged\n");
    }
  }

  mcchain.get_best_link(pset.best.data(),chi_min);

  for(pi=0;pi<q.param_inds.size();pi++)
    lpars[q.param_inds[pi]] = pset.best[pi];
  lf.set_params(lpars);
  if(q.vary_cexp)
    survey.set_color_exp(pset.best[q.cind]);

  printf("\nRe-Running Best Fit...\n");
  output=survey.simulate();
  printf("Model chi2: %lf\n",output.chisqr);
  printf("Acceptance Rate: %lf%%\n",metrop.mean_acceptance());

  string pnames[] = {"PHI0","L0","ALPHA","BETA","P","Q","ZCUT"};
  unique_ptr<string[]> parnames (new string[q.nparams]);

  for(pi=0;pi<q.param_inds.size();pi++)
    parnames[pi] = pnames[q.param_inds[pi]];
  if(q.vary_cexp)
    parnames[q.cind] = "CEXP";

  VERBOSE(printf("Saving Survey\n"));
  saved = survey.save(q.outfile);
  VERBOSE(printf("Saving Chains\n"));
  saved &= mcchain.save(q.outfile,parnames.get());
  VERBOSE(printf("Saving Counts\n"));
  saved &= counts.save(q.outfile,countnames);

  saved ? printf("Save Successful") : printf("Save Failed");
  printf("\nFitting Complete\n\n");

  return saved ? 0 : 1;
}

<commit_msg>Updating main, segfaults<commit_after>//****************************************************************************
// written by Anna Sajina and Noah Kurinsky, 2012
// updated by Noah Kurinsky 10/13
// The purpose of this program is to read-in the parameters set in the idl
// wrapper (simulation.pro) and to use MCMC to determine the best-fit set of
// parameters.
// Specifically it runs through a number of iterations (runs) in each stage
// calling on simulator.cpp to compute the chi2 for a given set of parameters
// then the metrop algorithm is invoked to decide whether or not a given trial
// run is accepted. If so it is added to a chain of mcmc values.
//****************************************************************************

#include "simulator.h"
#include "functions.h"
#include "mc_util.h"
#include <stdio.h>

//Array size definitions
#define BANDS 3

#define VERBOSE( ARG ) \
  if(q.oprint){	       \
    ARG;	       \
  }

#define TERSE( ARG )   \
  if(!q.oprint){       \
    ARG;	       \
  }

using namespace std;

int main(int argc,char** argv){

  printf("\nMCMC Fitting Code Compiled: %s\n\n",__DATE__);

  Configuration q(argc,argv);
  VERBOSE(q.print());
  RandomNumberGenerator rng;

  //general variable declarations
  bool accept,saved;
  unsigned long i,m;
  unsigned long pi;
  vector<int>::const_iterator p;
  double trial;

  //this array holds phi0,L0,alpha,beta,p, and q
  double lpars[LUMPARS];
  double lmin[LUMPARS];
  double lmax[LUMPARS];
  q.LFparameters(lpars);
  q.LFparameters(lmin,q.min);
  q.LFparameters(lmax,q.max);
  double CE = q.colorEvolution[q.value];
  double CEmin = q.colorEvolution[q.min];
  double CEmax = q.colorEvolution[q.max];

  //counts
  string countnames[]= {"dnds250","dnds350","dnds500"};

  lumfunct lf;
  lf.set_params(lpars);

  //initialize simulator
  simulator survey(q.filterfile,q.obsfile,q.sedfile);
  survey.set_color_exp(CE); //color evolution
  survey.set_lumfunct(&lf);

  //NON GENERAL COUNTS
  //the flux array is logarithmic in steps of 0.3dex
  q.ns=8;
  survey.set_size(q.areaSteradian(),q.dz,q.zmin,q.nz,q.ns);
  int bnum[]={16,13,10};
  products output(q.nz,bnum);

  MCChains mcchain(q.nchain,q.nparams,q.runs,q.conv_step);
  MCChains burnchain(q.nchain,q.nparams,q.runs,q.conv_step);
  mcchain.set_constraints(q.rmax,q.a_ci);
  burnchain.set_constraints(1.5,0.25);

  ResultChain counts(3,q.nchain*q.runs);

  MetropSampler metrop(q.nchain,q.tmax,q.idealpct,q.annrng);

  //mcmc variables and arrays
  double chi_min=1.0E+4;
  double ptemp[q.nchain][q.nparams];
  double pcurrent[q.nchain][q.nparams];
  double *setvars[q.nparams];
  ParameterSettings pset(q.nparams);

  VERBOSE(printf("Initializing Chains\n"));
  for(pi=0, p = q.param_inds.begin(); p != q.param_inds.end(); ++p,++pi){
    setvars[pi] = &lpars[*p];
    pcurrent[0][pi] = *setvars[pi];
    pset.set(pi,lmin[*p],lmax[*p],(lmax[*p] - lmin[*p])/6.0,lpars[*p]);
  }
  if(q.vary_cexp){
    setvars[q.cind] = &CE;
    pcurrent[0][q.cind] = *setvars[pi];
    pset.set(q.cind,CEmin,CEmax,(CEmax - CEmin)/6.0,CE);
  }

  for(m=1;m<q.nchain;m++){
    for(pi=0;pi<q.nparams;pi++)
      pcurrent[m][pi] = rng.flat(lmin[*p],lmax[*p]);
  }

  VERBOSE(printf("\n ---------- Beginning MC Burn-in Phase ---------- \n"));
  TERSE(printf("\nBeginning MC Burn-in Phase...\n"));

  for (i=0;i<q.burn_num;i++){
    for (m=0;m<q.nchain;m++){

      for(pi = 0;pi<q.nparams;pi++)
	*(setvars[pi]) = ptemp[m][pi] = rng.gaussian(pcurrent[m][pi],pset.sigma[pi],pset.min[pi],pset.max[pi]);

      VERBOSE(printf("%lu %lu -",(i+1),(m+1)));
      for(pi=0;pi<LUMPARS;pi++)
	VERBOSE(printf(" %5.2lf",lpars[pi]));
      VERBOSE(printf(" %5.2lf : ",(q.vary_cexp ? ptemp[m][q.cind] : CE)));

      lf.set_params(lpars);
      survey.set_color_exp(CE);

      output=survey.simulate();
      trial=output.chisqr;

      VERBOSE(printf("Iteration Chi-Square: %lf",trial));
      if(trial < chi_min){
	VERBOSE(printf(" -- Current Best Trial"));
	chi_min=trial;
	for(pi=0;pi<q.nparams;pi++)
	  pset.best[pi]=ptemp[m][pi];
      }
      VERBOSE(printf("\n"));

      accept = metrop.accept(m,trial);
      if(accept)
	for(pi=0;pi<q.nparams;pi++)
	  pcurrent[m][pi]=ptemp[m][pi];

      burnchain.add_link(m,ptemp[m],trial,accept);
    }

    if(((i+1) % q.burn_step) == 0){
      if(not metrop.anneal())
	i = q.runs;
      if(burnchain.converged()){
	VERBOSE(printf("Burn Chain Converged\n"));
	i = q.runs;}
      burnchain.get_stdev(pset.sigma.data());
    }
  }

  for(m=0;m<q.nchain;m++)
    for(pi=0;pi<q.nparams;pi++)
      pcurrent[m][pi] = pset.best[pi];

  metrop.reset();

  VERBOSE(printf("\n\n ---------------- Fitting Start ---------------- \n Total Run Number: %ld\n\n",q.runs));
  TERSE(printf("\nBeginning Fitting, Run Maximum: %ld\n",q.runs));

  for (i=0;i<q.runs;i++){
    for (m=0;m<q.nchain;m++){

      for(pi = 0;pi<q.nparams;pi++)
	*(setvars[pi]) = ptemp[m][pi] = rng.gaussian(pcurrent[m][pi],pset.sigma[pi],pset.min[pi],pset.max[pi]);

      VERBOSE(printf("%lu %lu -",(i+1),(m+1)));
      for(pi=0;pi<q.nparams;pi++)
	VERBOSE(printf(" %lf",ptemp[m][pi]));
      VERBOSE(printf(" : "));

      lf.set_params(lpars);
      output=survey.simulate();
      trial=output.chisqr;
      VERBOSE(printf("Model Chi-Square: %lf",trial));

      accept = metrop.accept(m,trial);
      survey.set_color_exp(CE);

      mcchain.add_link(m,ptemp[m],trial,accept);
      counts.add_link(output.dnds,trial);

      if(accept){
	VERBOSE(printf(" -- Accepted\n"));
	for(pi=0;pi<q.nparams;pi++)
	  pcurrent[m][pi]=ptemp[m][pi];
      }
      VERBOSE(printf(" -- Rejected\n"));
    }

    if(((i+1) % q.conv_step) == 0){
      printf("Checking Convergence\n");
      if (i < q.burn_num)
	metrop.anneal();
      mcchain.get_stdev(pset.sigma.data());
      if(mcchain.converged()){
	printf("Chains Converged!\n");
	i = q.runs;}
      else
	printf("Chains Have Not Converged\n");
    }
  }

  mcchain.get_best_link(pset.best.data(),chi_min);

  for(pi=0;pi<q.param_inds.size();pi++)
    lpars[q.param_inds[pi]] = pset.best[pi];
  lf.set_params(lpars);
  if(q.vary_cexp)
    survey.set_color_exp(pset.best[q.cind]);

  printf("\nRe-Running Best Fit...\n");
  output=survey.simulate();
  printf("Model chi2: %lf\n",output.chisqr);
  printf("Acceptance Rate: %lf%%\n",metrop.mean_acceptance());

  string pnames[] = {"PHI0","L0","ALPHA","BETA","P","Q","ZCUT"};
  unique_ptr<string[]> parnames (new string[q.nparams]);

  for(pi=0;pi<q.param_inds.size();pi++)
    parnames[pi] = pnames[q.param_inds[pi]];
  if(q.vary_cexp)
    parnames[q.cind] = "CEXP";

  VERBOSE(printf("Saving Survey\n"));
  saved = survey.save(q.outfile);
  VERBOSE(printf("Saving Chains\n"));
  saved &= mcchain.save(q.outfile,parnames.get());
  VERBOSE(printf("Saving Counts\n"));
  saved &= counts.save(q.outfile,countnames);

  saved ? printf("Save Successful") : printf("Save Failed");
  printf("\nFitting Complete\n\n");

  return saved ? 0 : 1;
}

<|endoftext|>


<commit_before>#include <UnitTest++/src/UnitTest++.h>
#include "rdestl/vector.h"
#include <cstdio>

struct MyStruct
{
	int i;
	char c;
	float f;
};
namespace rde
{
	template<> struct is_pod<MyStruct>
	{
		enum { value = true };
	};
}

namespace
{
	typedef rde::vector<int>			tTestVector;
	typedef rde::vector<std::string>	tStringVector;

	const int array [] = { 1, 4, 9, 16, 25, 36 };
	void PrintVector(const tTestVector& v)
	{
		for (tTestVector::const_iterator it = v.begin(); it != v.end(); ++it)
			printf("%d, ", *it);
		printf("\n");
	}
	void PrintVector(const tStringVector& v)
	{
		for (tStringVector::const_iterator it = v.begin(); it != v.end(); ++it)
			printf("%s, ", it->c_str());
		printf("\n");
	}

	TEST(DefaultCtorEmpty)
	{
		tTestVector v;
		CHECK(v.empty());
		CHECK_EQUAL(0, v.size());
		CHECK_EQUAL(v.begin(), v.end());
		printf("Sizeof(v) = %d\n", sizeof(v));
	}
	TEST(PushBack)
	{
		tTestVector v;
		v.push_back(2);
		CHECK_EQUAL(1, v.size());
		CHECK_EQUAL(2, v[0]);
		CHECK(!v.empty());
		CHECK(v.begin() != v.end());
	}
	TEST(PopBack)
	{
		tTestVector v;
		v.push_back(2);
		v.push_back(3);
		CHECK_EQUAL(2, v.front());
		CHECK_EQUAL(3, v.back());
		v.pop_back();
		CHECK(!v.empty());
		CHECK_EQUAL(1, v.size());
		CHECK_EQUAL(2, v[0]);
		tTestVector::const_iterator it = v.begin();
		++it;
		CHECK_EQUAL(v.end(), it);
	}
	TEST(AssignTab)
	{
		tTestVector v;
		CHECK(v.empty());
		v.assign(array, array + 6);
		CHECK_EQUAL(6, v.size());
		CHECK_EQUAL(0, memcmp(array, v.data(), sizeof(array)));
	}
	TEST(AssignTabConstruct)
	{
		tTestVector v(array, array + 6);
		CHECK_EQUAL(6, v.size());
		CHECK_EQUAL(0, memcmp(array, v.data(), sizeof(array)));
	}

	TEST(Clear)
	{
		tTestVector v(array, array + 6);
		CHECK_EQUAL(6, v.size());
		v.clear();
		CHECK_EQUAL(0, v.size());
		CHECK(v.empty());
		// Make sure it doesnt free mem.
		CHECK(v.capacity() > 0);
	}

	TEST(EraseBegin)
	{
		tTestVector v(array, array + 6);
		v.erase(v.begin());
		// 4, 9, 16, 25, 36
		CHECK_EQUAL(4, v.front());
	}
	TEST(Erase)
	{
		tTestVector v(array, array + 6);

		// Remove 4 & 9
		tTestVector::iterator it = v.begin();
		it += 1;
		tTestVector::iterator it2 = it;
		it2 += 2;
		v.erase(it, it2);
		CHECK_EQUAL(4, v.size());
		CHECK_EQUAL(1, v.front());
		CHECK_EQUAL(16, v[1]);
		CHECK_EQUAL(25, v[2]);
		CHECK_EQUAL(36, v[3]);
	}
	TEST(EraseSingle)
	{
		tTestVector v(array, array + 6);
		tTestVector::iterator it = v.erase(v.begin() + 1); // 4
		CHECK_EQUAL(9, *it);
		v.erase(it + 1); // 16

		CHECK_EQUAL(4, v.size());
		//PrintVector(v);
	}
	TEST(EraseEnd)
	{
		tTestVector v(array, array + 6);
		tTestVector::iterator it = v.begin();
		it += 2;
		v.erase(it, v.end());
		CHECK_EQUAL(2, v.size());
	}
	TEST(EraseAll)
	{
		tTestVector v(array, array + 6);
		v.erase(v.begin(), v.end());
		CHECK(v.empty());

		rde::vector<MyStruct> v2;
		v2.erase(v2.begin(), v2.end());
	}

	TEST(InsertString)
	{
		tStringVector v;
		v.push_back("brave");
		v.push_back("new");
		v.push_back("world");
		v.insert(0, 1, "Hello");
		CHECK_EQUAL(4, v.size());
		v.insert(4, 3, ".");
		CHECK_EQUAL(7, v.size());
		PrintVector(v);
		v.insert(1, 10, "very");
		CHECK_EQUAL(17, v.size());
		PrintVector(v);
	}

	TEST(EraseString)
	{
		tStringVector v;
		v.push_back("Hello");
		v.push_back("brave");
		v.push_back("new");
		v.push_back("world");
		CHECK_EQUAL(4, v.size());
		v.erase(v.begin() + 1, v.end() - 1);
		CHECK_EQUAL(2, v.size());
	}
	TEST(IndexOf)
	{
		tStringVector v;
		v.push_back("Hello");
		v.push_back("brave");
		v.push_back("new");
		v.push_back("world");
		CHECK_EQUAL(2, v.index_of("new"));
		CHECK_EQUAL(tStringVector::npos, v.index_of("blah"));
		CHECK_EQUAL(tStringVector::npos, v.index_of("brave", 2));
	}

	TEST(InsertFront)
	{
		tTestVector v(array, array + 6);
		v.insert(v.begin(), 2, -1);
		CHECK_EQUAL(8, v.size());
		CHECK_EQUAL(-1, v.front());
		CHECK_EQUAL(-1, v[1]);
		CHECK_EQUAL(1, v[2]);
		CHECK_EQUAL(4, v[3]);
		CHECK_EQUAL(36, v[7]);
	}
	TEST(InsertMiddle)
	{
		tTestVector v(array, array + 6);
		tTestVector::iterator it = v.begin() + 2;
		v.insert(it, 3, 5);
		CHECK_EQUAL(9, v.size());
		CHECK_EQUAL(5, v[2]);
		it = v.begin() + 2;
		v.insert(it, 4);
		CHECK_EQUAL(4, v[2]);
	}
	TEST(InsertEnd)
	{
		tTestVector v(array, array + 6);
		v.insert(v.end(), 1, 49);
		CHECK_EQUAL(7, v.size());
		CHECK_EQUAL(49, v[6]);
	}
	TEST(InsertToEmpty)
	{
		tTestVector v;
		v.insert(v.begin(), 1, 2);
		CHECK_EQUAL(1, v.size());
		CHECK_EQUAL(2, v.front());
	}

	TEST(ResizeSmaller)
	{
		tTestVector v(array, array + 6);
		v.resize(4);
		CHECK_EQUAL(4, v.size());
		CHECK_EQUAL(16, v[3]);
	}

	TEST(CopyConstructor)
	{
		tTestVector v(array, array + 6);
		tTestVector v2(v);
		CHECK_EQUAL(6, v2.size());
		CHECK(memcmp(v.begin(), v2.begin(), 6*sizeof(int)) == 0);
	}

	TEST(AssignmentOp)
	{
		tTestVector v(array, array + 6);
		tTestVector v2;
		v2 = v;
		CHECK_EQUAL(6, v2.size());
		CHECK(memcmp(v.begin(), v2.begin(), 6*sizeof(int)) == 0);
	}

	TEST(Tighten)
	{
		tTestVector v(array, array + 6);
		v.push_back(49);
		v.set_capacity(v.size());
		CHECK_EQUAL(7, v.capacity());
	}
	TEST(Reserve)
	{
		tTestVector v;
		CHECK_EQUAL(0, v.capacity());
		v.push_back(1); v.push_back(2); v.push_back(3);
		v.reserve(10);
		CHECK(v.capacity() >= 10);
		CHECK_EQUAL(3, v.size());
		CHECK_EQUAL(1, v[0]);
		CHECK_EQUAL(2, v[1]);
		CHECK_EQUAL(3, v[2]);
	}

	TEST(CopyEmpty)
	{
		tTestVector v;
		v.push_back(1); v.push_back(2); v.push_back(3);
		tTestVector v2;
		v = v2;
		CHECK(v.empty());
	}

    //-----------------------------------------------------------------
    //Vector tests by Danushka Abeysuriya silvermace@gmail.com

    TEST(Resize)
    {
        rde::vector<int> myFoos;
        myFoos.resize(20);

        CHECK(myFoos.size() == 20);
        CHECK(myFoos.capacity() >= 20);
    }

    //Regression test:
    //The bug is caused when the copy constructor is invoked on a vector where
    //the rhs is an empty (and non-preallocated) vector - i.e. there is nothing to copy
    TEST(Resize_Regression_1)
    {
        rde::vector< rde::vector<int> > myFoosFoos;
        myFoosFoos.push_back(rde::vector<int>());
        myFoosFoos.push_back(rde::vector<int>());
        myFoosFoos[1].push_back(42);

        CHECK(myFoosFoos.size() == 2);
        CHECK(myFoosFoos[0].size() == 0);
        CHECK(myFoosFoos[1].size() == 1);
    }

    TEST(Resize_Regression_2)
    {
        rde::vector< rde::vector<int> > myFoosFoos;
        rde::vector<int> a;
        rde::vector<int> b;

        a.push_back(42);
        a.push_back(24);

        myFoosFoos.push_back(a);
        myFoosFoos.push_back(b);
        myFoosFoos[1].push_back(4224);

        CHECK(myFoosFoos.size() == 2);

        CHECK(myFoosFoos[0].size() == 2);
        CHECK(myFoosFoos[0][0] == 42);
        CHECK(myFoosFoos[0][1] == 24);

        CHECK(myFoosFoos[1].size() == 1);
        CHECK(myFoosFoos[1][0] == 4224);
    }

    TEST(Insert)
    {
        rde::vector<int> myFoos;

        myFoos.push_back(42);
        CHECK(myFoos.size() == 1);
        CHECK(myFoos[0] == 42);

        myFoos.insert(myFoos.begin(), 24);
        CHECK(myFoos.size() == 2);
        CHECK(myFoos[0] == 24);
        CHECK(myFoos[1] == 42);

        myFoos.clear();
        CHECK(myFoos.size() == 0);

        myFoos.insert(myFoos.begin(), 42);
        CHECK(myFoos.size() == 1);
        CHECK(myFoos[0] == 42);
    }

    TEST(VectorOfVectors)
    {
        rde::vector< rde::vector<int> > myFoosFoos;
        myFoosFoos.push_back(rde::vector<int>(10));
        myFoosFoos.push_back(rde::vector<int>(20));
        CHECK(myFoosFoos.size() == 2);
        CHECK(myFoosFoos[0].size() == 10);
        CHECK(myFoosFoos[1].size() == 20);
    }

    //typedef rde::fixed_vector<int, 3, false> fvector;

    //TEST(fixedvec_copy)
    //{
    //    fvector a;
    //    fvector b;
    //    a.push_back(42);
    //    a.push_back(24);
    //    a.push_back(4224);
    //
    //    b = a;
    //
    //    CHECK(b.size() == 3);
    //    CHECK(b[0] == 42);
    //    CHECK(b[1] == 24);
    //    CHECK(b[2] == 4224);
    //
    //    b = fvector();
    //    CHECK(b.size() == 3);
    //}
}
<commit_msg>Two vector tests added<commit_after>#include <UnitTest++/src/UnitTest++.h>
#include "rdestl/vector.h"
#include <cstdio>

struct MyStruct
{
	int i;
	char c;
	float f;
};
namespace rde
{
	template<> struct is_pod<MyStruct>
	{
		enum { value = true };
	};
}

namespace
{
	typedef rde::vector<int>			tTestVector;
	typedef rde::vector<std::string>	tStringVector;

	const int array [] = { 1, 4, 9, 16, 25, 36 };
	void PrintVector(const tTestVector& v)
	{
		for (tTestVector::const_iterator it = v.begin(); it != v.end(); ++it)
			printf("%d, ", *it);
		printf("\n");
	}
	void PrintVector(const tStringVector& v)
	{
		for (tStringVector::const_iterator it = v.begin(); it != v.end(); ++it)
			printf("%s, ", it->c_str());
		printf("\n");
	}

	TEST(DefaultCtorEmpty)
	{
		tTestVector v;
		CHECK(v.empty());
		CHECK_EQUAL(0, v.size());
		CHECK_EQUAL(v.begin(), v.end());
		printf("Sizeof(v) = %d\n", sizeof(v));
	}
	TEST(PushBack)
	{
		tTestVector v;
		v.push_back(2);
		CHECK_EQUAL(1, v.size());
		CHECK_EQUAL(2, v[0]);
		CHECK(!v.empty());
		CHECK(v.begin() != v.end());
	}
	TEST(PopBack)
	{
		tTestVector v;
		v.push_back(2);
		v.push_back(3);
		CHECK_EQUAL(2, v.front());
		CHECK_EQUAL(3, v.back());
		v.pop_back();
		CHECK(!v.empty());
		CHECK_EQUAL(1, v.size());
		CHECK_EQUAL(2, v[0]);
		tTestVector::const_iterator it = v.begin();
		++it;
		CHECK_EQUAL(v.end(), it);
	}
	TEST(AssignTab)
	{
		tTestVector v;
		CHECK(v.empty());
		v.assign(array, array + 6);
		CHECK_EQUAL(6, v.size());
		CHECK_EQUAL(0, memcmp(array, v.data(), sizeof(array)));
	}
	TEST(AssignTabConstruct)
	{
		tTestVector v(array, array + 6);
		CHECK_EQUAL(6, v.size());
		CHECK_EQUAL(0, memcmp(array, v.data(), sizeof(array)));
	}

	TEST(Clear)
	{
		tTestVector v(array, array + 6);
		CHECK_EQUAL(6, v.size());
		v.clear();
		CHECK_EQUAL(0, v.size());
		CHECK(v.empty());
		// Make sure it doesnt free mem.
		CHECK(v.capacity() > 0);
	}

	TEST(EraseBegin)
	{
		tTestVector v(array, array + 6);
		v.erase(v.begin());
		// 4, 9, 16, 25, 36
		CHECK_EQUAL(4, v.front());
	}
	TEST(Erase)
	{
		tTestVector v(array, array + 6);

		// Remove 4 & 9
		tTestVector::iterator it = v.begin();
		it += 1;
		tTestVector::iterator it2 = it;
		it2 += 2;
		v.erase(it, it2);
		CHECK_EQUAL(4, v.size());
		CHECK_EQUAL(1, v.front());
		CHECK_EQUAL(16, v[1]);
		CHECK_EQUAL(25, v[2]);
		CHECK_EQUAL(36, v[3]);
	}
	TEST(EraseSingle)
	{
		tTestVector v(array, array + 6);
		tTestVector::iterator it = v.erase(v.begin() + 1); // 4
		CHECK_EQUAL(9, *it);
		v.erase(it + 1); // 16

		CHECK_EQUAL(4, v.size());
		//PrintVector(v);
	}
	TEST(EraseEnd)
	{
		tTestVector v(array, array + 6);
		tTestVector::iterator it = v.begin();
		it += 2;
		v.erase(it, v.end());
		CHECK_EQUAL(2, v.size());
	}
	TEST(EraseAll)
	{
		tTestVector v(array, array + 6);
		v.erase(v.begin(), v.end());
		CHECK(v.empty());

		rde::vector<MyStruct> v2;
		v2.erase(v2.begin(), v2.end());
	}

	TEST(InsertString)
	{
		tStringVector v;
		v.push_back("brave");
		v.push_back("new");
		v.push_back("world");
		v.insert(0, 1, "Hello");
		CHECK_EQUAL(4, v.size());
		v.insert(4, 3, ".");
		CHECK_EQUAL(7, v.size());
		PrintVector(v);
		v.insert(1, 10, "very");
		CHECK_EQUAL(17, v.size());
		PrintVector(v);
	}

	TEST(EraseString)
	{
		tStringVector v;
		v.push_back("Hello");
		v.push_back("brave");
		v.push_back("new");
		v.push_back("world");
		CHECK_EQUAL(4, v.size());
		v.erase(v.begin() + 1, v.end() - 1);
		CHECK_EQUAL(2, v.size());
	}
	TEST(IndexOf)
	{
		tStringVector v;
		v.push_back("Hello");
		v.push_back("brave");
		v.push_back("new");
		v.push_back("world");
		CHECK_EQUAL(2, v.index_of("new"));
		CHECK_EQUAL(tStringVector::npos, v.index_of("blah"));
		CHECK_EQUAL(tStringVector::npos, v.index_of("brave", 2));
	}

	TEST(InsertFront)
	{
		tTestVector v(array, array + 6);
		v.insert(v.begin(), 2, -1);
		CHECK_EQUAL(8, v.size());
		CHECK_EQUAL(-1, v.front());
		CHECK_EQUAL(-1, v[1]);
		CHECK_EQUAL(1, v[2]);
		CHECK_EQUAL(4, v[3]);
		CHECK_EQUAL(36, v[7]);
	}
	TEST(InsertMiddle)
	{
		tTestVector v(array, array + 6);
		tTestVector::iterator it = v.begin() + 2;
		v.insert(it, 3, 5);
		CHECK_EQUAL(9, v.size());
		CHECK_EQUAL(5, v[2]);
		it = v.begin() + 2;
		v.insert(it, 4);
		CHECK_EQUAL(4, v[2]);
	}
	TEST(InsertEnd)
	{
		tTestVector v(array, array + 6);
		v.insert(v.end(), 1, 49);
		CHECK_EQUAL(7, v.size());
		CHECK_EQUAL(49, v[6]);
	}

	TEST(InsertEndRealloc)
	{
		tTestVector v;
		for (tTestVector::size_type i = 0; i < v.capacity(); ++i)
		{
			v.push_back((int)i);
		}
		v.insert(v.end(), 666);
		CHECK_EQUAL(666, v.back());
	}

	TEST(InsertToEmpty)
	{
		tTestVector v;
		v.insert(v.begin(), 1, 2);
		CHECK_EQUAL(1, v.size());
		CHECK_EQUAL(2, v.front());
	}

	TEST(ResizeSmaller)
	{
		tTestVector v(array, array + 6);
		v.resize(4);
		CHECK_EQUAL(4, v.size());
		CHECK_EQUAL(16, v[3]);
	}

	TEST(CopyConstructor)
	{
		tTestVector v(array, array + 6);
		tTestVector v2(v);
		CHECK_EQUAL(6, v2.size());
		CHECK(memcmp(v.begin(), v2.begin(), 6*sizeof(int)) == 0);
	}

	TEST(AssignmentOp)
	{
		tTestVector v(array, array + 6);
		tTestVector v2;
		v2 = v;
		CHECK_EQUAL(6, v2.size());
		CHECK(memcmp(v.begin(), v2.begin(), 6*sizeof(int)) == 0);
	}

	TEST(Tighten)
	{
		tTestVector v(array, array + 6);
		v.push_back(49);
		v.set_capacity(v.size());
		CHECK_EQUAL(7, v.capacity());
	}
	TEST(Reserve)
	{
		tTestVector v;
		CHECK_EQUAL(0, v.capacity());
		v.push_back(1); v.push_back(2); v.push_back(3);
		v.reserve(10);
		CHECK(v.capacity() >= 10);
		CHECK_EQUAL(3, v.size());
		CHECK_EQUAL(1, v[0]);
		CHECK_EQUAL(2, v[1]);
		CHECK_EQUAL(3, v[2]);
	}

	TEST(CopyEmpty)
	{
		tTestVector v;
		v.push_back(1); v.push_back(2); v.push_back(3);
		tTestVector v2;
		v = v2;
		CHECK(v.empty());
	}

	// Force few grows
	TEST(MultipleGrow)
	{
		tTestVector v;
		for (int i = 0; i < 5000; ++i)
		{
			v.push_back(i);
		}
		CHECK_EQUAL(5000, v.size());
		for (int i = 0; i < 5000; ++i)
		{
			CHECK_EQUAL(i, v[i]);
		}
	}

    //-----------------------------------------------------------------
    //Vector tests by Danushka Abeysuriya silvermace@gmail.com

    TEST(Resize)
    {
        rde::vector<int> myFoos;
        myFoos.resize(20);

        CHECK(myFoos.size() == 20);
        CHECK(myFoos.capacity() >= 20);
    }

    //Regression test:
    //The bug is caused when the copy constructor is invoked on a vector where
    //the rhs is an empty (and non-preallocated) vector - i.e. there is nothing to copy
    TEST(Resize_Regression_1)
    {
        rde::vector< rde::vector<int> > myFoosFoos;
        myFoosFoos.push_back(rde::vector<int>());
        myFoosFoos.push_back(rde::vector<int>());
        myFoosFoos[1].push_back(42);

        CHECK(myFoosFoos.size() == 2);
        CHECK(myFoosFoos[0].size() == 0);
        CHECK(myFoosFoos[1].size() == 1);
    }

    TEST(Resize_Regression_2)
    {
        rde::vector< rde::vector<int> > myFoosFoos;
        rde::vector<int> a;
        rde::vector<int> b;

        a.push_back(42);
        a.push_back(24);

        myFoosFoos.push_back(a);
        myFoosFoos.push_back(b);
        myFoosFoos[1].push_back(4224);

        CHECK(myFoosFoos.size() == 2);

        CHECK(myFoosFoos[0].size() == 2);
        CHECK(myFoosFoos[0][0] == 42);
        CHECK(myFoosFoos[0][1] == 24);

        CHECK(myFoosFoos[1].size() == 1);
        CHECK(myFoosFoos[1][0] == 4224);
    }

    TEST(Insert)
    {
        rde::vector<int> myFoos;

        myFoos.push_back(42);
        CHECK(myFoos.size() == 1);
        CHECK(myFoos[0] == 42);

        myFoos.insert(myFoos.begin(), 24);
        CHECK(myFoos.size() == 2);
        CHECK(myFoos[0] == 24);
        CHECK(myFoos[1] == 42);

        myFoos.clear();
        CHECK(myFoos.size() == 0);

        myFoos.insert(myFoos.begin(), 42);
        CHECK(myFoos.size() == 1);
        CHECK(myFoos[0] == 42);
    }

    TEST(VectorOfVectors)
    {
        rde::vector< rde::vector<int> > myFoosFoos;
        myFoosFoos.push_back(rde::vector<int>(10));
        myFoosFoos.push_back(rde::vector<int>(20));
        CHECK(myFoosFoos.size() == 2);
        CHECK(myFoosFoos[0].size() == 10);
        CHECK(myFoosFoos[1].size() == 20);
    }

    //typedef rde::fixed_vector<int, 3, false> fvector;

    //TEST(fixedvec_copy)
    //{
    //    fvector a;
    //    fvector b;
    //    a.push_back(42);
    //    a.push_back(24);
    //    a.push_back(4224);
    //
    //    b = a;
    //
    //    CHECK(b.size() == 3);
    //    CHECK(b[0] == 42);
    //    CHECK(b[1] == 24);
    //    CHECK(b[2] == 4224);
    //
    //    b = fvector();
    //    CHECK(b.size() == 3);
    //}
}
<|endoftext|>


<commit_before>/*

openfx-arena - https://github.com/olear/openfx-arena

Copyright (c) 2015, Ole-André Rodlie <olear@fxarena.net>
Copyright (c) 2015, FxArena DA <mail@fxarena.net>
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
  list of conditions and the following disclaimer.

* Neither the name of FxArena DA nor the names of its
  contributors may be used to endorse or promote products derived from
  this software without specific prior written permission.

* Redistributions in binary form must reproduce the above copyright notice,
  this list of conditions and the following disclaimer in the documentation
  and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*/

#include "Texture.h"
#include "ofxsMacros.h"
#include <Magick++.h>

#define kPluginName "Texture"
#define kPluginGrouping "Draw"

#define kPluginIdentifier "net.fxarena.openfx.Texture"
#define kPluginVersionMajor 2
#define kPluginVersionMinor 1

#define kSupportsTiles 0
#define kSupportsMultiResolution 0
#define kSupportsRenderScale 1
#define kRenderThreadSafety eRenderInstanceSafe

#define kParamEffect "background"
#define kParamEffectLabel "Background"
#define kParamEffectHint "Background type"
#define kParamEffectDefault 6

#define kParamSeed "seed"
#define kParamSeedLabel "Seed"
#define kParamSeedHint "Seed the random generator"
#define kParamSeedDefault 4321

using namespace OFX;

class TexturePlugin : public OFX::ImageEffect
{
public:
    TexturePlugin(OfxImageEffectHandle handle);
    virtual ~TexturePlugin();
    virtual void render(const OFX::RenderArguments &args) OVERRIDE FINAL;
    virtual bool getRegionOfDefinition(const OFX::RegionOfDefinitionArguments &args, OfxRectD &rod) OVERRIDE FINAL;
private:
    OFX::Clip *dstClip_;
    OFX::ChoiceParam *effect_;
    OFX::IntParam *seed_;
};

TexturePlugin::TexturePlugin(OfxImageEffectHandle handle)
: OFX::ImageEffect(handle)
, dstClip_(0)
{
    Magick::InitializeMagick(NULL);

    dstClip_ = fetchClip(kOfxImageEffectOutputClipName);
    assert(dstClip_ && (dstClip_->getPixelComponents() == OFX::ePixelComponentRGBA || dstClip_->getPixelComponents() == OFX::ePixelComponentRGB));

    effect_ = fetchChoiceParam(kParamEffect);
    seed_ = fetchIntParam(kParamSeed);
    assert(effect_ && seed_);
}

TexturePlugin::~TexturePlugin()
{
}

/* Override the render */
void TexturePlugin::render(const OFX::RenderArguments &args)
{
    if (!kSupportsRenderScale && (args.renderScale.x != 1. || args.renderScale.y != 1.)) {
        OFX::throwSuiteStatusException(kOfxStatFailed);
        return;
    }

    if (!dstClip_) {
        OFX::throwSuiteStatusException(kOfxStatFailed);
        return;
    }
    assert(dstClip_);

    std::auto_ptr<OFX::Image> dstImg(dstClip_->fetchImage(args.time));
    if (!dstImg.get()) {
        OFX::throwSuiteStatusException(kOfxStatFailed);
        return;
    }

    if (dstImg->getRenderScale().x != args.renderScale.x ||
        dstImg->getRenderScale().y != args.renderScale.y ||
        dstImg->getField() != args.fieldToRender) {
        setPersistentMessage(OFX::Message::eMessageError, "", "OFX Host gave image with wrong scale or field properties");
        OFX::throwSuiteStatusException(kOfxStatFailed);
        return;
    }

    OFX::BitDepthEnum dstBitDepth = dstImg->getPixelDepth();
    if (dstBitDepth != OFX::eBitDepthFloat && dstBitDepth != OFX::eBitDepthUShort && dstBitDepth != OFX::eBitDepthUByte) {
        OFX::throwSuiteStatusException(kOfxStatErrFormat);
        return;
    }

    OFX::PixelComponentEnum dstComponents  = dstImg->getPixelComponents();
    if ((dstComponents != OFX::ePixelComponentRGBA && dstComponents != OFX::ePixelComponentRGB && dstComponents != OFX::ePixelComponentAlpha)) {
        OFX::throwSuiteStatusException(kOfxStatErrFormat);
        return;
    }

    // are we in the image bounds
    OfxRectI dstBounds = dstImg->getBounds();
    OfxRectI dstRod = dstImg->getRegionOfDefinition();
    if(args.renderWindow.x1 < dstBounds.x1 || args.renderWindow.x1 >= dstBounds.x2 || args.renderWindow.y1 < dstBounds.y1 || args.renderWindow.y1 >= dstBounds.y2 ||
       args.renderWindow.x2 <= dstBounds.x1 || args.renderWindow.x2 > dstBounds.x2 || args.renderWindow.y2 <= dstBounds.y1 || args.renderWindow.y2 > dstBounds.y2) {
        OFX::throwSuiteStatusException(kOfxStatErrValue);
        return;
    }

    // Get params
    int effect,seed;
    effect_->getValueAtTime(args.time, effect);
    seed_->getValueAtTime(args.time, seed);

    // Generate empty image
    int width = dstRod.x2-dstRod.x1;
    int height = dstRod.y2-dstRod.y1;
    Magick::Image image(Magick::Geometry(width,height),Magick::Color("rgba(0,0,0,0)"));

    // Set seed
    if (seed!=0)
        Magick::SetRandomSeed(seed);

    // generate background
    switch (effect) {
    case 0: // Plasma
        image.read("plasma:");
        break;
    case 1: // Plasma
        image.read("plasma:grey-grey");
        break;
    case 2: // Plasma
        image.read("plasma:white-blue");
        break;
    case 3: // Plasma
        image.read("plasma:green-yellow");
        break;
    case 4: // Plasma
        image.read("plasma:red-blue");
        break;
    case 5: // Plasma
        image.read("plasma:tomato-steelblue");
        break;
    case 6: // Plasma Fractal
        image.read("plasma:fractal");
        break;
    case 7: // GaussianNoise
        image.addNoise(Magick::GaussianNoise);
        break;
    case 8: // ImpulseNoise
        image.addNoise(Magick::ImpulseNoise);
        break;
    case 9: // LaplacianNoise
        image.addNoise(Magick::LaplacianNoise);
        break;
    case 10: // checkerboard
        image.read("pattern:checkerboard");
        break;
    case 11: // bricks
        image.read("pattern:bricks");
        break;
    }

    // return image
    if (dstClip_ && dstClip_->isConnected())
        image.write(0,0,width,height,"RGBA",Magick::FloatPixel,(float*)dstImg->getPixelData());
}

bool TexturePlugin::getRegionOfDefinition(const OFX::RegionOfDefinitionArguments &args, OfxRectD &rod)
{
    if (!kSupportsRenderScale && (args.renderScale.x != 1. || args.renderScale.y != 1.)) {
        OFX::throwSuiteStatusException(kOfxStatFailed);
        return false;
    }

    rod.x1 = rod.y1 = kOfxFlagInfiniteMin;
    rod.x2 = rod.y2 = kOfxFlagInfiniteMax;

    return true;
}

mDeclarePluginFactory(TexturePluginFactory, {}, {});

/** @brief The basic describe function, passed a plugin descriptor */
void TexturePluginFactory::describe(OFX::ImageEffectDescriptor &desc)
{
    // basic labels
    desc.setLabel(kPluginName);
    desc.setPluginGrouping(kPluginGrouping);
    std::string magickV = MagickCore::GetMagickVersion(NULL);
    std::string delegates = MagickCore::GetMagickDelegates();
    desc.setPluginDescription("Texture/Background generator for Natron.\n\nWritten by Ole-André Rodlie <olear@fxarena.net>\n\n Powered by "+magickV+"\n\nFeatures: "+delegates);

    // add the supported contexts
    desc.addSupportedContext(eContextGeneral);
    desc.addSupportedContext(eContextGenerator);

    // add supported pixel depths
    desc.addSupportedBitDepth(eBitDepthFloat);

    desc.setSupportsTiles(kSupportsTiles);
    desc.setSupportsMultiResolution(kSupportsMultiResolution);
    desc.setRenderThreadSafety(kRenderThreadSafety);
}

/** @brief The describe in context function, passed a plugin descriptor and a context */
void TexturePluginFactory::describeInContext(OFX::ImageEffectDescriptor &desc, ContextEnum /*context*/)
{
    // there has to be an input clip, even for generators
    ClipDescriptor* srcClip = desc.defineClip(kOfxImageEffectSimpleSourceClipName);
    srcClip->addSupportedComponent(ePixelComponentRGBA);
    srcClip->setSupportsTiles(kSupportsTiles);
    srcClip->setOptional(true);

    // create the mandated output clip
    ClipDescriptor *dstClip = desc.defineClip(kOfxImageEffectOutputClipName);
    dstClip->addSupportedComponent(ePixelComponentRGBA);
    dstClip->setSupportsTiles(kSupportsTiles);

    // make some pages
    PageParamDescriptor *page = desc.definePageParam(kPluginName);
    {
        ChoiceParamDescriptor *param = desc.defineChoiceParam(kParamEffect);
        param->setLabel(kParamEffectLabel);
        param->setHint(kParamEffectHint);
        param->appendOption("Plasma");
        param->appendOption("Plasma grey-grey");
        param->appendOption("Plasma white-blue");
        param->appendOption("Plasma green-yellow");
        param->appendOption("Plasma red-blue");
        param->appendOption("Plasma tomato-steelblue");
        param->appendOption("Plasma Fractal");
        param->appendOption("GaussianNoise");
        param->appendOption("ImpulseNoise");
        param->appendOption("LaplacianNoise");
        param->appendOption("Checkerboard");
        param->appendOption("Bricks");
        param->setDefault(kParamEffectDefault);
        param->setAnimates(true);
        page->addChild(*param);
    }
    {
        IntParamDescriptor *param = desc.defineIntParam(kParamSeed);
        param->setLabel(kParamSeedLabel);
        param->setHint(kParamSeedHint);
        param->setRange(0, 10000);
        param->setDisplayRange(0, 5000);
        param->setDefault(kParamSeedDefault);
        page->addChild(*param);
    }
}

/** @brief The create instance function, the plugin must return an object derived from the \ref OFX::ImageEffect class */
ImageEffect* TexturePluginFactory::createInstance(OfxImageEffectHandle handle, ContextEnum /*context*/)
{
    return new TexturePlugin(handle);
}

void getTexturePluginID(OFX::PluginFactoryArray &ids)
{
    static TexturePluginFactory p(kPluginIdentifier, kPluginVersionMajor, kPluginVersionMinor);
    ids.push_back(&p);
}
<commit_msg>Texture: added stripes background, issue #70<commit_after>/*

openfx-arena - https://github.com/olear/openfx-arena

Copyright (c) 2015, Ole-André Rodlie <olear@fxarena.net>
Copyright (c) 2015, FxArena DA <mail@fxarena.net>
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
  list of conditions and the following disclaimer.

* Neither the name of FxArena DA nor the names of its
  contributors may be used to endorse or promote products derived from
  this software without specific prior written permission.

* Redistributions in binary form must reproduce the above copyright notice,
  this list of conditions and the following disclaimer in the documentation
  and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*/

#include "Texture.h"
#include "ofxsMacros.h"
#include <Magick++.h>

#define kPluginName "Texture"
#define kPluginGrouping "Draw"

#define kPluginIdentifier "net.fxarena.openfx.Texture"
#define kPluginVersionMajor 2
#define kPluginVersionMinor 2

#define kSupportsTiles 0
#define kSupportsMultiResolution 0
#define kSupportsRenderScale 1
#define kRenderThreadSafety eRenderInstanceSafe

#define kParamEffect "background"
#define kParamEffectLabel "Background"
#define kParamEffectHint "Background type"
#define kParamEffectDefault 6

#define kParamSeed "seed"
#define kParamSeedLabel "Seed"
#define kParamSeedHint "Seed the random generator"
#define kParamSeedDefault 4321

using namespace OFX;

class TexturePlugin : public OFX::ImageEffect
{
public:
    TexturePlugin(OfxImageEffectHandle handle);
    virtual ~TexturePlugin();
    virtual void render(const OFX::RenderArguments &args) OVERRIDE FINAL;
    virtual bool getRegionOfDefinition(const OFX::RegionOfDefinitionArguments &args, OfxRectD &rod) OVERRIDE FINAL;
private:
    OFX::Clip *dstClip_;
    OFX::ChoiceParam *effect_;
    OFX::IntParam *seed_;
};

TexturePlugin::TexturePlugin(OfxImageEffectHandle handle)
: OFX::ImageEffect(handle)
, dstClip_(0)
{
    Magick::InitializeMagick(NULL);

    dstClip_ = fetchClip(kOfxImageEffectOutputClipName);
    assert(dstClip_ && (dstClip_->getPixelComponents() == OFX::ePixelComponentRGBA || dstClip_->getPixelComponents() == OFX::ePixelComponentRGB));

    effect_ = fetchChoiceParam(kParamEffect);
    seed_ = fetchIntParam(kParamSeed);
    assert(effect_ && seed_);
}

TexturePlugin::~TexturePlugin()
{
}

/* Override the render */
void TexturePlugin::render(const OFX::RenderArguments &args)
{
    if (!kSupportsRenderScale && (args.renderScale.x != 1. || args.renderScale.y != 1.)) {
        OFX::throwSuiteStatusException(kOfxStatFailed);
        return;
    }

    if (!dstClip_) {
        OFX::throwSuiteStatusException(kOfxStatFailed);
        return;
    }
    assert(dstClip_);

    std::auto_ptr<OFX::Image> dstImg(dstClip_->fetchImage(args.time));
    if (!dstImg.get()) {
        OFX::throwSuiteStatusException(kOfxStatFailed);
        return;
    }

    if (dstImg->getRenderScale().x != args.renderScale.x ||
        dstImg->getRenderScale().y != args.renderScale.y ||
        dstImg->getField() != args.fieldToRender) {
        setPersistentMessage(OFX::Message::eMessageError, "", "OFX Host gave image with wrong scale or field properties");
        OFX::throwSuiteStatusException(kOfxStatFailed);
        return;
    }

    OFX::BitDepthEnum dstBitDepth = dstImg->getPixelDepth();
    if (dstBitDepth != OFX::eBitDepthFloat && dstBitDepth != OFX::eBitDepthUShort && dstBitDepth != OFX::eBitDepthUByte) {
        OFX::throwSuiteStatusException(kOfxStatErrFormat);
        return;
    }

    OFX::PixelComponentEnum dstComponents  = dstImg->getPixelComponents();
    if ((dstComponents != OFX::ePixelComponentRGBA && dstComponents != OFX::ePixelComponentRGB && dstComponents != OFX::ePixelComponentAlpha)) {
        OFX::throwSuiteStatusException(kOfxStatErrFormat);
        return;
    }

    // are we in the image bounds
    OfxRectI dstBounds = dstImg->getBounds();
    OfxRectI dstRod = dstImg->getRegionOfDefinition();
    if(args.renderWindow.x1 < dstBounds.x1 || args.renderWindow.x1 >= dstBounds.x2 || args.renderWindow.y1 < dstBounds.y1 || args.renderWindow.y1 >= dstBounds.y2 ||
       args.renderWindow.x2 <= dstBounds.x1 || args.renderWindow.x2 > dstBounds.x2 || args.renderWindow.y2 <= dstBounds.y1 || args.renderWindow.y2 > dstBounds.y2) {
        OFX::throwSuiteStatusException(kOfxStatErrValue);
        return;
    }

    // Get params
    int effect,seed;
    effect_->getValueAtTime(args.time, effect);
    seed_->getValueAtTime(args.time, seed);

    // Generate empty image
    int width = dstRod.x2-dstRod.x1;
    int height = dstRod.y2-dstRod.y1;
    Magick::Image image(Magick::Geometry(width,height),Magick::Color("rgba(0,0,0,0)"));

    // Set seed
    if (seed!=0)
        Magick::SetRandomSeed(seed);

    // generate background
    switch (effect) {
    case 0: // Plasma
        image.read("plasma:");
        break;
    case 1: // Plasma
        image.read("plasma:grey-grey");
        break;
    case 2: // Plasma
        image.read("plasma:white-blue");
        break;
    case 3: // Plasma
        image.read("plasma:green-yellow");
        break;
    case 4: // Plasma
        image.read("plasma:red-blue");
        break;
    case 5: // Plasma
        image.read("plasma:tomato-steelblue");
        break;
    case 6: // Plasma Fractal
        image.read("plasma:fractal");
        break;
    case 7: // GaussianNoise
        image.addNoise(Magick::GaussianNoise);
        break;
    case 8: // ImpulseNoise
        image.addNoise(Magick::ImpulseNoise);
        break;
    case 9: // LaplacianNoise
        image.addNoise(Magick::LaplacianNoise);
        break;
    case 10: // checkerboard
        image.read("pattern:checkerboard");
        break;
    case 11: // stripes
        image.extent(Magick::Geometry(width,1));
        image.addNoise(Magick::GaussianNoise);
        image.channel(Magick::GreenChannel);
        image.negate();
        image.scale(Magick::Geometry(width,height));
        break;
    }

    // return image
    if (dstClip_ && dstClip_->isConnected())
        image.write(0,0,width,height,"RGBA",Magick::FloatPixel,(float*)dstImg->getPixelData());
}

bool TexturePlugin::getRegionOfDefinition(const OFX::RegionOfDefinitionArguments &args, OfxRectD &rod)
{
    if (!kSupportsRenderScale && (args.renderScale.x != 1. || args.renderScale.y != 1.)) {
        OFX::throwSuiteStatusException(kOfxStatFailed);
        return false;
    }

    rod.x1 = rod.y1 = kOfxFlagInfiniteMin;
    rod.x2 = rod.y2 = kOfxFlagInfiniteMax;

    return true;
}

mDeclarePluginFactory(TexturePluginFactory, {}, {});

/** @brief The basic describe function, passed a plugin descriptor */
void TexturePluginFactory::describe(OFX::ImageEffectDescriptor &desc)
{
    // basic labels
    desc.setLabel(kPluginName);
    desc.setPluginGrouping(kPluginGrouping);
    std::string magickV = MagickCore::GetMagickVersion(NULL);
    std::string delegates = MagickCore::GetMagickDelegates();
    desc.setPluginDescription("Texture/Background generator for Natron.\n\nWritten by Ole-André Rodlie <olear@fxarena.net>\n\n Powered by "+magickV+"\n\nFeatures: "+delegates);

    // add the supported contexts
    desc.addSupportedContext(eContextGeneral);
    desc.addSupportedContext(eContextGenerator);

    // add supported pixel depths
    desc.addSupportedBitDepth(eBitDepthFloat);

    desc.setSupportsTiles(kSupportsTiles);
    desc.setSupportsMultiResolution(kSupportsMultiResolution);
    desc.setRenderThreadSafety(kRenderThreadSafety);
}

/** @brief The describe in context function, passed a plugin descriptor and a context */
void TexturePluginFactory::describeInContext(OFX::ImageEffectDescriptor &desc, ContextEnum /*context*/)
{
    // there has to be an input clip, even for generators
    ClipDescriptor* srcClip = desc.defineClip(kOfxImageEffectSimpleSourceClipName);
    srcClip->addSupportedComponent(ePixelComponentRGBA);
    srcClip->setSupportsTiles(kSupportsTiles);
    srcClip->setOptional(true);

    // create the mandated output clip
    ClipDescriptor *dstClip = desc.defineClip(kOfxImageEffectOutputClipName);
    dstClip->addSupportedComponent(ePixelComponentRGBA);
    dstClip->setSupportsTiles(kSupportsTiles);

    // make some pages
    PageParamDescriptor *page = desc.definePageParam(kPluginName);
    {
        ChoiceParamDescriptor *param = desc.defineChoiceParam(kParamEffect);
        param->setLabel(kParamEffectLabel);
        param->setHint(kParamEffectHint);
        param->appendOption("Plasma");
        param->appendOption("Plasma grey-grey");
        param->appendOption("Plasma white-blue");
        param->appendOption("Plasma green-yellow");
        param->appendOption("Plasma red-blue");
        param->appendOption("Plasma tomato-steelblue");
        param->appendOption("Plasma Fractal");
        param->appendOption("GaussianNoise");
        param->appendOption("ImpulseNoise");
        param->appendOption("LaplacianNoise");
        param->appendOption("Checkerboard");
        param->appendOption("Stripes");
        param->setDefault(kParamEffectDefault);
        param->setAnimates(true);
        page->addChild(*param);
    }
    {
        IntParamDescriptor *param = desc.defineIntParam(kParamSeed);
        param->setLabel(kParamSeedLabel);
        param->setHint(kParamSeedHint);
        param->setRange(0, 10000);
        param->setDisplayRange(0, 5000);
        param->setDefault(kParamSeedDefault);
        page->addChild(*param);
    }
}

/** @brief The create instance function, the plugin must return an object derived from the \ref OFX::ImageEffect class */
ImageEffect* TexturePluginFactory::createInstance(OfxImageEffectHandle handle, ContextEnum /*context*/)
{
    return new TexturePlugin(handle);
}

void getTexturePluginID(OFX::PluginFactoryArray &ids)
{
    static TexturePluginFactory p(kPluginIdentifier, kPluginVersionMajor, kPluginVersionMinor);
    ids.push_back(&p);
}
<|endoftext|>


<commit_before>#include <wm.hpp>
#include <output.hpp>
#include <core.hpp>
#include <linux/input.h>
#include <signal_definitions.hpp>

class wayfire_resize : public wayfire_plugin_t {
    signal_callback_t resize_request;

    button_callback activate_binding;
    wayfire_view view;
    wl_fixed_t initial_x, initial_y;

    uint32_t edges;
    public:
        void init(wayfire_config *config) {
            grab_interface->name = "resize";
            grab_interface->compatAll = true;

            activate_binding = [=] (weston_pointer* ptr, uint32_t) {
                this->initiate(ptr);
            };

            using namespace std::placeholders;
            output->input->add_button(MODIFIER_SUPER, BTN_LEFT, &activate_binding);
            grab_interface->callbacks.pointer.button =
                std::bind(std::mem_fn(&wayfire_resize::button_pressed), this, _1, _2, _3);
            grab_interface->callbacks.pointer.motion =
                std::bind(std::mem_fn(&wayfire_resize::pointer_motion), this, _1, _2);

            resize_request = std::bind(std::mem_fn(&wayfire_resize::resize_requested), this, _1);
            output->signal->connect_signal("resize-request", &resize_request);
            /* TODO: resize_request, read binding from config */
        }

        void resize_requested(signal_data *data) {
            auto converted = static_cast<resize_request_signal*> (data);
            if (converted) {
                initiate(converted->ptr);
                edges = converted->edges; // the first function may not return,
                                          //but in this case this is a no-op
            }
        }

        void initiate(weston_pointer *ptr) {
            if (!ptr->focus)
                return;

            view = core->find_view(ptr->focus);
            if (!view)
                return;

            if (!output->input->activate_plugin(grab_interface))
                return;
            if (!grab_interface->grab())
                return;

            weston_view_from_global_fixed(view->handle, ptr->x, ptr->y, &initial_x, &initial_y);

            int pointer_x = wl_fixed_to_int(initial_x);
            int pointer_y = wl_fixed_to_int(initial_y);

            //const int32_t halfw = view->geometry.origin.x + view->geometry.size.w / 2;
            //const int32_t halfh = view->geometry.origin.y + view->geometry.size.h / 2;
            const int32_t halfw = view->geometry.size.w / 2;
            const int32_t halfh = view->geometry.size.h / 2;

            if (pointer_x < halfw) {
                edges = WL_SHELL_SURFACE_RESIZE_LEFT;
            } else {
                edges = WL_SHELL_SURFACE_RESIZE_RIGHT;
            }

            if (pointer_y < halfh) {
                edges |= WL_SHELL_SURFACE_RESIZE_TOP;
            } else {
                edges |= WL_SHELL_SURFACE_RESIZE_BOTTOM;
            }

            weston_desktop_surface_set_resizing(view->desktop_surface, true);
        }

        void button_pressed(weston_pointer *ptr, uint32_t button, uint32_t state) {
            if (button != BTN_LEFT || state != WL_POINTER_BUTTON_STATE_RELEASED)
                return;

            grab_interface->ungrab();
            output->input->deactivate_plugin(grab_interface);
            weston_desktop_surface_set_resizing(view->desktop_surface, false);
        }

        void pointer_motion(weston_pointer *ptr, weston_pointer_motion_event *ev) {
            auto newg = view->geometry;

            wl_fixed_t current_x, current_y;
            weston_view_from_global_fixed(view->handle, ptr->x, ptr->y, &current_x, &current_y);

            int dx = wl_fixed_to_int(current_x - initial_x);
            int dy = wl_fixed_to_int(current_y - initial_y);

            initial_x = current_x;
            initial_y = current_y;

            if (edges & WL_SHELL_SURFACE_RESIZE_LEFT) {
                newg.origin.x += dx;
                newg.size.w -= dx;
            } else {
                newg.size.w += dx;
            }

            if (edges & WL_SHELL_SURFACE_RESIZE_TOP) {
                newg.origin.y += dy;
                newg.size.h -= dy;
            } else {
                newg.size.h += dy;
            }

            auto max_size = weston_desktop_surface_get_max_size(view->desktop_surface);
            auto min_size = weston_desktop_surface_get_min_size(view->desktop_surface);

            min_size.width = std::max(min_size.width, 10);
            min_size.height = std::max(min_size.height, 10);

            if (max_size.width > 0)
                newg.size.w = std::min(max_size.width, newg.size.w);
            newg.size.w = std::max(min_size.width, newg.size.w);

            if (max_size.height > 0)
                newg.size.h = std::min(max_size.height, newg.size.h);
            newg.size.h = std::max(min_size.height, newg.size.h);

            view->set_geometry(newg);
        }
};

extern "C" {
    wayfire_plugin_t *newInstance() {
        return new wayfire_resize();
    }
}
<commit_msg>Fix resizing when gravity is not bottom-right<commit_after>#include <wm.hpp>
#include <output.hpp>
#include <core.hpp>
#include <linux/input.h>
#include <signal_definitions.hpp>

class wayfire_resize : public wayfire_plugin_t {
    signal_callback_t resize_request;

    button_callback activate_binding;
    wayfire_view view;
    wl_fixed_t initial_x, initial_y;

    uint32_t edges;
    public:
        void init(wayfire_config *config) {
            grab_interface->name = "resize";
            grab_interface->compatAll = true;

            activate_binding = [=] (weston_pointer* ptr, uint32_t) {
                this->initiate(ptr);
            };

            using namespace std::placeholders;
            output->input->add_button(MODIFIER_SUPER, BTN_LEFT, &activate_binding);
            grab_interface->callbacks.pointer.button =
                std::bind(std::mem_fn(&wayfire_resize::button_pressed), this, _1, _2, _3);
            grab_interface->callbacks.pointer.motion =
                std::bind(std::mem_fn(&wayfire_resize::pointer_motion), this, _1, _2);

            resize_request = std::bind(std::mem_fn(&wayfire_resize::resize_requested), this, _1);
            output->signal->connect_signal("resize-request", &resize_request);
            /* TODO: resize_request, read binding from config */
        }

        void resize_requested(signal_data *data) {
            auto converted = static_cast<resize_request_signal*> (data);
            if (converted) {
                initiate(converted->ptr);
                edges = converted->edges; // the first function may not return,
                                          //but in this case this is a no-op
            }
        }

        void initiate(weston_pointer *ptr) {
            if (!ptr->focus)
                return;

            view = core->find_view(ptr->focus);
            if (!view)
                return;

            if (!output->input->activate_plugin(grab_interface))
                return;
            if (!grab_interface->grab())
                return;

            weston_view_from_global_fixed(view->handle, ptr->x, ptr->y, &initial_x, &initial_y);

            int pointer_x = wl_fixed_to_int(initial_x);
            int pointer_y = wl_fixed_to_int(initial_y);

            initial_x = ptr->x;
            initial_y = ptr->y;

            //const int32_t halfw = view->geometry.origin.x + view->geometry.size.w / 2;
            //const int32_t halfh = view->geometry.origin.y + view->geometry.size.h / 2;
            const int32_t halfw = view->geometry.size.w / 2;
            const int32_t halfh = view->geometry.size.h / 2;

            if (pointer_x < halfw) {
                edges = WL_SHELL_SURFACE_RESIZE_LEFT;
            } else {
                edges = WL_SHELL_SURFACE_RESIZE_RIGHT;
            }

            if (pointer_y < halfh) {
                edges |= WL_SHELL_SURFACE_RESIZE_TOP;
            } else {
                edges |= WL_SHELL_SURFACE_RESIZE_BOTTOM;
            }

            weston_desktop_surface_set_resizing(view->desktop_surface, true);
        }

        void button_pressed(weston_pointer *ptr, uint32_t button, uint32_t state) {
            if (button != BTN_LEFT || state != WL_POINTER_BUTTON_STATE_RELEASED)
                return;

            grab_interface->ungrab();
            output->input->deactivate_plugin(grab_interface);
            weston_desktop_surface_set_resizing(view->desktop_surface, false);
        }

        void pointer_motion(weston_pointer *ptr, weston_pointer_motion_event *ev) {
            auto newg = view->geometry;

            wl_fixed_t current_x, current_y, old_x, old_y;
            weston_view_from_global_fixed(view->handle, ptr->x, ptr->y, &current_x, &current_y);
            weston_view_from_global_fixed(view->handle, initial_x, initial_y, &old_x, &old_y);

            int dx = wl_fixed_to_int(current_x - old_x);
            int dy = wl_fixed_to_int(current_y - old_y);

            initial_x = ptr->x;
            initial_y = ptr->y;

            if (edges & WL_SHELL_SURFACE_RESIZE_LEFT) {
                newg.origin.x += dx;
                newg.size.w -= dx;
            } else {
                newg.size.w += dx;
            }

            if (edges & WL_SHELL_SURFACE_RESIZE_TOP) {
                newg.origin.y += dy;
                newg.size.h -= dy;
            } else {
                newg.size.h += dy;
            }

            auto max_size = weston_desktop_surface_get_max_size(view->desktop_surface);
            auto min_size = weston_desktop_surface_get_min_size(view->desktop_surface);

            min_size.width = std::max(min_size.width, 10);
            min_size.height = std::max(min_size.height, 10);

            if (max_size.width > 0)
                newg.size.w = std::min(max_size.width, newg.size.w);
            newg.size.w = std::max(min_size.width, newg.size.w);

            if (max_size.height > 0)
                newg.size.h = std::min(max_size.height, newg.size.h);
            newg.size.h = std::max(min_size.height, newg.size.h);

            view->set_geometry(newg);
        }
};

extern "C" {
    wayfire_plugin_t *newInstance() {
        return new wayfire_resize();
    }
}
<|endoftext|>


<commit_before>/*
    <one line to give the library's name and an idea of what it does.>
    Copyright (C) <year>  <name of author>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*/

#include "scriptengine.h"

#include "gluonobjectfactory.h"
#include "gluonobject.h"
#include "messagehandler.h"

#include <QtScript/QScriptEngine>

void qtscript_initialize_com_trolltech_qt_gui_bindings( QScriptValue& );
namespace GluonCore
{
    class ScriptEngine::Private
    {
        public:
            Private()
                : engine(0)
            {}
            ~Private()
            {}

            QScriptEngine* engine;
    };
}

using namespace GluonCore;

GLUON_DEFINE_SINGLETON(ScriptEngine)

ScriptEngine::ScriptEngine(QObject* /* parent */ )
    : d(new Private())
{
}

ScriptEngine::~ScriptEngine()
{
    delete(d);
}

QScriptEngine* ScriptEngine::scriptEngine()
{
    DEBUG_BLOCK
    if(QCoreApplication::instance() && !d->engine)
    {
        d->engine = new QScriptEngine(this);
        DEBUG_TEXT2( "Available extensions: %1", d->engine->availableExtensions().join( ", " ) );
        d->engine->importExtension( "jsmoke.qtcore" );
        d->engine->importExtension( "jsmoke.qtgui" );
        d->engine->importExtension( "jsmoke.qtopengl" );
        DEBUG_TEXT2( "Imported extensions: %1", d->engine->importedExtensions().join( ", " ) );

        QScriptValue extensionObject = d->engine->globalObject();
        qtscript_initialize_com_trolltech_qt_gui_bindings( extensionObject );

        QScriptEngine::QObjectWrapOptions wrapOptions = QScriptEngine::AutoCreateDynamicProperties | QScriptEngine::ExcludeDeleteLater | QScriptEngine::PreferExistingWrapperObject;
        QScriptEngine::ValueOwnership ownership = QScriptEngine::QtOwnership;

        QScriptValue objectFactory = d->engine->newQObject( GluonObjectFactory::instance(), ownership, wrapOptions);
        extensionObject.setProperty("ObjectFactory", objectFactory );

        QScriptValue messageHandler = d->engine->newQObject( MessageHandler::instance(), ownership, wrapOptions);
        extensionObject.setProperty("MessageHandler", messageHandler);

        // Finally, register all the objects in the factory...
        QHash<QString, const QMetaObject*> types = GluonObjectFactory::instance()->objectTypes();
        QHash<QString, const QMetaObject*>::const_iterator i;
        for( i = types.constBegin(); i != types.constEnd(); ++i)
        {
            QObject* obj = i.value()->newInstance();
            if(qobject_cast<GluonCore::GluonObject*>(obj))
            {
                qobject_cast<GluonCore::GluonObject*>(obj)->registerOnScriptEngine(d->engine);;
            }
            delete(obj);
        }
    }
    return d->engine;
}

void ScriptEngine::resetEngine()
{
    if(d->engine)
    {
        delete(d->engine);
        d->engine = 0;
    }
}

#include "scriptengine.moc"
<commit_msg>Core: Remove uninformative debug messages from ScriptEngine.<commit_after>/*
    <one line to give the library's name and an idea of what it does.>
    Copyright (C) <year>  <name of author>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*/

#include "scriptengine.h"

#include "gluonobjectfactory.h"
#include "gluonobject.h"
#include "messagehandler.h"

#include <QtScript/QScriptEngine>

void qtscript_initialize_com_trolltech_qt_gui_bindings( QScriptValue& );
namespace GluonCore
{
    class ScriptEngine::Private
    {
        public:
            Private()
                : engine(0)
            {}
            ~Private()
            {}

            QScriptEngine* engine;
    };
}

using namespace GluonCore;

GLUON_DEFINE_SINGLETON(ScriptEngine)

ScriptEngine::ScriptEngine(QObject* /* parent */ )
    : d(new Private())
{
}

ScriptEngine::~ScriptEngine()
{
    delete(d);
}

QScriptEngine* ScriptEngine::scriptEngine()
{
    DEBUG_BLOCK
    if(QCoreApplication::instance() && !d->engine)
    {
        d->engine = new QScriptEngine(this);
        d->engine->importExtension( "jsmoke.qtcore" );
        d->engine->importExtension( "jsmoke.qtgui" );
        d->engine->importExtension( "jsmoke.qtopengl" );

        QScriptValue extensionObject = d->engine->globalObject();
        qtscript_initialize_com_trolltech_qt_gui_bindings( extensionObject );

        QScriptEngine::QObjectWrapOptions wrapOptions = QScriptEngine::AutoCreateDynamicProperties | QScriptEngine::ExcludeDeleteLater | QScriptEngine::PreferExistingWrapperObject;
        QScriptEngine::ValueOwnership ownership = QScriptEngine::QtOwnership;

        QScriptValue objectFactory = d->engine->newQObject( GluonObjectFactory::instance(), ownership, wrapOptions);
        extensionObject.setProperty("ObjectFactory", objectFactory );

        QScriptValue messageHandler = d->engine->newQObject( MessageHandler::instance(), ownership, wrapOptions);
        extensionObject.setProperty("MessageHandler", messageHandler);

        // Finally, register all the objects in the factory...
        QHash<QString, const QMetaObject*> types = GluonObjectFactory::instance()->objectTypes();
        QHash<QString, const QMetaObject*>::const_iterator i;
        for( i = types.constBegin(); i != types.constEnd(); ++i)
        {
            QObject* obj = i.value()->newInstance();
            if(qobject_cast<GluonCore::GluonObject*>(obj))
            {
                qobject_cast<GluonCore::GluonObject*>(obj)->registerOnScriptEngine(d->engine);;
            }
            delete(obj);
        }
    }
    return d->engine;
}

void ScriptEngine::resetEngine()
{
    if(d->engine)
    {
        delete(d->engine);
        d->engine = 0;
    }
}

#include "scriptengine.moc"
<|endoftext|>


<commit_before><commit_msg>[core/zlib] printout error in deflateEnd<commit_after><|endoftext|>


<commit_before>

/* Copyright (c) 2011, Peter Barrett
**
** Permission to use, copy, modify, and/or distribute this software for
** any purpose with or without fee is hereby granted, provided that the
** above copyright notice and this permission notice appear in all copies.
**
** THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
** WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
** WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR
** BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES
** OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
** WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
** ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
** SOFTWARE.
*/

#include "Platform.h"
#include "USBAPI.h"
#include <avr/wdt.h>

#if defined(USBCON)
#ifdef CDC_ENABLED

#if (RAMEND < 1000)
#define SERIAL_BUFFER_SIZE 16
#else
#define SERIAL_BUFFER_SIZE 64
#endif

struct ring_buffer
{
	unsigned char buffer[SERIAL_BUFFER_SIZE];
	volatile int head;
	volatile int tail;
};

ring_buffer cdc_rx_buffer = { { 0 }, 0, 0};

typedef struct
{
	u32	dwDTERate;
	u8	bCharFormat;
	u8 	bParityType;
	u8 	bDataBits;
	u8	lineState;
} LineInfo;

static volatile LineInfo _usbLineInfo = { 57600, 0x00, 0x00, 0x00, 0x00 };

#define WEAK __attribute__ ((weak))

extern const CDCDescriptor _cdcInterface PROGMEM;
const CDCDescriptor _cdcInterface =
{
	D_IAD(0,2,CDC_COMMUNICATION_INTERFACE_CLASS,CDC_ABSTRACT_CONTROL_MODEL,1),

	//	CDC communication interface
	D_INTERFACE(CDC_ACM_INTERFACE,1,CDC_COMMUNICATION_INTERFACE_CLASS,CDC_ABSTRACT_CONTROL_MODEL,0),
	D_CDCCS(CDC_HEADER,0x10,0x01),								// Header (1.10 bcd)
	D_CDCCS(CDC_CALL_MANAGEMENT,1,1),							// Device handles call management (not)
	D_CDCCS4(CDC_ABSTRACT_CONTROL_MANAGEMENT,6),				// SET_LINE_CODING, GET_LINE_CODING, SET_CONTROL_LINE_STATE supported
	D_CDCCS(CDC_UNION,CDC_ACM_INTERFACE,CDC_DATA_INTERFACE),	// Communication interface is master, data interface is slave 0
	D_ENDPOINT(USB_ENDPOINT_IN (CDC_ENDPOINT_ACM),USB_ENDPOINT_TYPE_INTERRUPT,0x10,0x40),

	//	CDC data interface
	D_INTERFACE(CDC_DATA_INTERFACE,2,CDC_DATA_INTERFACE_CLASS,0,0),
	D_ENDPOINT(USB_ENDPOINT_OUT(CDC_ENDPOINT_OUT),USB_ENDPOINT_TYPE_BULK,0x40,0),
	D_ENDPOINT(USB_ENDPOINT_IN (CDC_ENDPOINT_IN ),USB_ENDPOINT_TYPE_BULK,0x40,0)
};

int WEAK CDC_GetInterface(u8* interfaceNum)
{
	interfaceNum[0] += 2;	// uses 2
	return USB_SendControl(TRANSFER_PGM,&_cdcInterface,sizeof(_cdcInterface));
}

bool WEAK CDC_Setup(Setup& setup)
{
	u8 r = setup.bRequest;
	u8 requestType = setup.bmRequestType;

	if (REQUEST_DEVICETOHOST_CLASS_INTERFACE == requestType)
	{
		if (CDC_GET_LINE_CODING == r)
		{
			USB_SendControl(0,(void*)&_usbLineInfo,7);
			return true;
		}
	}

	if (REQUEST_HOSTTODEVICE_CLASS_INTERFACE == requestType)
	{
		if (CDC_SET_LINE_CODING == r)
		{
			USB_RecvControl((void*)&_usbLineInfo,7);
			return true;
		}

		if (CDC_SET_CONTROL_LINE_STATE == r)
		{
			_usbLineInfo.lineState = setup.wValueL;

			// auto-reset into the bootloader is triggered when the port, already
			// open at 1200 bps, is closed.  this is the signal to start the watchdog
			// with a relatively long period so it can finish housekeeping tasks
			// like servicing endpoints before the sketch ends
			if (1200 == _usbLineInfo.dwDTERate) {
				// We check DTR state to determine if host port is open (bit 0 of lineState).
				// Serial1.print(">"); Serial1.println(_usbLineInfo.lineState, HEX);
				if ((_usbLineInfo.lineState & 0x01) == 0) {
					*(uint16_t *)0x0A00 = 0x7777;
					wdt_enable(WDTO_120MS);
				} else {
					// Most OSs do some intermediate steps when configuring ports and DTR can
					// twiggle more than once before stabilizing.
					// To avoid spurious resets we set the watchdog to 250ms and eventually
					// cancel if DTR goes back high.

					wdt_disable();
					wdt_reset();
					*(uint16_t *)0x0A00 = 0x0;
				}
			}
			return true;
		}
	}
	return false;
}

int _serialPeek = -1;
void Serial_::begin(uint16_t baud_count)
{
}

void Serial_::end(void)
{
}

void Serial_::accept(void)
{
	ring_buffer *buffer = &cdc_rx_buffer;
	int c = USB_Recv(CDC_RX);
	int i = (unsigned int)(buffer->head+1) % SERIAL_BUFFER_SIZE;

	// if we should be storing the received character into the location
	// just before the tail (meaning that the head would advance to the
	// current location of the tail), we're about to overflow the buffer
	// and so we don't write the character or advance the head.
	if (i != buffer->tail) {
		buffer->buffer[buffer->head] = c;
		buffer->head = i;
	}
}

int Serial_::available(void)
{
	ring_buffer *buffer = &cdc_rx_buffer;
	return (unsigned int)(SERIAL_BUFFER_SIZE + buffer->head - buffer->tail) % SERIAL_BUFFER_SIZE;
}

int Serial_::peek(void)
{
	ring_buffer *buffer = &cdc_rx_buffer;
	if (buffer->head == buffer->tail) {
		return -1;
	} else {
		return buffer->buffer[buffer->tail];
	}
}

int Serial_::read(void)
{
	ring_buffer *buffer = &cdc_rx_buffer;
	// if the head isn't ahead of the tail, we don't have any characters
	if (buffer->head == buffer->tail) {
		return -1;
	} else {
		unsigned char c = buffer->buffer[buffer->tail];
		buffer->tail = (unsigned int)(buffer->tail + 1) % SERIAL_BUFFER_SIZE;
		return c;
	}
}

void Serial_::flush(void)
{
	USB_Flush(CDC_TX);
}

size_t Serial_::write(uint8_t c)
{
	/* only try to send bytes if the high-level CDC connection itself
	 is open (not just the pipe) - the OS should set lineState when the port
	 is opened and clear lineState when the port is closed.
	 bytes sent before the user opens the connection or after
	 the connection is closed are lost - just like with a UART. */

	// TODO - ZE - check behavior on different OSes and test what happens if an
	// open connection isn't broken cleanly (cable is yanked out, host dies
	// or locks up, or host virtual serial port hangs)
	if (_usbLineInfo.lineState > 0)	{
		int r = USB_Send(CDC_TX,&c,1);
		if (r > 0) {
			return r;
		} else {
			setWriteError();
			return 0;
		}
	}
	setWriteError();
	return 0;
}

Serial_::operator bool() {
	if (_usbLineInfo.lineState > 0)
		return true;
	return false;
}

Serial_ Serial;

#endif
#endif /* if defined(USBCON) */
<commit_msg>added a short delay and comment to boolean operator in CDC<commit_after>

/* Copyright (c) 2011, Peter Barrett
**
** Permission to use, copy, modify, and/or distribute this software for
** any purpose with or without fee is hereby granted, provided that the
** above copyright notice and this permission notice appear in all copies.
**
** THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
** WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
** WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR
** BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES
** OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
** WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
** ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
** SOFTWARE.
*/

#include "Platform.h"
#include "USBAPI.h"
#include <avr/wdt.h>

#if defined(USBCON)
#ifdef CDC_ENABLED

#if (RAMEND < 1000)
#define SERIAL_BUFFER_SIZE 16
#else
#define SERIAL_BUFFER_SIZE 64
#endif

struct ring_buffer
{
	unsigned char buffer[SERIAL_BUFFER_SIZE];
	volatile int head;
	volatile int tail;
};

ring_buffer cdc_rx_buffer = { { 0 }, 0, 0};

typedef struct
{
	u32	dwDTERate;
	u8	bCharFormat;
	u8 	bParityType;
	u8 	bDataBits;
	u8	lineState;
} LineInfo;

static volatile LineInfo _usbLineInfo = { 57600, 0x00, 0x00, 0x00, 0x00 };

#define WEAK __attribute__ ((weak))

extern const CDCDescriptor _cdcInterface PROGMEM;
const CDCDescriptor _cdcInterface =
{
	D_IAD(0,2,CDC_COMMUNICATION_INTERFACE_CLASS,CDC_ABSTRACT_CONTROL_MODEL,1),

	//	CDC communication interface
	D_INTERFACE(CDC_ACM_INTERFACE,1,CDC_COMMUNICATION_INTERFACE_CLASS,CDC_ABSTRACT_CONTROL_MODEL,0),
	D_CDCCS(CDC_HEADER,0x10,0x01),								// Header (1.10 bcd)
	D_CDCCS(CDC_CALL_MANAGEMENT,1,1),							// Device handles call management (not)
	D_CDCCS4(CDC_ABSTRACT_CONTROL_MANAGEMENT,6),				// SET_LINE_CODING, GET_LINE_CODING, SET_CONTROL_LINE_STATE supported
	D_CDCCS(CDC_UNION,CDC_ACM_INTERFACE,CDC_DATA_INTERFACE),	// Communication interface is master, data interface is slave 0
	D_ENDPOINT(USB_ENDPOINT_IN (CDC_ENDPOINT_ACM),USB_ENDPOINT_TYPE_INTERRUPT,0x10,0x40),

	//	CDC data interface
	D_INTERFACE(CDC_DATA_INTERFACE,2,CDC_DATA_INTERFACE_CLASS,0,0),
	D_ENDPOINT(USB_ENDPOINT_OUT(CDC_ENDPOINT_OUT),USB_ENDPOINT_TYPE_BULK,0x40,0),
	D_ENDPOINT(USB_ENDPOINT_IN (CDC_ENDPOINT_IN ),USB_ENDPOINT_TYPE_BULK,0x40,0)
};

int WEAK CDC_GetInterface(u8* interfaceNum)
{
	interfaceNum[0] += 2;	// uses 2
	return USB_SendControl(TRANSFER_PGM,&_cdcInterface,sizeof(_cdcInterface));
}

bool WEAK CDC_Setup(Setup& setup)
{
	u8 r = setup.bRequest;
	u8 requestType = setup.bmRequestType;

	if (REQUEST_DEVICETOHOST_CLASS_INTERFACE == requestType)
	{
		if (CDC_GET_LINE_CODING == r)
		{
			USB_SendControl(0,(void*)&_usbLineInfo,7);
			return true;
		}
	}

	if (REQUEST_HOSTTODEVICE_CLASS_INTERFACE == requestType)
	{
		if (CDC_SET_LINE_CODING == r)
		{
			USB_RecvControl((void*)&_usbLineInfo,7);
			return true;
		}

		if (CDC_SET_CONTROL_LINE_STATE == r)
		{
			_usbLineInfo.lineState = setup.wValueL;

			// auto-reset into the bootloader is triggered when the port, already
			// open at 1200 bps, is closed.  this is the signal to start the watchdog
			// with a relatively long period so it can finish housekeeping tasks
			// like servicing endpoints before the sketch ends
			if (1200 == _usbLineInfo.dwDTERate) {
				// We check DTR state to determine if host port is open (bit 0 of lineState).
				// Serial1.print(">"); Serial1.println(_usbLineInfo.lineState, HEX);
				if ((_usbLineInfo.lineState & 0x01) == 0) {
					*(uint16_t *)0x0A00 = 0x7777;
					wdt_enable(WDTO_120MS);
				} else {
					// Most OSs do some intermediate steps when configuring ports and DTR can
					// twiggle more than once before stabilizing.
					// To avoid spurious resets we set the watchdog to 250ms and eventually
					// cancel if DTR goes back high.

					wdt_disable();
					wdt_reset();
					*(uint16_t *)0x0A00 = 0x0;
				}
			}
			return true;
		}
	}
	return false;
}

int _serialPeek = -1;
void Serial_::begin(uint16_t baud_count)
{
}

void Serial_::end(void)
{
}

void Serial_::accept(void)
{
	ring_buffer *buffer = &cdc_rx_buffer;
	int c = USB_Recv(CDC_RX);
	int i = (unsigned int)(buffer->head+1) % SERIAL_BUFFER_SIZE;

	// if we should be storing the received character into the location
	// just before the tail (meaning that the head would advance to the
	// current location of the tail), we're about to overflow the buffer
	// and so we don't write the character or advance the head.
	if (i != buffer->tail) {
		buffer->buffer[buffer->head] = c;
		buffer->head = i;
	}
}

int Serial_::available(void)
{
	ring_buffer *buffer = &cdc_rx_buffer;
	return (unsigned int)(SERIAL_BUFFER_SIZE + buffer->head - buffer->tail) % SERIAL_BUFFER_SIZE;
}

int Serial_::peek(void)
{
	ring_buffer *buffer = &cdc_rx_buffer;
	if (buffer->head == buffer->tail) {
		return -1;
	} else {
		return buffer->buffer[buffer->tail];
	}
}

int Serial_::read(void)
{
	ring_buffer *buffer = &cdc_rx_buffer;
	// if the head isn't ahead of the tail, we don't have any characters
	if (buffer->head == buffer->tail) {
		return -1;
	} else {
		unsigned char c = buffer->buffer[buffer->tail];
		buffer->tail = (unsigned int)(buffer->tail + 1) % SERIAL_BUFFER_SIZE;
		return c;
	}
}

void Serial_::flush(void)
{
	USB_Flush(CDC_TX);
}

size_t Serial_::write(uint8_t c)
{
	/* only try to send bytes if the high-level CDC connection itself
	 is open (not just the pipe) - the OS should set lineState when the port
	 is opened and clear lineState when the port is closed.
	 bytes sent before the user opens the connection or after
	 the connection is closed are lost - just like with a UART. */

	// TODO - ZE - check behavior on different OSes and test what happens if an
	// open connection isn't broken cleanly (cable is yanked out, host dies
	// or locks up, or host virtual serial port hangs)
	if (_usbLineInfo.lineState > 0)	{
		int r = USB_Send(CDC_TX,&c,1);
		if (r > 0) {
			return r;
		} else {
			setWriteError();
			return 0;
		}
	}
	setWriteError();
	return 0;
}

// This operator is a convenient way for a sketch to check whether the
// port has actually been configured and opened by the host (as opposed
// to just being connected to the host).  It can be used, for example, in
// setup() before printing to ensure that an application on the host is
// actually ready to receive and display the data.
// We add a short delay before returning to fix a bug observed by Federico
// where the port is configured (lineState != 0) but not quite opened.
Serial_::operator bool() {
	bool result = false;
	if (_usbLineInfo.lineState > 0)
		result = true;
	delay(10);
	return result;
}

Serial_ Serial;

#endif
#endif /* if defined(USBCON) */
<|endoftext|>


<commit_before><commit_msg>[bookmarks] Bookmarks belong to compilations attached to compilation id instead of category id. MAPSME-15129<commit_after><|endoftext|>


<commit_before>/*************************************************************************
Mots - Classe de manipulation d'un ensemble de mots gntiques
-------------------
dbut                :	31/04/17
copyright            :	(C) 2017 par CHAZELLE
e-mail               :	benjamin.chazelle@insa-lyon.fr
*************************************************************************/

//--------- Ralisation de la classe <Mots> (fichier Mots.cpp) ---------//

//---------------------------------------------------------------- INCLUDE

//-------------------------------------------------------- Include systme

//------------------------------------------------------ Include personnel

#include <exception>
#include "Mots.h"

//----------------------------------------------------------------- PUBLIC

Mots* Mots::instanceMots = new Mots();

Mots & Mots::ObtenirInstance()
{
	return *(Mots::instanceMots);
}

unsigned int Mots::ObtenirIndex(const char const mot[])//non tester
{
	if(mot == nullptr)
		throw invalid_argument("nullptr n'est pas autoriser pour cette method");
	char * str = new char[strlen(mot) + 1];
	strcpy(str, mot);
	unordered_map<char*, unsigned int>::iterator t = mots.find((char*)str);
	free(str);
	if (t == mots.end())
		throw range_error("mot non trouver");
	return t->second;
}

unsigned int Mots::InsererMot(const char const mot[])//non tester
{
	if (mot == nullptr)
		throw invalid_argument("nullptr n'est pas autoriser pour cette method");
	char * str = new char[strlen(mot) + 1];
	strcpy(str, mot);
	unordered_map<char*, unsigned int>::iterator t = mots.find((char*)str);
	if (t != mots.end()) {
		free(str);
		throw range_error("Mot deja present");
	}

	std::pair<char*, unsigned int> pair1(str, this->counter);
	std::pair<unsigned int, char *> pair2(this->counter, str);
	mots.insert(pair1);
	mots_revers.insert(pair2);

	this->counter++;

	free(str);

	return this->counter-1;
}

char const * Mots::RecupererMot(const unsigned int i)//non tester
{
	if (i < 0 || i >= counter)
		throw range_error("Mot inexistant");
	return mots_revers[i];
}

unsigned int Mots::ObtenirNombreMots()//non tester
{
	return counter;
}

//----------------------------------------------------------------- PRIVEE

Mots::Mots()
{
	this->counter = 0;
}

Mots::~Mots()
{
}
<commit_msg>corection des inclusion systeme (Mots.cpp)<commit_after>/*************************************************************************
Mots - Classe de manipulation d'un ensemble de mots gntiques
-------------------
dbut                :	31/04/17
copyright            :	(C) 2017 par CHAZELLE
e-mail               :	benjamin.chazelle@insa-lyon.fr
*************************************************************************/

//--------- Ralisation de la classe <Mots> (fichier Mots.cpp) ---------//

//---------------------------------------------------------------- INCLUDE

//-------------------------------------------------------- Include systme

#include <exception>
#include <cstring>

//------------------------------------------------------ Include personnel

#include "Mots.h"

//----------------------------------------------------------------- PUBLIC

Mots* Mots::instanceMots = new Mots();

Mots & Mots::ObtenirInstance()
{
	return *(Mots::instanceMots);
}

unsigned int Mots::ObtenirIndex(const char const mot[])//non tester
{
	if(mot == nullptr)
		throw invalid_argument("nullptr n'est pas autoriser pour cette method");
	char * str = new char[strlen(mot) + 1];
	strcpy(str, mot);
	unordered_map<char*, unsigned int>::iterator t = mots.find((char*)str);
	free(str);
	if (t == mots.end())
		throw range_error("mot non trouver");
	return t->second;
}

unsigned int Mots::InsererMot(const char const mot[])//non tester
{
	if (mot == nullptr)
		throw invalid_argument("nullptr n'est pas autoriser pour cette method");
	char * str = new char[strlen(mot) + 1];
	strcpy(str, mot);
	unordered_map<char*, unsigned int>::iterator t = mots.find((char*)str);
	if (t != mots.end()) {
		free(str);
		throw range_error("Mot deja present");
	}

	std::pair<char*, unsigned int> pair1(str, this->counter);
	std::pair<unsigned int, char *> pair2(this->counter, str);
	mots.insert(pair1);
	mots_revers.insert(pair2);

	this->counter++;

	free(str);

	return this->counter-1;
}

char const * Mots::RecupererMot(const unsigned int i)//non tester
{
	if (i < 0 || i >= counter)
		throw range_error("Mot inexistant");
	return mots_revers[i];
}

unsigned int Mots::ObtenirNombreMots()//non tester
{
	return counter;
}

//----------------------------------------------------------------- PRIVEE

Mots::Mots()
{
	this->counter = 0;
}

Mots::~Mots()
{
}
<|endoftext|>


<commit_before>/******************************************************************************\
* File:          stcfile.cpp
* Purpose:       Implementation of class wxExSTCFile
* Author:        Anton van Wezenbeek
* RCS-ID:        $Id$
*
* Copyright (c) 1998-2009 Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/

#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <wx/extension/stcfile.h>
#include <wx/extension/filedlg.h>
#include <wx/extension/filename.h>
#include <wx/extension/frame.h>
#include <wx/extension/lexers.h>
#include <wx/extension/log.h>
#include <wx/extension/stc.h>

#if wxUSE_GUI
const int SCI_ADDTEXT = 2001;
const int SCI_APPENDTEXT = 2282;

wxExSTCFile::wxExSTCFile(wxExSTC* stc)
  : m_STC(stc)
  , m_PreviousLength(0)
{
}

void wxExSTCFile::DoFileLoad(bool synced)
{
  if (GetContentsChanged())
  {
    wxExFileDialog dlg(m_STC, this);
    if (dlg.ShowModalIfChanged() == wxID_CANCEL) return;
  }

  // Synchronizing by appending only new data only works for log files.
  // Other kind of files might get new data anywhere inside the file,
  // we cannot sync that by keeping pos. Also only do it for reasonably large files,
  // so small log files are synced always (e.g. COM LIB report.log).
  const bool log_sync =
    synced &&
    GetFileName().GetExt().CmpNoCase("log") == 0 &&
    m_STC->GetTextLength() > 1024;

  // Be sure we can add text.
  m_STC->SetReadOnly(false);

  ReadFromFile(log_sync);

  if (!(m_STC->GetFlags() & wxExSTC::STC_WIN_HEX))
  {
    m_STC->SetLexer(GetFileName().GetLexer().GetScintillaLexer());

    if (m_STC->GetLexer().GetScintillaLexer() == "po")
    {
      m_STC->AddBasePathToPathList();
    }
  }

  if (m_STC->GetFlags() & m_STC->STC_WIN_READ_ONLY ||
      GetFileName().GetStat().IsReadOnly() ||
      // At this moment we do not allow to write in hex mode.
      m_STC->GetFlags() & m_STC->STC_WIN_HEX)
  {
    m_STC->SetReadOnly(true);
  }

  m_STC->EmptyUndoBuffer();

  if (!synced)
  {
    wxExLog::Get()->Log(_("Opened") + ": " + GetFileName().GetFullPath());
    m_STC->PropertiesMessage();
  }
  else
  {
#if wxUSE_STATUSBAR
    wxExFrame::StatusText(GetFileName(), wxExFrame::STAT_SYNC);
    m_STC->UpdateStatusBar("PaneLines");
#endif
  }

  // No edges for log files.
  if (GetFileName().GetExt() == "log")
  {
    m_STC->SetEdgeMode(wxSTC_EDGE_NONE);
  }

  if (GetFileName() == wxExLog::Get()->GetFileName())
  {
    m_STC->DocumentEnd();
  }
}

void wxExSTCFile::DoFileNew()
{
  m_STC->SetName(GetFileName().GetFullPath());

  m_STC->PropertiesMessage();

  m_STC->ClearDocument();

  m_STC->SetLexer(GetFileName().GetLexer().GetScintillaLexer());
}

void wxExSTCFile::DoFileSave(bool save_as)
{
  const wxCharBuffer& buffer = m_STC->GetTextRaw();
  Write(buffer.data(), buffer.length());

  if (save_as)
  {
    m_STC->SetName(GetFileName().GetFullPath());
    m_STC->SetLexer(GetFileName().GetLexer().GetScintillaLexer());
  }

  if (wxExLexers::Get()->MarkerIsLoaded(m_STC->GetMarkerChange()))
  {
    m_STC->MarkerDeleteAll(m_STC->GetMarkerChange().GetNo());
  }

  const wxString msg = _("Saved") + ": " + GetFileName().GetFullPath();
  wxExLog::Get()->Log(msg);

#if wxUSE_STATUSBAR
  wxExFrame::StatusText(msg);
#endif
}

bool wxExSTCFile::GetContentsChanged() const
{
  return m_STC->GetModify();
}

void wxExSTCFile::ReadFromFile(bool get_only_new_data)
{
  const bool pos_at_end = (m_STC->GetCurrentPos() >= m_STC->GetTextLength() - 1);

  int startPos, endPos;
  m_STC->GetSelection(&startPos, &endPos);

  wxFileOffset offset = 0;

  if (m_PreviousLength < Length() && get_only_new_data)
  {
    offset = m_PreviousLength;
  }

  if (offset == 0)
  {
    m_STC->ClearDocument();
  }

  m_PreviousLength = Length();

  const wxCharBuffer& buffer = Read(offset);

  if (!(m_STC->GetFlags() & wxExSTC::STC_WIN_HEX))
  {
    // At least for toggling between hex and non-hex this is necessary to
    // reshow the edge line.
    m_STC->ConfigGet();

    m_STC->SetControlCharSymbol(0);

    const auto message = (get_only_new_data ? SCI_APPENDTEXT: SCI_ADDTEXT);

    // README: The stc.h equivalents AddText, AddTextRaw, InsertText,
    // InsertTextRaw do not add the length.
    // So for binary files this is the only way for opening.
    m_STC->SendMsg(message, buffer.length(), (wxIntPtr)(const char *)buffer.data());
  }
  else
  {
    m_STC->AddTextHexMode(offset, buffer);
  }

  if (get_only_new_data)
  {
    if (pos_at_end)
    {
      m_STC->DocumentEnd();
    }
  }
  else
  {
    m_STC->GuessType();
    m_STC->DocumentStart();
  }

  if (startPos != endPos)
  {
    // TODO: This does not seem to work.
    m_STC->SetSelection(startPos, endPos);
  }
}

void wxExSTCFile::ResetContentsChanged()
{
  m_STC->SetSavePoint();
}

#endif // wxUSE_GUI
<commit_msg>minor updates<commit_after>/******************************************************************************\
* File:          stcfile.cpp
* Purpose:       Implementation of class wxExSTCFile
* Author:        Anton van Wezenbeek
* RCS-ID:        $Id$
*
* Copyright (c) 1998-2009 Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/

#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <wx/extension/stcfile.h>
#include <wx/extension/filedlg.h>
#include <wx/extension/filename.h>
#include <wx/extension/frame.h>
#include <wx/extension/lexers.h>
#include <wx/extension/log.h>
#include <wx/extension/stc.h>

#if wxUSE_GUI
wxExSTCFile::wxExSTCFile(wxExSTC* stc)
  : m_STC(stc)
  , m_PreviousLength(0)
{
}

void wxExSTCFile::DoFileLoad(bool synced)
{
  if (GetContentsChanged())
  {
    wxExFileDialog dlg(m_STC, this);
    if (dlg.ShowModalIfChanged() == wxID_CANCEL) return;
  }

  // Synchronizing by appending only new data only works for log files.
  // Other kind of files might get new data anywhere inside the file,
  // we cannot sync that by keeping pos. Also only do it for reasonably large files,
  // so small log files are synced always (e.g. COM LIB report.log).
  const bool log_sync =
    synced &&
    GetFileName().GetExt().CmpNoCase("log") == 0 &&
    m_STC->GetTextLength() > 1024;

  // Be sure we can add text.
  m_STC->SetReadOnly(false);

  ReadFromFile(log_sync);

  if (!(m_STC->GetFlags() & wxExSTC::STC_WIN_HEX))
  {
    m_STC->SetLexer(GetFileName().GetLexer().GetScintillaLexer());

    if (m_STC->GetLexer().GetScintillaLexer() == "po")
    {
      m_STC->AddBasePathToPathList();
    }
  }

  if (m_STC->GetFlags() & m_STC->STC_WIN_READ_ONLY ||
      GetFileName().GetStat().IsReadOnly() ||
      // At this moment we do not allow to write in hex mode.
      m_STC->GetFlags() & m_STC->STC_WIN_HEX)
  {
    m_STC->SetReadOnly(true);
  }

  m_STC->EmptyUndoBuffer();

  if (!synced)
  {
    wxExLog::Get()->Log(_("Opened") + ": " + GetFileName().GetFullPath());
    m_STC->PropertiesMessage();
  }
  else
  {
#if wxUSE_STATUSBAR
    wxExFrame::StatusText(GetFileName(), wxExFrame::STAT_SYNC);
    m_STC->UpdateStatusBar("PaneLines");
#endif
  }

  // No edges for log files.
  if (GetFileName().GetExt() == "log")
  {
    m_STC->SetEdgeMode(wxSTC_EDGE_NONE);
  }

  if (GetFileName() == wxExLog::Get()->GetFileName())
  {
    m_STC->DocumentEnd();
  }
}

void wxExSTCFile::DoFileNew()
{
  m_STC->SetName(GetFileName().GetFullPath());
  m_STC->PropertiesMessage();
  m_STC->ClearDocument();
  m_STC->SetLexer(GetFileName().GetLexer().GetScintillaLexer());
}

void wxExSTCFile::DoFileSave(bool save_as)
{
  const wxCharBuffer& buffer = m_STC->GetTextRaw();
  Write(buffer.data(), buffer.length());

  if (save_as)
  {
    m_STC->SetName(GetFileName().GetFullPath());
    m_STC->SetLexer(GetFileName().GetLexer().GetScintillaLexer());
  }

  if (wxExLexers::Get()->MarkerIsLoaded(m_STC->GetMarkerChange()))
  {
    m_STC->MarkerDeleteAll(m_STC->GetMarkerChange().GetNo());
  }

  const wxString msg = _("Saved") + ": " + GetFileName().GetFullPath();
  wxExLog::Get()->Log(msg);

#if wxUSE_STATUSBAR
  wxExFrame::StatusText(msg);
#endif
}

bool wxExSTCFile::GetContentsChanged() const
{
  return m_STC->GetModify();
}

void wxExSTCFile::ReadFromFile(bool get_only_new_data)
{
  const bool pos_at_end = (m_STC->GetCurrentPos() >= m_STC->GetTextLength() - 1);

  int startPos, endPos;
  m_STC->GetSelection(&startPos, &endPos);

  wxFileOffset offset = 0;

  if (m_PreviousLength < Length() && get_only_new_data)
  {
    offset = m_PreviousLength;
  }

  if (offset == 0)
  {
    m_STC->ClearDocument();
  }

  m_PreviousLength = Length();

  const wxCharBuffer& buffer = Read(offset);

  if (!(m_STC->GetFlags() & wxExSTC::STC_WIN_HEX))
  {
    // At least for toggling between hex and non-hex this is necessary to
    // reshow the edge line.
    m_STC->ConfigGet();

    m_STC->SetControlCharSymbol(0);

    const int SCI_ADDTEXT = 2001;
    const int SCI_APPENDTEXT = 2282;
    const auto message = (get_only_new_data ? SCI_APPENDTEXT: SCI_ADDTEXT);

    // README: The stc.h equivalents AddText, AddTextRaw, InsertText,
    // InsertTextRaw do not add the length.
    // So for binary files this is the only way for opening.
    m_STC->SendMsg(message, buffer.length(), (wxIntPtr)(const char *)buffer.data());
  }
  else
  {
    m_STC->AddTextHexMode(offset, buffer);
  }

  if (get_only_new_data)
  {
    if (pos_at_end)
    {
      m_STC->DocumentEnd();
    }
  }
  else
  {
    m_STC->GuessType();
    m_STC->DocumentStart();
  }

  if (startPos != endPos)
  {
    // TODO: This does not seem to work.
    m_STC->SetSelection(startPos, endPos);
  }
}

void wxExSTCFile::ResetContentsChanged()
{
  m_STC->SetSavePoint();
}

#endif // wxUSE_GUI
<|endoftext|>