text
stringlengths
54
60.6k
<commit_before>#include "flexinfo.h" #include <boost/lexical_cast.hpp> #include <openbabel/mol.h> #include <openbabel/atom.h> #include <openbabel/bond.h> #include <boost/unordered_map.hpp> #include <exception> #include <limits> using namespace std; FlexInfo::FlexInfo(const std::string& flexres, double flexdist, const std::string& ligand, int nflex_, bool nflex_hard_limit_, tee& l) : flex_dist(flexdist), nflex(nflex_), nflex_hard_limit(nflex_hard_limit_), log(l) { using namespace OpenBabel; using namespace std; //first extract comma separated list if (flexres.size() > 0) { vector<string> tokens; boost::split(tokens, flexres, boost::is_any_of(",")); vector<string> chres; for (unsigned i = 0, n = tokens.size(); i < n; i++) { //each token may be either chain:resid or just resid string tok = tokens[i]; boost::split(chres, tok, boost::is_any_of(":")); char chain = 0; int resid = 0; char icode = 0; if (chres.size() >= 2) { if (chres[0].size() != 1) log << "WARNING: chain specification not single character " << chres[0] << "\n"; chain = chres[0][0]; //if empty will be null which is what is desired resid = boost::lexical_cast<int>(chres[1]); if (chres.size() == 3) { // Insertion code is present if(chres[2].size() == 1){ // Check that icode is single char icode = chres[2][0]; } else{ // Invalid icode log << "WARNING: ignoring invalid chain:resid:icode specifier " << tok << "\n"; continue; } } } else if (chres.size() == 1) { resid = boost::lexical_cast<int>(chres[0]); } else { log << "WARNING: ignoring invalid chain:resid specifier " << tok << "\n"; continue; } residues.insert(tuple<char, int, char>(chain, resid, icode)); } } if (ligand.size() > 0 && flex_dist > 0) { //next read ligand for distance checking obmol_opener opener; OBConversion conv; opener.openForInput(conv, ligand); conv.Read(&distligand); //first ligand only } } //return true if residue isn't flexible static bool isInflexible(const string& resname) { return resname == "ALA" || resname == "GLY" || resname == "PRO"; } //remove inflexible residues from residues set //the receptor is needed because we don't store the residue name void FlexInfo::sanitizeResidues(OpenBabel::OBMol& receptor) { using namespace OpenBabel; if(!hasContent()) return; OBResidueIterator ritr, rend; OBResidue *firstres = receptor.BeginResidue(ritr); char defaultch = ' '; if (firstres) defaultch = firstres->GetChain(); // Iterate over all receptor residues for (ritr = receptor.BeginResidues(), rend = receptor.EndResidues(); ritr != rend; ++ritr) { OBResidue *r = *ritr; char ch = r->GetChain(); int resid = r->GetNum(); char icode = r->GetInsertionCode(); std::string resname = r->GetName(); if(ch == 0)ch = defaultch; //substitute default chain for unspecified chain tuple<char,int,char> res(ch,resid,icode); if (residues.count(res) > 0) { // Residue in user-specified flexible residues if (isInflexible(resname)) { // Residue can't be flexible residues.erase(res); // Remove residue from list of flexible residues log << "WARNING: Removing non-flexible residue " << resname; log << " " << ch << ":" << resid << ":" << icode << "\n"; } } } } void FlexInfo::keepNearestResidues( const OpenBabel::OBMol& rigid, std::unordered_map<std::size_t, double>& residues_distances){ using namespace OpenBabel; // Loop over residue list and compute minimum distances for(auto& resdist : residues_distances){ // Current residue (among flexible ones) std::size_t residx = resdist.first; // Key OBResidue* res = rigid.GetResidue(residx); // Minimum distance between ligand and current residue atoms double d2; // Loop over ligand atoms FOR_ATOMS_OF_MOL(alig, distligand) { vector3 al = alig->GetVector(); // Loop over residue atoms for(const auto ares: res->GetAtoms()){ if(!isSideChain(res->GetAtomID(ares))) continue; // skip backbone vector3 ar = ares->GetVector(); d2 = al.distSq(ar); if (d2 < resdist.second) { resdist.second = d2; } } } } // std::map is sorted by keys std::map<double, std::size_t> residues_distances_sorted; for(const auto& resdist : residues_distances){ residues_distances_sorted.insert({resdist.second, resdist.first}); } residues.clear(); std::size_t res_added = 0; for (const auto& resdist : residues_distances_sorted) { if(res_added == nflex){ break; } OBResidue* residue = rigid.GetResidue(resdist.second); char ch = residue->GetChain(); int resid = residue->GetNum(); char icode = residue->GetInsertionCode(); residues.insert(std::tuple<char, int, char>(ch, resid, icode)); res_added++; } } bool FlexInfo::isSideChain(std::string aid){ boost::trim(aid); return aid != "CA" && aid != "N" && aid != "C" && aid != "O" && aid != "H" && aid != "HN"; } void FlexInfo::extractFlex(OpenBabel::OBMol& receptor, OpenBabel::OBMol& rigid, std::string& flexpdbqt) { using namespace OpenBabel; rigid = receptor; rigid.SetChainsPerceived(true); //OB bug workaround flexpdbqt.clear(); //identify residues close to distligand here Box b; b.add_ligand_box(distligand); b.expand(flex_dist); double flsq = flex_dist * flex_dist; std::unordered_map<std::size_t, double> residues_distances; FOR_ATOMS_OF_MOL(a, rigid){ if(a->GetAtomicNum() == 1) continue; //heavy atoms only //if(!isSideChain(a->GetResidue()->GetAtomID(&(*a)))) continue; // skip backbone vector3 v = a->GetVector(); if (b.ptIn(v.x(), v.y(), v.z())) { //in box, see if any atoms are close enough FOR_ATOMS_OF_MOL(b, distligand) { vector3 bv = b->GetVector(); if (v.distSq(bv) < flsq) { //process residue OBResidue *residue = a->GetResidue(); if (residue) { char ch = residue->GetChain(); int resid = residue->GetNum(); char icode = residue->GetInsertionCode(); if(!isInflexible(residue->GetName())) { residues_distances.insert({residue->GetIdx(), std::numeric_limits<double>::max()}); residues.insert(std::tuple<char, int, char>(ch, resid, icode)); } } break; } } } } //replace any empty chains with first chain in mol OBResidueIterator ritr; OBResidue *firstres = rigid.BeginResidue(ritr); if (firstres) defaultch = firstres->GetChain(); sanitizeResidues(receptor); if(nflex > -1 && residues.size() > nflex && nflex_hard_limit){ throw std::runtime_error("Number of flexible residues found is higher than --flex_limit."); } else if(nflex > -1 && residues.size() > nflex){ log << "WARNING: Only the flex_max residues closer to the ligand are considered as flexible.\n"; keepNearestResidues(rigid, residues_distances); } std::vector<std::tuple<char, int, char> > sortedres(residues.begin(), residues.end()); for (unsigned i = 0, n = sortedres.size(); i < n; i++) { if (get<0>(sortedres[i]) == 0) get<0>(sortedres[i]) = defaultch; } sort(sortedres.begin(), sortedres.end()); //reinsert residues now with default chain residues.clear(); residues.insert(sortedres.begin(), sortedres.end()); OBConversion conv; conv.SetOutFormat("PDBQT"); conv.AddOption("s", OBConversion::OUTOPTIONS); //flexible residue rigid.BeginModify(); int flexcnt = 0; //identify atoms that have to be in flexible component //this is the side chain and CA, but _not_ the C and N for (OBResidueIterator ritr = rigid.BeginResidues(), rend = rigid.EndResidues(); ritr != rend; ++ritr) { OBResidue *r = *ritr; char ch = r->GetChain(); int resid = r->GetNum(); char icode = r->GetInsertionCode(); std::tuple<char, int, char> chres(ch, resid, icode); if (residues.count(chres)) { flexcnt++; //create a separate molecule for each flexible residue OBMol flex; std::vector<OBAtom*> flexatoms; //rigid atom ptrs that should be flexible boost::unordered_map<OBAtom*, int> flexmap; //map rigid atom ptrs to atom indices in flex //make absolutely sure that CA is the first atom //first bond is rigid, so take both CA and C for (OBAtomIterator aitr = r->BeginAtoms(), aend = r->EndAtoms(); aitr != aend; ++aitr) { OBAtom *a = *aitr; std::string aid = r->GetAtomID(a); boost::trim(aid); if (aid == "CA" || aid == "C") { flexatoms.push_back(a); flex.AddAtom(*a); flexmap[a] = flex.NumAtoms(); //after addatom since indexed by } } for (OBAtomIterator aitr = r->BeginAtoms(), aend = r->EndAtoms(); aitr != aend; ++aitr) { OBAtom *a = *aitr; std::string aid = r->GetAtomID(a); boost::trim(aid); if (aid != "CA" && aid != "N" && aid != "C" && aid != "O" && aid != "H" && aid != "HN" && //leave backbone alone other than CA which is handled above !a->IsNonPolarHydrogen()) { flexatoms.push_back(a); flex.AddAtom(*a); flexmap[a] = flex.NumAtoms(); //after addatom since indexed by } } //now add bonds - at some point I should add functions to openbabel to do this.. for (unsigned i = 0, n = flexatoms.size(); i < n; i++) { OBAtom *a = flexatoms[i]; FOR_BONDS_OF_ATOM(b, a){ OBBond& bond = *b; //just do one direction, if first atom is a //and second atom is a flexatom need to add bond if(a == bond.GetBeginAtom() && flexmap.count(bond.GetEndAtom())) { flex.AddBond(flexmap[a],flexmap[bond.GetEndAtom()],bond.GetBondOrder(), bond.GetFlags()); } } } flex.AddResidue(*r); OBResidue *newres = flex.GetResidue(0); if (newres) { //add all atoms with proper atom ids for (unsigned i = 0, n = flexatoms.size(); i < n; i++) { OBAtom *origa = flexatoms[i]; OBAtom *newa = flex.GetAtom(flexmap[origa]); newres->RemoveAtom(origa); newres->AddAtom(newa); newa->SetResidue(newres); std::string aid = r->GetAtomID(origa); newres->SetAtomID(newa, aid); } } std::string flexres = conv.WriteString(&flex); if (newres) { //the pdbqt writing code breaks flex into fragments, in the process it loses all residue information //so we rewrite the strings.. std::vector<std::string> tokens; std::string resn = newres->GetName(); while (resn.size() < 3) resn += " "; std::string resnum = boost::lexical_cast<std::string>(newres->GetNum()); while (resnum.size() < 4) resnum = " " + resnum; char ch = newres->GetChain(); char icode = newres->GetInsertionCode(); boost::split(tokens, flexres, boost::is_any_of("\n")); for (unsigned i = 0, n = tokens.size(); i < n; i++) { std::string line = tokens[i]; if (line.size() > 25) { //replace UNL with resn for (unsigned p = 0; p < 3; p++) { line[17 + p] = resn[p]; } //resid for (unsigned p = 0; p < 4; p++) { line[22 + p] = resnum[p]; } if(icode > 0) line[26] = icode; line[21] = ch; } if (line.size() > 0) { flexpdbqt += line; flexpdbqt += "\n"; } } } else { flexpdbqt += flexres; } //remove flexatoms from rigid for (unsigned i = 0, n = flexatoms.size(); i < n; i++) { OBAtom *a = flexatoms[i]; rigid.DeleteAtom(a); } } //end if residue } if(flexcnt != residues.size()) { log << "WARNING: Only identified " << flexcnt << " of " << residues.size() << " requested flexible residues.\n"; } rigid.EndModify(); } void FlexInfo::printFlex() const{ // Residues are stored as unordered_set // Sort before printing std::vector<std::tuple<char, int, char> > sortedres(residues.begin(), residues.end()); sort(sortedres.begin(), sortedres.end()); if (sortedres.size() > 0) { log << "Flexible residues:"; for (unsigned i = 0, n = sortedres.size(); i < n; i++) { log << " " << get<0>(sortedres[i]) << ":" << get<1>(sortedres[i]); if(get<2>(sortedres[i]) > 0) log << ":" << get<2>(sortedres[i]); } log << "\n"; } }<commit_msg>check if atom has associated residue<commit_after>#include "flexinfo.h" #include <boost/lexical_cast.hpp> #include <openbabel/mol.h> #include <openbabel/atom.h> #include <openbabel/bond.h> #include <boost/unordered_map.hpp> #include <exception> #include <limits> using namespace std; FlexInfo::FlexInfo(const std::string& flexres, double flexdist, const std::string& ligand, int nflex_, bool nflex_hard_limit_, tee& l) : flex_dist(flexdist), nflex(nflex_), nflex_hard_limit(nflex_hard_limit_), log(l) { using namespace OpenBabel; using namespace std; //first extract comma separated list if (flexres.size() > 0) { vector<string> tokens; boost::split(tokens, flexres, boost::is_any_of(",")); vector<string> chres; for (unsigned i = 0, n = tokens.size(); i < n; i++) { //each token may be either chain:resid or just resid string tok = tokens[i]; boost::split(chres, tok, boost::is_any_of(":")); char chain = 0; int resid = 0; char icode = 0; if (chres.size() >= 2) { if (chres[0].size() != 1) log << "WARNING: chain specification not single character " << chres[0] << "\n"; chain = chres[0][0]; //if empty will be null which is what is desired resid = boost::lexical_cast<int>(chres[1]); if (chres.size() == 3) { // Insertion code is present if(chres[2].size() == 1){ // Check that icode is single char icode = chres[2][0]; } else{ // Invalid icode log << "WARNING: ignoring invalid chain:resid:icode specifier " << tok << "\n"; continue; } } } else if (chres.size() == 1) { resid = boost::lexical_cast<int>(chres[0]); } else { log << "WARNING: ignoring invalid chain:resid specifier " << tok << "\n"; continue; } residues.insert(tuple<char, int, char>(chain, resid, icode)); } } if (ligand.size() > 0 && flex_dist > 0) { //next read ligand for distance checking obmol_opener opener; OBConversion conv; opener.openForInput(conv, ligand); conv.Read(&distligand); //first ligand only } } //return true if residue isn't flexible static bool isInflexible(const string& resname) { return resname == "ALA" || resname == "GLY" || resname == "PRO"; } //remove inflexible residues from residues set //the receptor is needed because we don't store the residue name void FlexInfo::sanitizeResidues(OpenBabel::OBMol& receptor) { using namespace OpenBabel; if(!hasContent()) return; OBResidueIterator ritr, rend; OBResidue *firstres = receptor.BeginResidue(ritr); char defaultch = ' '; if (firstres) defaultch = firstres->GetChain(); // Iterate over all receptor residues for (ritr = receptor.BeginResidues(), rend = receptor.EndResidues(); ritr != rend; ++ritr) { OBResidue *r = *ritr; char ch = r->GetChain(); int resid = r->GetNum(); char icode = r->GetInsertionCode(); std::string resname = r->GetName(); if(ch == 0)ch = defaultch; //substitute default chain for unspecified chain tuple<char,int,char> res(ch,resid,icode); if (residues.count(res) > 0) { // Residue in user-specified flexible residues if (isInflexible(resname)) { // Residue can't be flexible residues.erase(res); // Remove residue from list of flexible residues log << "WARNING: Removing non-flexible residue " << resname; log << " " << ch << ":" << resid << ":" << icode << "\n"; } } } } void FlexInfo::keepNearestResidues( const OpenBabel::OBMol& rigid, std::unordered_map<std::size_t, double>& residues_distances){ using namespace OpenBabel; // Loop over residue list and compute minimum distances for(auto& resdist : residues_distances){ // Current residue (among flexible ones) std::size_t residx = resdist.first; // Key OBResidue* res = rigid.GetResidue(residx); // Minimum distance between ligand and current residue atoms double d2; // Loop over ligand atoms FOR_ATOMS_OF_MOL(alig, distligand) { vector3 al = alig->GetVector(); // Loop over residue atoms for(const auto ares: res->GetAtoms()){ if(!isSideChain(res->GetAtomID(ares))) continue; // skip backbone vector3 ar = ares->GetVector(); d2 = al.distSq(ar); if (d2 < resdist.second) { resdist.second = d2; } } } } // std::map is sorted by keys std::map<double, std::size_t> residues_distances_sorted; for(const auto& resdist : residues_distances){ residues_distances_sorted.insert({resdist.second, resdist.first}); } residues.clear(); std::size_t res_added = 0; for (const auto& resdist : residues_distances_sorted) { if(res_added == nflex){ break; } OBResidue* residue = rigid.GetResidue(resdist.second); char ch = residue->GetChain(); int resid = residue->GetNum(); char icode = residue->GetInsertionCode(); residues.insert(std::tuple<char, int, char>(ch, resid, icode)); res_added++; } } bool FlexInfo::isSideChain(std::string aid){ boost::trim(aid); return aid != "CA" && aid != "N" && aid != "C" && aid != "O" && aid != "H" && aid != "HN"; } void FlexInfo::extractFlex(OpenBabel::OBMol& receptor, OpenBabel::OBMol& rigid, std::string& flexpdbqt) { using namespace OpenBabel; rigid = receptor; rigid.SetChainsPerceived(true); //OB bug workaround flexpdbqt.clear(); //identify residues close to distligand here Box b; b.add_ligand_box(distligand); b.expand(flex_dist); double flsq = flex_dist * flex_dist; std::unordered_map<std::size_t, double> residues_distances; FOR_ATOMS_OF_MOL(a, rigid){ if(a->GetAtomicNum() == 1) continue; //heavy atoms only if (a->GetResidue() != NULL){ // Check // TODO: @RMeli figure out exactly then this happens if (!isSideChain(a->GetResidue()->GetAtomID(&(*a)))) continue; // skip backbone } vector3 v = a->GetVector(); if (b.ptIn(v.x(), v.y(), v.z())) { //in box, see if any atoms are close enough FOR_ATOMS_OF_MOL(b, distligand) { vector3 bv = b->GetVector(); if (v.distSq(bv) < flsq) { //process residue OBResidue *residue = a->GetResidue(); if (residue) { char ch = residue->GetChain(); int resid = residue->GetNum(); char icode = residue->GetInsertionCode(); if(!isInflexible(residue->GetName())) { residues_distances.insert({residue->GetIdx(), std::numeric_limits<double>::max()}); residues.insert(std::tuple<char, int, char>(ch, resid, icode)); } } break; } } } } //replace any empty chains with first chain in mol OBResidueIterator ritr; OBResidue *firstres = rigid.BeginResidue(ritr); if (firstres) defaultch = firstres->GetChain(); sanitizeResidues(receptor); if(nflex > -1 && residues.size() > nflex && nflex_hard_limit){ throw std::runtime_error("Number of flexible residues found is higher than --flex_limit."); } else if(nflex > -1 && residues.size() > nflex){ log << "WARNING: Only the flex_max residues closer to the ligand are considered as flexible.\n"; keepNearestResidues(rigid, residues_distances); } std::vector<std::tuple<char, int, char> > sortedres(residues.begin(), residues.end()); for (unsigned i = 0, n = sortedres.size(); i < n; i++) { if (get<0>(sortedres[i]) == 0) get<0>(sortedres[i]) = defaultch; } sort(sortedres.begin(), sortedres.end()); //reinsert residues now with default chain residues.clear(); residues.insert(sortedres.begin(), sortedres.end()); OBConversion conv; conv.SetOutFormat("PDBQT"); conv.AddOption("s", OBConversion::OUTOPTIONS); //flexible residue rigid.BeginModify(); int flexcnt = 0; //identify atoms that have to be in flexible component //this is the side chain and CA, but _not_ the C and N for (OBResidueIterator ritr = rigid.BeginResidues(), rend = rigid.EndResidues(); ritr != rend; ++ritr) { OBResidue *r = *ritr; char ch = r->GetChain(); int resid = r->GetNum(); char icode = r->GetInsertionCode(); std::tuple<char, int, char> chres(ch, resid, icode); if (residues.count(chres)) { flexcnt++; //create a separate molecule for each flexible residue OBMol flex; std::vector<OBAtom*> flexatoms; //rigid atom ptrs that should be flexible boost::unordered_map<OBAtom*, int> flexmap; //map rigid atom ptrs to atom indices in flex //make absolutely sure that CA is the first atom //first bond is rigid, so take both CA and C for (OBAtomIterator aitr = r->BeginAtoms(), aend = r->EndAtoms(); aitr != aend; ++aitr) { OBAtom *a = *aitr; std::string aid = r->GetAtomID(a); boost::trim(aid); if (aid == "CA" || aid == "C") { flexatoms.push_back(a); flex.AddAtom(*a); flexmap[a] = flex.NumAtoms(); //after addatom since indexed by } } for (OBAtomIterator aitr = r->BeginAtoms(), aend = r->EndAtoms(); aitr != aend; ++aitr) { OBAtom *a = *aitr; std::string aid = r->GetAtomID(a); boost::trim(aid); if (aid != "CA" && aid != "N" && aid != "C" && aid != "O" && aid != "H" && aid != "HN" && //leave backbone alone other than CA which is handled above !a->IsNonPolarHydrogen()) { flexatoms.push_back(a); flex.AddAtom(*a); flexmap[a] = flex.NumAtoms(); //after addatom since indexed by } } //now add bonds - at some point I should add functions to openbabel to do this.. for (unsigned i = 0, n = flexatoms.size(); i < n; i++) { OBAtom *a = flexatoms[i]; FOR_BONDS_OF_ATOM(b, a){ OBBond& bond = *b; //just do one direction, if first atom is a //and second atom is a flexatom need to add bond if(a == bond.GetBeginAtom() && flexmap.count(bond.GetEndAtom())) { flex.AddBond(flexmap[a],flexmap[bond.GetEndAtom()],bond.GetBondOrder(), bond.GetFlags()); } } } flex.AddResidue(*r); OBResidue *newres = flex.GetResidue(0); if (newres) { //add all atoms with proper atom ids for (unsigned i = 0, n = flexatoms.size(); i < n; i++) { OBAtom *origa = flexatoms[i]; OBAtom *newa = flex.GetAtom(flexmap[origa]); newres->RemoveAtom(origa); newres->AddAtom(newa); newa->SetResidue(newres); std::string aid = r->GetAtomID(origa); newres->SetAtomID(newa, aid); } } std::string flexres = conv.WriteString(&flex); if (newres) { //the pdbqt writing code breaks flex into fragments, in the process it loses all residue information //so we rewrite the strings.. std::vector<std::string> tokens; std::string resn = newres->GetName(); while (resn.size() < 3) resn += " "; std::string resnum = boost::lexical_cast<std::string>(newres->GetNum()); while (resnum.size() < 4) resnum = " " + resnum; char ch = newres->GetChain(); char icode = newres->GetInsertionCode(); boost::split(tokens, flexres, boost::is_any_of("\n")); for (unsigned i = 0, n = tokens.size(); i < n; i++) { std::string line = tokens[i]; if (line.size() > 25) { //replace UNL with resn for (unsigned p = 0; p < 3; p++) { line[17 + p] = resn[p]; } //resid for (unsigned p = 0; p < 4; p++) { line[22 + p] = resnum[p]; } if(icode > 0) line[26] = icode; line[21] = ch; } if (line.size() > 0) { flexpdbqt += line; flexpdbqt += "\n"; } } } else { flexpdbqt += flexres; } //remove flexatoms from rigid for (unsigned i = 0, n = flexatoms.size(); i < n; i++) { OBAtom *a = flexatoms[i]; rigid.DeleteAtom(a); } } //end if residue } if(flexcnt != residues.size()) { log << "WARNING: Only identified " << flexcnt << " of " << residues.size() << " requested flexible residues.\n"; } rigid.EndModify(); } void FlexInfo::printFlex() const{ // Residues are stored as unordered_set // Sort before printing std::vector<std::tuple<char, int, char> > sortedres(residues.begin(), residues.end()); sort(sortedres.begin(), sortedres.end()); if (sortedres.size() > 0) { log << "Flexible residues:"; for (unsigned i = 0, n = sortedres.size(); i < n; i++) { log << " " << get<0>(sortedres[i]) << ":" << get<1>(sortedres[i]); if(get<2>(sortedres[i]) > 0) log << ":" << get<2>(sortedres[i]); } log << "\n"; } }<|endoftext|>
<commit_before>#include <algorithm> #include <cfloat> #include <iostream> #include <iterator> #include <list> #include <numeric> #include <vector> struct action { float lin_vel; float ang_vel; float duration; }; // For generating a sequence of equidistant values struct double_inc_iterator : std::iterator<std::forward_iterator_tag, double> { double_inc_iterator(double initial, double inc = 1.0) : _value(initial), _inc(inc) {} value_type operator*() const { return _value; } double_inc_iterator& operator++() { _value += _inc; return *this; } bool operator==(double_inc_iterator const& r) const { return _value >= r._value; } bool operator!=(double_inc_iterator const& r) const { return !(*this == r); } value_type _value; value_type _inc; }; class GenericActionSpace { public: GenericActionSpace(float lin_min, float lin_max, float lin_samples, float ang_min, float ang_max, float ang_samples, float dur_min, float dur_max, float dur_samples) : lin_min(lin_min), lin_max(lin_max), lin_samples(lin_samples), ang_min(ang_min), ang_max(ang_max), ang_samples(ang_samples), dur_min(dur_min), dur_max(dur_max), dur_samples(dur_samples) { generate_actions(); } std::list<action> get_action_space() { return actions; } private: float lin_min{ 0 }; float lin_max{ 0 }; float lin_samples{ 0 }; float ang_min{ 0 }; float ang_max{ 0 }; float ang_samples{ 0 }; float dur_min{ 0 }; float dur_max{ 0 }; float dur_samples{ 0 }; std::list<action> actions; void generate_actions() { std::vector<double> lin_choices = create_choices(lin_min, lin_max, lin_samples, true); std::vector<double> ang_choices = create_choices(ang_min, ang_max, ang_samples, true); std::vector<double> dur_choices = create_choices(dur_min, dur_max, dur_samples, false); for (double dur_choice : dur_choices) { for (double lin_choice : lin_choices) { for (double ang_choice : ang_choices) { if (!(lin_choice == ang_choice && lin_choice == 0) || dur_choice == 0) { action a; a.lin_vel = lin_choice; a.ang_vel = ang_choice; a.duration = dur_choice; actions.push_back(a); } } } } } // Helper function to generate [num] number of choices from [start] to [stop] // include_zero : True to add zero to choices, False to not // This allows for 0 verlocity in either the linear or angular direction std::vector<double> create_choices(double start, double stop, int num, bool include_zero) { double step = (stop - start) / (num - 1); std::vector<double> choices(double_inc_iterator(start, step), double_inc_iterator(stop + FLT_EPSILON)); if (include_zero) { bool contains_zero = false; if (std::find(choices.begin(), choices.end(), 0) != choices.end()) { contains_zero = true; } if (!contains_zero) { choices.insert(choices.begin(), 0); } } return choices; } }; int main() { GenericActionSpace gen_space (10, 100, 5, 10, 100, 5, 1, 5, 5); std::list<action> actions = gen_space.get_action_space(); } <commit_msg>Starting to make the helper functions for oos<commit_after>#include <algorithm> #include <cfloat> #include <iostream> #include <iterator> #include <list> #include <math.h> #include <numeric> #include <vector> struct Action { double lin_vel; double ang_vel; double duration; }; struct Pose { double pos_x; double pos_y; double pos_z; double angle_z; }; struct Object_Oriented_Action { Pose pose; Action action; }; // For generating a sequence of equidistant values struct double_inc_iterator : std::iterator<std::forward_iterator_tag, double> { double_inc_iterator(double initial, double inc = 1.0) : _value(initial), _inc(inc) {} value_type operator*() const { return _value; } double_inc_iterator& operator++() { _value += _inc; return *this; } bool operator==(double_inc_iterator const& r) const { return _value >= r._value; } bool operator!=(double_inc_iterator const& r) const { return !(*this == r); } value_type _value; value_type _inc; }; // Utility function to generate [num] number of choices from [start] to [stop] // include_zero : True to add zero to choices, False to not // This allows for 0 verlocity in either the linear or angular direction std::vector<double> create_choices(double start, double stop, int num, bool include_zero) { double step = (stop - start) / (num - 1); std::vector<double> choices(double_inc_iterator(start, step), double_inc_iterator(stop + FLT_EPSILON)); if (include_zero) { bool contains_zero = false; if (std::find(choices.begin(), choices.end(), 0) != choices.end()) { contains_zero = true; } if (!contains_zero) { choices.insert(choices.begin(), 0); } } return choices; } class GenericActionSpace { public: GenericActionSpace(double lin_min, double lin_max, double lin_samples, double ang_min, double ang_max, double ang_samples, double dur_min, double dur_max, double dur_samples) : lin_min(lin_min), lin_max(lin_max), lin_samples(lin_samples), ang_min(ang_min), ang_max(ang_max), ang_samples(ang_samples), dur_min(dur_min), dur_max(dur_max), dur_samples(dur_samples) { generate_actions(); } std::list<Action> get_action_space() { return actions; } private: double lin_min{ 0 }; double lin_max{ 0 }; double lin_samples{ 0 }; double ang_min{ 0 }; double ang_max{ 0 }; double ang_samples{ 0 }; double dur_min{ 0 }; double dur_max{ 0 }; double dur_samples{ 0 }; std::list<Action> actions; void generate_actions() { std::vector<double> lin_choices = create_choices(lin_min, lin_max, lin_samples, true); std::vector<double> ang_choices = create_choices(ang_min, ang_max, ang_samples, true); std::vector<double> dur_choices = create_choices(dur_min, dur_max, dur_samples, false); for (double dur_choice : dur_choices) { for (double lin_choice : lin_choices) { for (double ang_choice : ang_choices) { if (!(lin_choice == ang_choice && lin_choice == 0) || dur_choice == 0) { Action a {lin_choice, ang_choice, dur_choice}; actions.push_back(a); } } } } } }; class ObjectOrientedActionSpace { public: ObjectOrientedActionSpace(Pose pose, int samples, double lin_min, double lin_max, double lin_samples, double dur_min, double dur_max, double dur_samples) : pose(pose), samples(samples), lin_min(lin_min), lin_max(lin_max), lin_samples(lin_samples), dur_min(dur_min), dur_max(dur_max), dur_samples(dur_samples) { generate_actions(); } private: Pose pose{ 0, 0, 0, 0 }; double samples{ 0 }; double lin_min{ 0 }; double lin_max{ 0 }; double lin_samples{ 0 }; double dur_min{ 0 }; double dur_max{ 0 }; double dur_samples{ 0 }; std::list<Object_Oriented_Action> actions; void generate_actions(double h_offset=40, double v_offset=60) { generate_offsets(h_offset, v_offset); } void generate_offsets(double h_offset, double v_offset) { std::vector<double> choices; if (samples == 1) { choices.push_back(0); } else { choices = create_choices(-h_offset, h_offset, samples, true); } find_sides(pose.angle_z); } std::vector<double> find_sides(double angle) { // std::cout << angle; std::vector<double> sides; sides.push_back(angle); for (int i = 0; i < 3; i++) { angle -= M_PI / 2; std::cout << angle; } return sides; } }; int main() { GenericActionSpace gen_space (10, 100, 5, 10, 100, 5, 1, 5, 5); std::list<Action> actions = gen_space.get_action_space(); for (auto a : actions) { std::cout << a.lin_vel << ", " << a.ang_vel << ", " << a.duration << "\n"; } Pose pose{100, 200, 10, 0.5}; ObjectOrientedActionSpace oos (pose, 3, 10, 100, 3, 1, 5, 3); } <|endoftext|>
<commit_before>/* ** Copyright 2011-2013 Merethis ** ** This file is part of Centreon Broker. ** ** Centreon Broker is free software: you can redistribute it and/or ** modify it under the terms of the GNU General Public License version 2 ** as published by the Free Software Foundation. ** ** Centreon Broker 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 ** General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with Centreon Broker. If not, see ** <http://www.gnu.org/licenses/>. */ #include "com/centreon/broker/io/protocols.hh" #include "com/centreon/broker/logging/logging.hh" #include "com/centreon/broker/notification/factory.hh" using namespace com::centreon::broker; // Load count. static unsigned int instances(0); extern "C" { /** * Module deinitialization routine. */ void broker_module_deinit() { // Decrement instance number. if (!--instances) { // Deregister NOTIFICATION layer. io::protocols::instance().unreg("NOTIFICATION"); } return ; } /** * Module initialization routine. * * @param[in] arg Configuration object. */ void broker_module_init(void const* arg) { (void)arg; // Increment instance number. if (!instances++) { // Notification module. logging::info(logging::high) << "NOTIFICATION: module for Centreon Broker " << CENTREON_BROKER_VERSION; // Register Notification layer. io::protocols::instance().reg("NOTIFICATION", notification::factory(), 1, 7); } return ; } /** * Module update routine. * * @param[in] arg Configuration argument. */ void broker_module_update(void const* arg) { return ; } } <commit_msg>Remove update.<commit_after>/* ** Copyright 2011-2013 Merethis ** ** This file is part of Centreon Broker. ** ** Centreon Broker is free software: you can redistribute it and/or ** modify it under the terms of the GNU General Public License version 2 ** as published by the Free Software Foundation. ** ** Centreon Broker 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 ** General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with Centreon Broker. If not, see ** <http://www.gnu.org/licenses/>. */ #include "com/centreon/broker/io/protocols.hh" #include "com/centreon/broker/logging/logging.hh" #include "com/centreon/broker/notification/factory.hh" using namespace com::centreon::broker; // Load count. static unsigned int instances(0); extern "C" { /** * Module deinitialization routine. */ void broker_module_deinit() { // Decrement instance number. if (!--instances) { // Deregister NOTIFICATION layer. io::protocols::instance().unreg("NOTIFICATION"); } return ; } /** * Module initialization routine. * * @param[in] arg Configuration object. */ void broker_module_init(void const* arg) { (void)arg; // Increment instance number. if (!instances++) { // Notification module. logging::info(logging::high) << "NOTIFICATION: module for Centreon Broker " << CENTREON_BROKER_VERSION; // Register Notification layer. io::protocols::instance().reg("NOTIFICATION", notification::factory(), 1, 7); } return ; } } <|endoftext|>
<commit_before>#include <exception> #include <iostream> #include <string> #include <vector> void* operator new(size_t size) { throw std::bad_alloc(); return nullptr; } int my_atoi(const std::string& str) { int value = std::atoi(str.c_str()); if (value == 0 && str == "0") { return value; } if (value != 0) return value; throw std::invalid_argument("Bad argument"); } int main(int argc, char* argv[]) { if (argc < 2) { std::cerr << "" << std::endl; return EXIT_FAILURE; } int* p; try { p = new int; std::cout << my_atoi(argv[1]) << std::endl; delete p; } catch (const std::exception& ex) { std::cerr << "Exception happened " << ex.what() << std::endl; delete p; } catch (const std::bad_alloc& ex) { std::cerr << "Bad Exception happened " << ex.what() << std::endl; } return EXIT_SUCCESS; } <commit_msg>[exception] 5<commit_after>#include <exception> #include <iostream> #include <string> #include <vector> int my_atoi(const std::string& str) { int value = std::atoi(str.c_str()); if (value == 0 && str == "0") { return value; } if (value != 0) return value; throw std::invalid_argument("Bad argument"); } std::vector<int> foo(const std::vector<std::string>& strs) noexcept { std::vector<int> toBeReturned; try { for (const std::string val : strs) { toBeReturned.push_back(my_atoi(val)); } } catch (const std::bad_alloc&) { // .. } return toBeReturned; } int main(int argc, char* argv[]) { if (argc < 3) { std::cerr << "" << std::endl; return EXIT_FAILURE; } std::vector<std::string> vec{argv[1], argv[2]}; try { auto v = foo(vec); for (auto i : v) std::cout << i << std::endl; } catch (const std::exception& ex) { std::cerr << "Exception " << std::endl; } } <|endoftext|>
<commit_before>/******************************************************* * Copyright (c) 2015, ArrayFire * All rights reserved. * * This file is distributed under 3-clause BSD license. * The complete license agreement can be obtained at: * http://arrayfire.com/licenses/BSD-3-Clause ********************************************************/ #pragma once #include <common/Logger.hpp> #include <common/err_common.hpp> #include <common/module_loading.hpp> #include <common/util.hpp> #include <af/backend.h> #include <af/defines.h> #include <spdlog/spdlog.h> #include <array> #include <cstdlib> #include <string> #include <unordered_map> namespace unified { const int NUM_BACKENDS = 3; #define UNIFIED_ERROR_LOAD_LIB() \ AF_RETURN_ERROR( \ "Failed to load dynamic library. " \ "See http://www.arrayfire.com/docs/unifiedbackend.htm " \ "for instructions to set up environment for Unified backend.", \ AF_ERR_LOAD_LIB) static inline int backend_index(af::Backend be) { switch (be) { case AF_BACKEND_CPU: return 0; case AF_BACKEND_CUDA: return 1; case AF_BACKEND_OPENCL: return 2; default: return -1; } } class AFSymbolManager { public: static AFSymbolManager& getInstance(); ~AFSymbolManager(); unsigned getBackendCount(); int getAvailableBackends(); af_err setBackend(af::Backend bnkd); af::Backend getActiveBackend() { return activeBackend; } LibHandle getHandle() { return activeHandle; } spdlog::logger* getLogger(); protected: AFSymbolManager(); // Following two declarations are required to // avoid copying accidental copy/assignment // of instance returned by getInstance to other // variables AFSymbolManager(AFSymbolManager const&); void operator=(AFSymbolManager const&); private: LibHandle bkndHandles[NUM_BACKENDS]; LibHandle activeHandle; LibHandle defaultHandle; unsigned numBackends; int backendsAvailable; af_backend activeBackend; af_backend defaultBackend; std::shared_ptr<spdlog::logger> logger; }; namespace { bool checkArray(af_backend activeBackend, const af_array a) { // Convert af_array into int to retrieve the backend info. // See ArrayInfo.hpp for more af_backend backend = (af_backend)0; // This condition is required so that the invalid args tests for unified // backend return the expected error rather than AF_ERR_ARR_BKND_MISMATCH // Since a = 0, does not have a backend specified, it should be a // AF_ERR_ARG instead of AF_ERR_ARR_BKND_MISMATCH if (a == 0) return true; af_get_backend_id(&backend, a); return backend == activeBackend; } bool checkArray(af_backend activeBackend, const af_array* a) { if (a) { return checkArray(activeBackend, *a); } else { return true; } } bool checkArrays(af_backend activeBackend) { UNUSED(activeBackend); // Dummy return true; } } // namespace template<typename T, typename... Args> bool checkArrays(af_backend activeBackend, T a, Args... arg) { return checkArray(activeBackend, a) && checkArrays(activeBackend, arg...); } } // namespace unified /// Checks if the active backend and the af_arrays are the same. /// /// Checks if the active backend and the af_array's backend match. If they do /// not match, an error is returned. This macro accepts pointer to af_arrays /// and af_arrays. Null pointers to af_arrays are considered acceptable. /// /// \param[in] Any number of af_arrays or pointer to af_arrays #define CHECK_ARRAYS(...) \ do { \ af_backend backendId = \ unified::AFSymbolManager::getInstance().getActiveBackend(); \ if (!unified::checkArrays(backendId, __VA_ARGS__)) \ AF_RETURN_ERROR("Input array does not belong to current backend", \ AF_ERR_ARR_BKND_MISMATCH); \ } while (0) #define CALL(FUNCTION, ...) \ using af_func = std::add_pointer<decltype(FUNCTION)>::type; \ thread_local auto& instance = unified::AFSymbolManager::getInstance(); \ thread_local af_backend index_ = instance.getActiveBackend(); \ thread_local af_func func = \ (af_func)common::getFunctionPointer(instance.getHandle(), __func__); \ if (index_ != instance.getActiveBackend()) { \ index_ = instance.getActiveBackend(); \ func = (af_func)common::getFunctionPointer(instance.getHandle(), \ __func__); \ } \ return func(__VA_ARGS__); #define CALL_NO_PARAMS(FUNCTION) CALL(FUNCTION) #define LOAD_SYMBOL() \ common::getFunctionPointer( \ unified::AFSymbolManager::getInstance().getHandle(), __FUNCTION__) <commit_msg>Fix segfault in the CALL macro when no backends are found<commit_after>/******************************************************* * Copyright (c) 2015, ArrayFire * All rights reserved. * * This file is distributed under 3-clause BSD license. * The complete license agreement can be obtained at: * http://arrayfire.com/licenses/BSD-3-Clause ********************************************************/ #pragma once #include <common/Logger.hpp> #include <common/err_common.hpp> #include <common/module_loading.hpp> #include <common/util.hpp> #include <af/backend.h> #include <af/defines.h> #include <spdlog/spdlog.h> #include <array> #include <cstdlib> #include <string> #include <unordered_map> namespace unified { const int NUM_BACKENDS = 3; #define UNIFIED_ERROR_LOAD_LIB() \ AF_RETURN_ERROR( \ "Failed to load dynamic library. " \ "See http://www.arrayfire.com/docs/unifiedbackend.htm " \ "for instructions to set up environment for Unified backend.", \ AF_ERR_LOAD_LIB) static inline int backend_index(af::Backend be) { switch (be) { case AF_BACKEND_CPU: return 0; case AF_BACKEND_CUDA: return 1; case AF_BACKEND_OPENCL: return 2; default: return -1; } } class AFSymbolManager { public: static AFSymbolManager& getInstance(); ~AFSymbolManager(); unsigned getBackendCount(); int getAvailableBackends(); af_err setBackend(af::Backend bnkd); af::Backend getActiveBackend() { return activeBackend; } LibHandle getHandle() { return activeHandle; } spdlog::logger* getLogger(); protected: AFSymbolManager(); // Following two declarations are required to // avoid copying accidental copy/assignment // of instance returned by getInstance to other // variables AFSymbolManager(AFSymbolManager const&); void operator=(AFSymbolManager const&); private: LibHandle bkndHandles[NUM_BACKENDS]; LibHandle activeHandle; LibHandle defaultHandle; unsigned numBackends; int backendsAvailable; af_backend activeBackend; af_backend defaultBackend; std::shared_ptr<spdlog::logger> logger; }; namespace { bool checkArray(af_backend activeBackend, const af_array a) { // Convert af_array into int to retrieve the backend info. // See ArrayInfo.hpp for more af_backend backend = (af_backend)0; // This condition is required so that the invalid args tests for unified // backend return the expected error rather than AF_ERR_ARR_BKND_MISMATCH // Since a = 0, does not have a backend specified, it should be a // AF_ERR_ARG instead of AF_ERR_ARR_BKND_MISMATCH if (a == 0) return true; af_get_backend_id(&backend, a); return backend == activeBackend; } bool checkArray(af_backend activeBackend, const af_array* a) { if (a) { return checkArray(activeBackend, *a); } else { return true; } } bool checkArrays(af_backend activeBackend) { UNUSED(activeBackend); // Dummy return true; } } // namespace template<typename T, typename... Args> bool checkArrays(af_backend activeBackend, T a, Args... arg) { return checkArray(activeBackend, a) && checkArrays(activeBackend, arg...); } } // namespace unified /// Checks if the active backend and the af_arrays are the same. /// /// Checks if the active backend and the af_array's backend match. If they do /// not match, an error is returned. This macro accepts pointer to af_arrays /// and af_arrays. Null pointers to af_arrays are considered acceptable. /// /// \param[in] Any number of af_arrays or pointer to af_arrays #define CHECK_ARRAYS(...) \ do { \ af_backend backendId = \ unified::AFSymbolManager::getInstance().getActiveBackend(); \ if (!unified::checkArrays(backendId, __VA_ARGS__)) \ AF_RETURN_ERROR("Input array does not belong to current backend", \ AF_ERR_ARR_BKND_MISMATCH); \ } while (0) #define CALL(FUNCTION, ...) \ using af_func = std::add_pointer<decltype(FUNCTION)>::type; \ thread_local auto& instance = unified::AFSymbolManager::getInstance(); \ thread_local af_backend index_ = instance.getActiveBackend(); \ if (instance.getHandle()) { \ thread_local af_func func = (af_func)common::getFunctionPointer( \ instance.getHandle(), __func__); \ if (index_ != instance.getActiveBackend()) { \ index_ = instance.getActiveBackend(); \ func = (af_func)common::getFunctionPointer(instance.getHandle(), \ __func__); \ } \ return func(__VA_ARGS__); \ } else { \ AF_RETURN_ERROR("ArrayFire couldn't locate any backends.", \ AF_ERR_LOAD_LIB); \ } #define CALL_NO_PARAMS(FUNCTION) CALL(FUNCTION) #define LOAD_SYMBOL() \ common::getFunctionPointer( \ unified::AFSymbolManager::getInstance().getHandle(), __FUNCTION__) <|endoftext|>
<commit_before>/* * imageviewer2.cpp * Copyright (C) 2009-2015 by MegaMol Team * Alle Rechte vorbehalten. */ #include "stdafx.h" #include "imageviewer2/imageviewer2.h" #include "mmcore/api/MegaMolCore.std.h" #include "mmcore/utility/plugins/Plugin200Instance.h" #include "mmcore/versioninfo.h" #include "vislib/vislibversion.h" #include "imageviewer2/ImageViewer.h" /* anonymous namespace hides this type from any other object files */ namespace { /** Implementing the instance class of this plugin */ class plugin_instance : public ::megamol::core::utility::plugins::Plugin200Instance { public: /** ctor */ plugin_instance(void) : ::megamol::core::utility::plugins::Plugin200Instance( /* machine-readable plugin assembly name */ "imageviewer2", // TODO: Change this! /* human-readable plugin description */ "Describing imageviewer2 (TODO: Change this!)") { // here we could perform addition initialization }; /** Dtor */ virtual ~plugin_instance(void) { // here we could perform addition de-initialization } /** Registers modules and calls */ virtual void registerClasses(void) { // register modules here: this->module_descriptions.RegisterAutoDescription<megamol::imageviewer2::ImageRenderer>(); // // TODO: Register your plugin's modules here // like: // this->module_descriptions.RegisterAutoDescription<megamol::imageviewer2::MyModule1>(); // this->module_descriptions.RegisterAutoDescription<megamol::imageviewer2::MyModule2>(); // ... // // register calls here: // // TODO: Register your plugin's calls here // like: // this->call_descriptions.RegisterAutoDescription<megamol::imageviewer2::MyCall1>(); // this->call_descriptions.RegisterAutoDescription<megamol::imageviewer2::MyCall2>(); // ... // } MEGAMOLCORE_PLUGIN200UTIL_IMPLEMENT_plugininstance_connectStatics }; } /* * mmplgPluginAPIVersion */ IMAGEVIEWER2_API int mmplgPluginAPIVersion(void) { MEGAMOLCORE_PLUGIN200UTIL_IMPLEMENT_mmplgPluginAPIVersion } /* * mmplgGetPluginCompatibilityInfo */ IMAGEVIEWER2_API ::megamol::core::utility::plugins::PluginCompatibilityInfo * mmplgGetPluginCompatibilityInfo( ::megamol::core::utility::plugins::ErrorCallback onError) { // compatibility information with core and vislib using ::megamol::core::utility::plugins::PluginCompatibilityInfo; using ::megamol::core::utility::plugins::LibraryVersionInfo; PluginCompatibilityInfo *ci = new PluginCompatibilityInfo; ci->libs_cnt = 2; ci->libs = new LibraryVersionInfo[2]; SetLibraryVersionInfo(ci->libs[0], "MegaMolCore", MEGAMOL_CORE_MAJOR_VER, MEGAMOL_CORE_MINOR_VER, MEGAMOL_CORE_COMP_REV, 0 #if defined(DEBUG) || defined(_DEBUG) | MEGAMOLCORE_PLUGIN200UTIL_FLAGS_DEBUG_BUILD #endif #if defined(MEGAMOL_CORE_DIRTY) && (MEGAMOL_CORE_DIRTY != 0) | MEGAMOLCORE_PLUGIN200UTIL_FLAGS_DIRTY_BUILD #endif ); SetLibraryVersionInfo(ci->libs[1], "vislib", vislib::VISLIB_VERSION_MAJOR, vislib::VISLIB_VERSION_MINOR, vislib::VISLIB_VERSION_REVISION, 0 #if defined(DEBUG) || defined(_DEBUG) | MEGAMOLCORE_PLUGIN200UTIL_FLAGS_DEBUG_BUILD #endif #if defined(VISLIB_DIRTY_BUILD) && (VISLIB_DIRTY_BUILD != 0) | MEGAMOLCORE_PLUGIN200UTIL_FLAGS_DIRTY_BUILD #endif ); // // If you want to test additional compatibilties, add the corresponding versions here // return ci; } /* * mmplgReleasePluginCompatibilityInfo */ IMAGEVIEWER2_API void mmplgReleasePluginCompatibilityInfo( ::megamol::core::utility::plugins::PluginCompatibilityInfo* ci) { // release compatiblity data on the correct heap MEGAMOLCORE_PLUGIN200UTIL_IMPLEMENT_mmplgReleasePluginCompatibilityInfo(ci) } /* * mmplgGetPluginInstance */ IMAGEVIEWER2_API ::megamol::core::utility::plugins::AbstractPluginInstance* mmplgGetPluginInstance( ::megamol::core::utility::plugins::ErrorCallback onError) { MEGAMOLCORE_PLUGIN200UTIL_IMPLEMENT_mmplgGetPluginInstance(plugin_instance, onError) } /* * mmplgReleasePluginInstance */ IMAGEVIEWER2_API void mmplgReleasePluginInstance( ::megamol::core::utility::plugins::AbstractPluginInstance* pi) { MEGAMOLCORE_PLUGIN200UTIL_IMPLEMENT_mmplgReleasePluginInstance(pi) } <commit_msg>forgot to fix imageviewer include<commit_after>/* * imageviewer2.cpp * Copyright (C) 2009-2015 by MegaMol Team * Alle Rechte vorbehalten. */ #include "stdafx.h" #include "imageviewer2/imageviewer2.h" #include "mmcore/api/MegaMolCore.std.h" #include "mmcore/utility/plugins/Plugin200Instance.h" #include "mmcore/versioninfo.h" #include "vislib/vislibversion.h" #include "imageviewer2/ImageRenderer.h" /* anonymous namespace hides this type from any other object files */ namespace { /** Implementing the instance class of this plugin */ class plugin_instance : public ::megamol::core::utility::plugins::Plugin200Instance { public: /** ctor */ plugin_instance(void) : ::megamol::core::utility::plugins::Plugin200Instance( /* machine-readable plugin assembly name */ "imageviewer2", // TODO: Change this! /* human-readable plugin description */ "Describing imageviewer2 (TODO: Change this!)") { // here we could perform addition initialization }; /** Dtor */ virtual ~plugin_instance(void) { // here we could perform addition de-initialization } /** Registers modules and calls */ virtual void registerClasses(void) { // register modules here: this->module_descriptions.RegisterAutoDescription<megamol::imageviewer2::ImageRenderer>(); // // TODO: Register your plugin's modules here // like: // this->module_descriptions.RegisterAutoDescription<megamol::imageviewer2::MyModule1>(); // this->module_descriptions.RegisterAutoDescription<megamol::imageviewer2::MyModule2>(); // ... // // register calls here: // // TODO: Register your plugin's calls here // like: // this->call_descriptions.RegisterAutoDescription<megamol::imageviewer2::MyCall1>(); // this->call_descriptions.RegisterAutoDescription<megamol::imageviewer2::MyCall2>(); // ... // } MEGAMOLCORE_PLUGIN200UTIL_IMPLEMENT_plugininstance_connectStatics }; } /* * mmplgPluginAPIVersion */ IMAGEVIEWER2_API int mmplgPluginAPIVersion(void) { MEGAMOLCORE_PLUGIN200UTIL_IMPLEMENT_mmplgPluginAPIVersion } /* * mmplgGetPluginCompatibilityInfo */ IMAGEVIEWER2_API ::megamol::core::utility::plugins::PluginCompatibilityInfo * mmplgGetPluginCompatibilityInfo( ::megamol::core::utility::plugins::ErrorCallback onError) { // compatibility information with core and vislib using ::megamol::core::utility::plugins::PluginCompatibilityInfo; using ::megamol::core::utility::plugins::LibraryVersionInfo; PluginCompatibilityInfo *ci = new PluginCompatibilityInfo; ci->libs_cnt = 2; ci->libs = new LibraryVersionInfo[2]; SetLibraryVersionInfo(ci->libs[0], "MegaMolCore", MEGAMOL_CORE_MAJOR_VER, MEGAMOL_CORE_MINOR_VER, MEGAMOL_CORE_COMP_REV, 0 #if defined(DEBUG) || defined(_DEBUG) | MEGAMOLCORE_PLUGIN200UTIL_FLAGS_DEBUG_BUILD #endif #if defined(MEGAMOL_CORE_DIRTY) && (MEGAMOL_CORE_DIRTY != 0) | MEGAMOLCORE_PLUGIN200UTIL_FLAGS_DIRTY_BUILD #endif ); SetLibraryVersionInfo(ci->libs[1], "vislib", vislib::VISLIB_VERSION_MAJOR, vislib::VISLIB_VERSION_MINOR, vislib::VISLIB_VERSION_REVISION, 0 #if defined(DEBUG) || defined(_DEBUG) | MEGAMOLCORE_PLUGIN200UTIL_FLAGS_DEBUG_BUILD #endif #if defined(VISLIB_DIRTY_BUILD) && (VISLIB_DIRTY_BUILD != 0) | MEGAMOLCORE_PLUGIN200UTIL_FLAGS_DIRTY_BUILD #endif ); // // If you want to test additional compatibilties, add the corresponding versions here // return ci; } /* * mmplgReleasePluginCompatibilityInfo */ IMAGEVIEWER2_API void mmplgReleasePluginCompatibilityInfo( ::megamol::core::utility::plugins::PluginCompatibilityInfo* ci) { // release compatiblity data on the correct heap MEGAMOLCORE_PLUGIN200UTIL_IMPLEMENT_mmplgReleasePluginCompatibilityInfo(ci) } /* * mmplgGetPluginInstance */ IMAGEVIEWER2_API ::megamol::core::utility::plugins::AbstractPluginInstance* mmplgGetPluginInstance( ::megamol::core::utility::plugins::ErrorCallback onError) { MEGAMOLCORE_PLUGIN200UTIL_IMPLEMENT_mmplgGetPluginInstance(plugin_instance, onError) } /* * mmplgReleasePluginInstance */ IMAGEVIEWER2_API void mmplgReleasePluginInstance( ::megamol::core::utility::plugins::AbstractPluginInstance* pi) { MEGAMOLCORE_PLUGIN200UTIL_IMPLEMENT_mmplgReleasePluginInstance(pi) } <|endoftext|>
<commit_before>/*************************************************************************/ /* camera_server.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "camera_server.h" #include "servers/camera/camera_feed.h" #include "visual_server.h" //////////////////////////////////////////////////////// // CameraServer CameraServer::CreateFunc CameraServer::create_func = NULL; void CameraServer::_bind_methods() { ClassDB::bind_method(D_METHOD("get_feed", "index"), &CameraServer::get_feed); ClassDB::bind_method(D_METHOD("get_feed_count"), &CameraServer::get_feed_count); ClassDB::bind_method(D_METHOD("feeds"), &CameraServer::get_feeds); ClassDB::bind_method(D_METHOD("add_feed", "feed"), &CameraServer::add_feed); ClassDB::bind_method(D_METHOD("remove_feed", "feed"), &CameraServer::remove_feed); ADD_SIGNAL(MethodInfo("camera_feed_added", PropertyInfo(Variant::INT, "id"))); ADD_SIGNAL(MethodInfo("camera_feed_removed", PropertyInfo(Variant::INT, "id"))); BIND_ENUM_CONSTANT(FEED_RGBA_IMAGE); BIND_ENUM_CONSTANT(FEED_YCBCR_IMAGE); BIND_ENUM_CONSTANT(FEED_Y_IMAGE); BIND_ENUM_CONSTANT(FEED_CBCR_IMAGE); }; CameraServer *CameraServer::singleton = NULL; CameraServer *CameraServer::get_singleton() { return singleton; }; int CameraServer::get_free_id() { bool id_exists = true; int newid = 0; // find a free id while (id_exists) { newid++; id_exists = false; for (int i = 0; i < feeds.size() && !id_exists; i++) { if (feeds[i]->get_id() == newid) { id_exists = true; }; }; }; return newid; }; int CameraServer::get_feed_index(int p_id) { for (int i = 0; i < feeds.size(); i++) { if (feeds[i]->get_id() == p_id) { return i; }; }; return -1; }; Ref<CameraFeed> CameraServer::get_feed_by_id(int p_id) { int index = get_feed_index(p_id); if (index == -1) { return NULL; } else { return feeds[index]; } }; void CameraServer::add_feed(const Ref<CameraFeed> &p_feed) { // add our feed feeds.push_back(p_feed); // record for debugging #ifdef DEBUG_ENABLED print_line("Registered camera " + p_feed->get_name() + " with id " + itos(p_feed->get_id()) + " position " + itos(p_feed->get_position()) + " at index " + itos(feeds.size() - 1)); #endif // let whomever is interested know emit_signal("camera_feed_added", p_feed->get_id()); }; void CameraServer::remove_feed(const Ref<CameraFeed> &p_feed) { for (int i = 0; i < feeds.size(); i++) { if (feeds[i] == p_feed) { int feed_id = p_feed->get_id(); // record for debugging #ifdef DEBUG_ENABLED print_line("Removed camera " + p_feed->get_name() + " with id " + itos(feed_id) + " position " + itos(p_feed->get_position())); #endif // remove it from our array, if this results in our feed being unreferenced it will be destroyed feeds.remove(i); // let whomever is interested know emit_signal("camera_feed_removed", feed_id); return; }; }; }; Ref<CameraFeed> CameraServer::get_feed(int p_index) { ERR_FAIL_INDEX_V(p_index, feeds.size(), NULL); return feeds[p_index]; }; int CameraServer::get_feed_count() { return feeds.size(); }; Array CameraServer::get_feeds() { Array return_feeds; int cc = get_feed_count(); return_feeds.resize(cc); for (int i = 0; i < feeds.size(); i++) { return_feeds[i] = get_feed(i); }; return return_feeds; }; RID CameraServer::feed_texture(int p_id, CameraServer::FeedImage p_texture) { int index = get_feed_index(p_id); ERR_FAIL_COND_V(index == -1, RID()); Ref<CameraFeed> feed = get_feed(index); return feed->get_texture(p_texture); }; CameraServer::CameraServer() { singleton = this; }; CameraServer::~CameraServer() { singleton = NULL; }; <commit_msg>Fix crash caused by null parameter passed to CameraServer.add_feed()<commit_after>/*************************************************************************/ /* camera_server.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "camera_server.h" #include "servers/camera/camera_feed.h" #include "visual_server.h" //////////////////////////////////////////////////////// // CameraServer CameraServer::CreateFunc CameraServer::create_func = NULL; void CameraServer::_bind_methods() { ClassDB::bind_method(D_METHOD("get_feed", "index"), &CameraServer::get_feed); ClassDB::bind_method(D_METHOD("get_feed_count"), &CameraServer::get_feed_count); ClassDB::bind_method(D_METHOD("feeds"), &CameraServer::get_feeds); ClassDB::bind_method(D_METHOD("add_feed", "feed"), &CameraServer::add_feed); ClassDB::bind_method(D_METHOD("remove_feed", "feed"), &CameraServer::remove_feed); ADD_SIGNAL(MethodInfo("camera_feed_added", PropertyInfo(Variant::INT, "id"))); ADD_SIGNAL(MethodInfo("camera_feed_removed", PropertyInfo(Variant::INT, "id"))); BIND_ENUM_CONSTANT(FEED_RGBA_IMAGE); BIND_ENUM_CONSTANT(FEED_YCBCR_IMAGE); BIND_ENUM_CONSTANT(FEED_Y_IMAGE); BIND_ENUM_CONSTANT(FEED_CBCR_IMAGE); }; CameraServer *CameraServer::singleton = NULL; CameraServer *CameraServer::get_singleton() { return singleton; }; int CameraServer::get_free_id() { bool id_exists = true; int newid = 0; // find a free id while (id_exists) { newid++; id_exists = false; for (int i = 0; i < feeds.size() && !id_exists; i++) { if (feeds[i]->get_id() == newid) { id_exists = true; }; }; }; return newid; }; int CameraServer::get_feed_index(int p_id) { for (int i = 0; i < feeds.size(); i++) { if (feeds[i]->get_id() == p_id) { return i; }; }; return -1; }; Ref<CameraFeed> CameraServer::get_feed_by_id(int p_id) { int index = get_feed_index(p_id); if (index == -1) { return NULL; } else { return feeds[index]; } }; void CameraServer::add_feed(const Ref<CameraFeed> &p_feed) { ERR_FAIL_COND(p_feed.is_null()); // add our feed feeds.push_back(p_feed); // record for debugging #ifdef DEBUG_ENABLED print_line("Registered camera " + p_feed->get_name() + " with id " + itos(p_feed->get_id()) + " position " + itos(p_feed->get_position()) + " at index " + itos(feeds.size() - 1)); #endif // let whomever is interested know emit_signal("camera_feed_added", p_feed->get_id()); }; void CameraServer::remove_feed(const Ref<CameraFeed> &p_feed) { for (int i = 0; i < feeds.size(); i++) { if (feeds[i] == p_feed) { int feed_id = p_feed->get_id(); // record for debugging #ifdef DEBUG_ENABLED print_line("Removed camera " + p_feed->get_name() + " with id " + itos(feed_id) + " position " + itos(p_feed->get_position())); #endif // remove it from our array, if this results in our feed being unreferenced it will be destroyed feeds.remove(i); // let whomever is interested know emit_signal("camera_feed_removed", feed_id); return; }; }; }; Ref<CameraFeed> CameraServer::get_feed(int p_index) { ERR_FAIL_INDEX_V(p_index, feeds.size(), NULL); return feeds[p_index]; }; int CameraServer::get_feed_count() { return feeds.size(); }; Array CameraServer::get_feeds() { Array return_feeds; int cc = get_feed_count(); return_feeds.resize(cc); for (int i = 0; i < feeds.size(); i++) { return_feeds[i] = get_feed(i); }; return return_feeds; }; RID CameraServer::feed_texture(int p_id, CameraServer::FeedImage p_texture) { int index = get_feed_index(p_id); ERR_FAIL_COND_V(index == -1, RID()); Ref<CameraFeed> feed = get_feed(index); return feed->get_texture(p_texture); }; CameraServer::CameraServer() { singleton = this; }; CameraServer::~CameraServer() { singleton = NULL; }; <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <unordered_set> #include <boost/format.hpp> #include <boost/program_options.hpp> #include "csvlint.h" using namespace std; using namespace boost; namespace po = boost::program_options; int main (int argc, char *argv[]) { char quote_char; char fs_char; unsigned guess_size; vector<string> fields; string input_path; string output_path; po::options_description desc_visible("General options"); desc_visible.add_options() ("help,h", "produce help message.") ("input,I", po::value(&input_path), "input path") ("output,O", po::value(&output_path), "output path") (",M", po::value(&guess_size)->default_value(100), "") ("fs", po::value(&fs_char)->default_value(','), "") ("quote", po::value(&quote_char)->default_value('"'),"") ("field,f", po::value(&fields), "") ; po::options_description desc("Allowed options"); desc.add(desc_visible); po::positional_options_description p; p.add("input", 1); p.add("output", 1); p.add("field", -1); po::variables_map vm; po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm); po::notify(vm); if (vm.count("help") || vm.count("input") == 0) { cout << "Usage: 101 [OTHER OPTIONS]... <data> [test]" << endl; cout << desc_visible << endl; return 0; } csvlint::Format fmt; fmt.train(input_path, guess_size * 1024 * 1024); csvlint::Format tofmt = fmt; if (vm.count("fs")) { tofmt.fs_char = fs_char; } if (vm.count("quote")) { tofmt.quote_char = quote_char; } { tofmt.fields.clear(); map<string, unsigned> lookup; for (unsigned i = 0; i < fmt.fields.size(); ++i) { lookup[fmt.fields[i].name] = i; } for (string const &s: fields) { auto it = lookup.find(s); if (it == lookup.end()) { cerr << "Field " << s << " not found." << endl; return 1; } tofmt.fields.push_back(fmt.fields[it->second]); } } ofstream os(output_path); tofmt.write_header(os); ifstream is(input_path); string line; is.seekg(fmt.data_offset); vector<csvlint::crange> cols; while (getline(is, line)) { fmt.parse(csvlint::crange(line), &cols); tofmt.write_line(os, cols); } return 0; } <commit_msg>updates<commit_after>#include <iostream> #include <fstream> #include <unordered_set> #include <boost/format.hpp> #include <boost/algorithm/string/split.hpp> #include <boost/algorithm/string/trim.hpp> #include <boost/algorithm/string/predicate.hpp> #include <boost/program_options.hpp> #include <boost/log/trivial.hpp> #include <boost/log/utility/setup/console.hpp> #include "csvlint.h" using namespace std; using namespace boost; namespace po = boost::program_options; int main (int argc, char *argv[]) { char quote_char; char fs_char; unsigned guess_size; vector<string> fields; string input_path; string output_path; po::options_description desc_visible("General options"); desc_visible.add_options() ("help,h", "produce help message.") ("input,I", po::value(&input_path), "input path") ("output,O", po::value(&output_path), "output path") (",M", po::value(&guess_size)->default_value(10), "") ("fs", po::value(&fs_char), "") ("quote", po::value(&quote_char),"") ("field,f", po::value(&fields), "") ; po::options_description desc("Allowed options"); desc.add(desc_visible); po::positional_options_description p; p.add("input", 1); p.add("output", 1); po::variables_map vm; po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm); po::notify(vm); if (vm.count("help") || vm.count("input") == 0) { cout << "Usage: 101 [OTHER OPTIONS]... <data> [test]" << endl; cout << desc_visible << endl; return 0; } boost::log::add_console_log(cerr); { vector<string> fs; for (auto const &f: fields) { using namespace boost::algorithm; vector<string> ss; split(ss, f, is_any_of(","), token_compress_on); for (string const &s: ss) { fs.push_back(s); } } fields.swap(fs); } csvlint::Format fmt; fmt.train(input_path, guess_size * 1024 * 1024); csvlint::Format tofmt = fmt; if (vm.count("fs")) { tofmt.fs_char = fs_char; } if (vm.count("quote")) { tofmt.quote_char = quote_char; } { tofmt.fields.clear(); map<string, unsigned> lookup; for (unsigned i = 0; i < fmt.fields.size(); ++i) { lookup[fmt.fields[i].name] = i; } for (string const &s: fields) { auto it = lookup.find(s); if (it == lookup.end()) { cerr << "Field " << s << " not found." << endl; return 1; } tofmt.fields.push_back(fmt.fields[it->second]); } } ofstream os_file; if (output_path.size()) { os_file.open(output_path.c_str()); } ostream &os = output_path.size() ? os_file : cout; tofmt.write_header(os); ifstream is(input_path); string line; is.seekg(fmt.data_offset); vector<csvlint::crange> cols; while (getline(is, line)) { fmt.parse(csvlint::crange(line), &cols); tofmt.write_line(os, cols); } return 0; } <|endoftext|>
<commit_before>#define BOOST_TEST_MODULE account_query_db #include <eosio/chain/permission_object.hpp> #include <boost/test/unit_test.hpp> #include <eosio/testing/tester.hpp> #include <eosio/chain/types.hpp> #include <eosio/chain/block_state.hpp> #include <eosio/chain_plugin/account_query_db.hpp> #ifdef NON_VALIDATING_TEST #define TESTER tester #else #define TESTER validating_tester #endif using namespace eosio; using namespace eosio::chain; using namespace eosio::testing; using namespace eosio::chain_apis; using params = account_query_db::get_accounts_by_authorizers_params; using results = account_query_db::get_accounts_by_authorizers_result; bool find_account_name(results rst, account_name name){ for (const auto& acc : rst.accounts){ if (acc.account_name == name){ return true; } } return false; } bool find_account_auth(results rst, account_name name, permission_name perm){ for (const auto& acc : rst.accounts){ if (acc.account_name == name && acc.permission_name == perm) return true; } return false; } BOOST_AUTO_TEST_SUITE(account_query_db_tests) BOOST_FIXTURE_TEST_CASE(newaccount_test, TESTER) { try { // instantiate an account_query_db auto aq_db = account_query_db(*control); //link aq_db to the `accepted_block` signal on the controller auto c2 = control->accepted_block.connect([&](const block_state_ptr& blk) { aq_db.commit_block( blk); }); produce_blocks(10); account_name tester_account = "tester"_n; const auto trace_ptr = create_account(tester_account); aq_db.cache_transaction_trace(trace_ptr); produce_block(); params pars; pars.keys.emplace_back(get_public_key(tester_account, "owner")); const auto results = aq_db.get_accounts_by_authorizers(pars); BOOST_TEST_REQUIRE(find_account_name(results, tester_account) == true); } FC_LOG_AND_RETHROW() } BOOST_FIXTURE_TEST_CASE(updateauth_test, TESTER) { try { // instantiate an account_query_db auto aq_db = account_query_db(*control); //link aq_db to the `accepted_block` signal on the controller auto c = control->accepted_block.connect([&](const block_state_ptr& blk) { aq_db.commit_block( blk); }); produce_blocks(10); const auto& tester_account = "tester"_n; const string role = "first"; produce_block(); create_account(tester_account); const auto trace_ptr = push_action(config::system_account_name, updateauth::get_name(), tester_account, fc::mutable_variant_object() ("account", tester_account) ("permission", "role"_n) ("parent", "active") ("auth", authority(get_public_key(tester_account, role), 5)) ); aq_db.cache_transaction_trace(trace_ptr); produce_block(); params pars; pars.keys.emplace_back(get_public_key(tester_account, role)); const auto results = aq_db.get_accounts_by_authorizers(pars); BOOST_TEST_REQUIRE(find_account_auth(results, tester_account, "role"_n) == true); } FC_LOG_AND_RETHROW() } BOOST_AUTO_TEST_CASE(fork_test) { try { tester node_a(setup_policy::none); tester node_b(setup_policy::none); // instantiate an account_query_db auto aq_db = account_query_db(*node_a.control); //link aq_db to the `accepted_block` signal on the controller auto c = node_a.control->accepted_block.connect([&](const block_state_ptr& blk) { aq_db.commit_block( blk); }); // create 10 blocks synced for (int i = 0; i < 10; i++) { node_b.push_block(node_a.produce_block()); } // produce a block on node A with a new account and permission const auto& tester_account = N(tester); const auto& tester_account2 = N(tester2); const string role = "first"; node_a.create_account(tester_account); node_a.create_account(tester_account2); const auto trace_ptr = node_a.push_action(config::system_account_name, updateauth::get_name(), tester_account, fc::mutable_variant_object() ("account", tester_account) ("permission", N(role)) ("parent", "active") ("auth", authority(node_a.get_public_key(tester_account, role), 5)), 1 ); aq_db.cache_transaction_trace(trace_ptr); const auto trace_ptr2 = node_a.push_action(config::system_account_name, updateauth::get_name(), tester_account2, fc::mutable_variant_object() ("account", tester_account2) ("permission", N(role)) ("parent", "active") ("auth", authority(node_a.get_public_key(tester_account2, role), 5)), 2 ); aq_db.cache_transaction_trace(trace_ptr2); node_a.produce_block(); params pars; pars.keys.emplace_back(node_a.get_public_key(tester_account, role)); const auto pre_results = aq_db.get_accounts_by_authorizers(pars); BOOST_TEST_REQUIRE(find_account_auth(pre_results, tester_account, N(role)) == true); // have node B take over from head-1 and also update permissions node_b.create_account(tester_account); node_b.create_account(tester_account2); const auto trace_ptr3 = node_b.push_action(config::system_account_name, updateauth::get_name(), tester_account, fc::mutable_variant_object() ("account", tester_account) ("permission", N(role)) ("parent", "active") ("auth", authority(node_b.get_public_key(tester_account, role), 6)), 1 ); aq_db.cache_transaction_trace(trace_ptr3); const auto trace_ptr4 = node_b.push_action(config::system_account_name, updateauth::get_name(), tester_account2, fc::mutable_variant_object() ("account", tester_account2) ("permission", N(role)) ("parent", "active") ("auth", authority(node_b.get_public_key(tester_account2, role), 6)), 2 ); aq_db.cache_transaction_trace(trace_ptr4); // push b's onto a node_a.push_block(node_b.produce_block()); const auto trace_ptr5 = node_b.push_action(config::system_account_name, updateauth::get_name(), tester_account, fc::mutable_variant_object() ("account", tester_account) ("permission", N(role)) ("parent", "active") ("auth", authority(node_b.get_public_key(tester_account, role), 5)), 3 ); aq_db.cache_transaction_trace(trace_ptr5); const auto trace_ptr6 = node_b.push_action(config::system_account_name, updateauth::get_name(), tester_account2, fc::mutable_variant_object() ("account", tester_account2) ("permission", N(role)) ("parent", "active") ("auth", authority(node_b.get_public_key(tester_account2, role), 5)), 4 ); aq_db.cache_transaction_trace(trace_ptr6); node_a.push_block(node_b.produce_block()); // ensure the account was forked away const auto post_results = aq_db.get_accounts_by_authorizers(pars); // verify correct account is in results BOOST_TEST_REQUIRE(post_results.accounts.size() == 1); } FC_LOG_AND_RETHROW() } BOOST_AUTO_TEST_SUITE_END() <commit_msg>change N(tester) to "tester"_n, change N(role) to "role"_n<commit_after>#define BOOST_TEST_MODULE account_query_db #include <eosio/chain/permission_object.hpp> #include <boost/test/unit_test.hpp> #include <eosio/testing/tester.hpp> #include <eosio/chain/types.hpp> #include <eosio/chain/block_state.hpp> #include <eosio/chain_plugin/account_query_db.hpp> #ifdef NON_VALIDATING_TEST #define TESTER tester #else #define TESTER validating_tester #endif using namespace eosio; using namespace eosio::chain; using namespace eosio::testing; using namespace eosio::chain_apis; using params = account_query_db::get_accounts_by_authorizers_params; using results = account_query_db::get_accounts_by_authorizers_result; bool find_account_name(results rst, account_name name){ for (const auto& acc : rst.accounts){ if (acc.account_name == name){ return true; } } return false; } bool find_account_auth(results rst, account_name name, permission_name perm){ for (const auto& acc : rst.accounts){ if (acc.account_name == name && acc.permission_name == perm) return true; } return false; } BOOST_AUTO_TEST_SUITE(account_query_db_tests) BOOST_FIXTURE_TEST_CASE(newaccount_test, TESTER) { try { // instantiate an account_query_db auto aq_db = account_query_db(*control); //link aq_db to the `accepted_block` signal on the controller auto c2 = control->accepted_block.connect([&](const block_state_ptr& blk) { aq_db.commit_block( blk); }); produce_blocks(10); account_name tester_account = "tester"_n; const auto trace_ptr = create_account(tester_account); aq_db.cache_transaction_trace(trace_ptr); produce_block(); params pars; pars.keys.emplace_back(get_public_key(tester_account, "owner")); const auto results = aq_db.get_accounts_by_authorizers(pars); BOOST_TEST_REQUIRE(find_account_name(results, tester_account) == true); } FC_LOG_AND_RETHROW() } BOOST_FIXTURE_TEST_CASE(updateauth_test, TESTER) { try { // instantiate an account_query_db auto aq_db = account_query_db(*control); //link aq_db to the `accepted_block` signal on the controller auto c = control->accepted_block.connect([&](const block_state_ptr& blk) { aq_db.commit_block( blk); }); produce_blocks(10); const auto& tester_account = "tester"_n; const string role = "first"; produce_block(); create_account(tester_account); const auto trace_ptr = push_action(config::system_account_name, updateauth::get_name(), tester_account, fc::mutable_variant_object() ("account", tester_account) ("permission", "role"_n) ("parent", "active") ("auth", authority(get_public_key(tester_account, role), 5)) ); aq_db.cache_transaction_trace(trace_ptr); produce_block(); params pars; pars.keys.emplace_back(get_public_key(tester_account, role)); const auto results = aq_db.get_accounts_by_authorizers(pars); BOOST_TEST_REQUIRE(find_account_auth(results, tester_account, "role"_n) == true); } FC_LOG_AND_RETHROW() } BOOST_AUTO_TEST_CASE(fork_test) { try { tester node_a(setup_policy::none); tester node_b(setup_policy::none); // instantiate an account_query_db auto aq_db = account_query_db(*node_a.control); //link aq_db to the `accepted_block` signal on the controller auto c = node_a.control->accepted_block.connect([&](const block_state_ptr& blk) { aq_db.commit_block( blk); }); // create 10 blocks synced for (int i = 0; i < 10; i++) { node_b.push_block(node_a.produce_block()); } // produce a block on node A with a new account and permission const auto& tester_account = "tester"_n; const auto& tester_account2 = "tester2"_n; const string role = "first"; node_a.create_account(tester_account); node_a.create_account(tester_account2); const auto trace_ptr = node_a.push_action(config::system_account_name, updateauth::get_name(), tester_account, fc::mutable_variant_object() ("account", tester_account) ("permission", "role"_n) ("parent", "active") ("auth", authority(node_a.get_public_key(tester_account, role), 5)), 1 ); aq_db.cache_transaction_trace(trace_ptr); const auto trace_ptr2 = node_a.push_action(config::system_account_name, updateauth::get_name(), tester_account2, fc::mutable_variant_object() ("account", tester_account2) ("permission", "role"_n) ("parent", "active") ("auth", authority(node_a.get_public_key(tester_account2, role), 5)), 2 ); aq_db.cache_transaction_trace(trace_ptr2); node_a.produce_block(); params pars; pars.keys.emplace_back(node_a.get_public_key(tester_account, role)); const auto pre_results = aq_db.get_accounts_by_authorizers(pars); BOOST_TEST_REQUIRE(find_account_auth(pre_results, tester_account, "role"_n) == true); // have node B take over from head-1 and also update permissions node_b.create_account(tester_account); node_b.create_account(tester_account2); const auto trace_ptr3 = node_b.push_action(config::system_account_name, updateauth::get_name(), tester_account, fc::mutable_variant_object() ("account", tester_account) ("permission", "role"_n) ("parent", "active") ("auth", authority(node_b.get_public_key(tester_account, role), 6)), 1 ); aq_db.cache_transaction_trace(trace_ptr3); const auto trace_ptr4 = node_b.push_action(config::system_account_name, updateauth::get_name(), tester_account2, fc::mutable_variant_object() ("account", tester_account2) ("permission", "role"_n) ("parent", "active") ("auth", authority(node_b.get_public_key(tester_account2, role), 6)), 2 ); aq_db.cache_transaction_trace(trace_ptr4); // push b's onto a node_a.push_block(node_b.produce_block()); const auto trace_ptr5 = node_b.push_action(config::system_account_name, updateauth::get_name(), tester_account, fc::mutable_variant_object() ("account", tester_account) ("permission", "role"_n) ("parent", "active") ("auth", authority(node_b.get_public_key(tester_account, role), 5)), 3 ); aq_db.cache_transaction_trace(trace_ptr5); const auto trace_ptr6 = node_b.push_action(config::system_account_name, updateauth::get_name(), tester_account2, fc::mutable_variant_object() ("account", tester_account2) ("permission", "role"_n) ("parent", "active") ("auth", authority(node_b.get_public_key(tester_account2, role), 5)), 4 ); aq_db.cache_transaction_trace(trace_ptr6); node_a.push_block(node_b.produce_block()); // ensure the account was forked away const auto post_results = aq_db.get_accounts_by_authorizers(pars); // verify correct account is in results BOOST_TEST_REQUIRE(post_results.accounts.size() == 1); } FC_LOG_AND_RETHROW() } BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>// Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved. #include "stdafx.h" #include "AutoPacketGraph.h" #include "CoreContext.h" #include "DecorationDisposition.h" #include "demangle.h" #include "SatCounter.h" #include <algorithm> #include <fstream> #include <string> #include <sstream> #include FUNCTIONAL_HEADER AutoPacketGraph::AutoPacketGraph() { } std::string AutoPacketGraph::DemangleTypeName(const std::type_info* type_info) const { std::string demangled = autowiring::demangle(type_info); size_t demangledLength = demangled.length(); size_t newLength = demangled[demangledLength - 2] == ' ' ? demangledLength - 10 : demangledLength - 9; return demangled.substr(demangled.find("<") + 1, newLength); } void AutoPacketGraph::LoadEdges() { std::lock_guard<std::mutex> lk(m_lock); std::list<AutoFilterDescriptor> descriptors; m_factory->AppendAutoFiltersTo(descriptors); for (auto& descriptor : descriptors) { for(auto pCur = descriptor.GetAutoFilterInput(); *pCur; pCur++) { const std::type_info& type_info = *pCur->ti; // Skip the AutoPacketGraph const std::type_info& descType = m_factory->GetContext()->GetAutoTypeId(descriptor.GetAutoFilter()); if (descType == typeid(AutoPacketGraph)) { continue; } if (pCur->is_input) { DeliveryEdge edge { &type_info, descriptor, true }; if (m_deliveryGraph.find(edge) == m_deliveryGraph.end()) { m_deliveryGraph[edge] = 0; } } if (pCur->is_output) { DeliveryEdge edge { &type_info, descriptor, false }; if (m_deliveryGraph.find(edge) == m_deliveryGraph.end()) { m_deliveryGraph[edge] = 0; } } } } } void AutoPacketGraph::RecordDelivery(const std::type_info* ti, const AutoFilterDescriptor& descriptor, bool input) { DeliveryEdge edge { ti, descriptor, input }; auto itr = m_deliveryGraph.find(edge); assert(itr != m_deliveryGraph.end()); itr->second++; } void AutoPacketGraph::NewObject(CoreContext&, const ObjectTraits&) { LoadEdges(); } bool AutoPacketGraph::OnStart(void) { LoadEdges(); return false; } void AutoPacketGraph::AutoFilter(AutoPacket& packet) { packet.AddTeardownListener([this, &packet] () { for (auto& cur : packet.GetDecorations()) { auto& decoration = cur.second; auto type = &decoration.GetKey().ti; for (auto& publisher : decoration.m_publishers) { if (!publisher->remaining) { RecordDelivery(type, *publisher, false); } } for (auto& subscriber : decoration.m_subscribers) { // Skip the AutoPacketGraph const std::type_info& descType = m_factory->GetContext()->GetAutoTypeId(subscriber->GetAutoFilter()); if (descType == typeid(AutoPacketGraph)) { continue; } if (subscriber->remaining) { RecordDelivery(type, *subscriber, true); } } } }); } bool AutoPacketGraph::WriteGV(const std::string& filename, bool numPackets) const { std::ofstream file(filename.c_str()); if (!file && !file.good()) { return false; } file << "digraph \"" << autowiring::demangle(CoreContext::CurrentContext()->GetSigilType()) << " context\" {" << std::endl; std::lock_guard<std::mutex> lk(m_lock); // Containers for the unique types and descriptors std::unordered_set<std::string> typeNames; std::unordered_set<std::string> descriptorNames; for (auto& itr : m_deliveryGraph) { auto& edge = itr.first; auto type = edge.type_info; auto& descriptor = edge.descriptor; auto count = itr.second; // Skip the AutoPacketGraph const std::type_info& descType = m_factory->GetContext()->GetAutoTypeId(descriptor.GetAutoFilter()); if (descType == typeid(AutoPacketGraph)) { continue; } std::string typeName = DemangleTypeName(type); std::string descriptorName = autowiring::demangle(descType); // Get a unique set of types/descriptors if (typeNames.find(typeName) == typeNames.end()) typeNames.insert(typeName); if (descriptorNames.find(descriptorName) == descriptorNames.end()) descriptorNames.insert(descriptorName); // string format: "type" -> "AutoFilter" (or vice versa) std::stringstream ss; ss << " \""; if (edge.input) { ss << typeName << "\" -> \"" << descriptorName << "\""; } else { ss << descriptorName << "\" -> \"" << typeName << "\""; } if (numPackets) ss << "[label=\"" << count << "\"];"; ss << std::endl; file << ss.str(); } file << std::endl; // Setup the shapes for the types and descriptors for (auto& typeName : typeNames) file << " \"" << typeName << "\" [shape=box];" << std::endl; for (auto& descriptorName : descriptorNames) file << " \"" << descriptorName << "\" [shape=ellipse];" << std::endl; file << "}\n"; return true; } <commit_msg>Fixing issue where the AutoPacketGraph CoreRunnable is just dying when OnStart is called<commit_after>// Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved. #include "stdafx.h" #include "AutoPacketGraph.h" #include "CoreContext.h" #include "DecorationDisposition.h" #include "demangle.h" #include "SatCounter.h" #include <algorithm> #include <fstream> #include <string> #include <sstream> #include FUNCTIONAL_HEADER AutoPacketGraph::AutoPacketGraph() { } std::string AutoPacketGraph::DemangleTypeName(const std::type_info* type_info) const { std::string demangled = autowiring::demangle(type_info); size_t demangledLength = demangled.length(); size_t newLength = demangled[demangledLength - 2] == ' ' ? demangledLength - 10 : demangledLength - 9; return demangled.substr(demangled.find("<") + 1, newLength); } void AutoPacketGraph::LoadEdges() { std::lock_guard<std::mutex> lk(m_lock); std::list<AutoFilterDescriptor> descriptors; m_factory->AppendAutoFiltersTo(descriptors); for (auto& descriptor : descriptors) { for(auto pCur = descriptor.GetAutoFilterInput(); *pCur; pCur++) { const std::type_info& type_info = *pCur->ti; // Skip the AutoPacketGraph const std::type_info& descType = m_factory->GetContext()->GetAutoTypeId(descriptor.GetAutoFilter()); if (descType == typeid(AutoPacketGraph)) { continue; } if (pCur->is_input) { DeliveryEdge edge { &type_info, descriptor, true }; if (m_deliveryGraph.find(edge) == m_deliveryGraph.end()) { m_deliveryGraph[edge] = 0; } } if (pCur->is_output) { DeliveryEdge edge { &type_info, descriptor, false }; if (m_deliveryGraph.find(edge) == m_deliveryGraph.end()) { m_deliveryGraph[edge] = 0; } } } } } void AutoPacketGraph::RecordDelivery(const std::type_info* ti, const AutoFilterDescriptor& descriptor, bool input) { DeliveryEdge edge { ti, descriptor, input }; auto itr = m_deliveryGraph.find(edge); assert(itr != m_deliveryGraph.end()); itr->second++; } void AutoPacketGraph::NewObject(CoreContext&, const ObjectTraits&) { LoadEdges(); } bool AutoPacketGraph::OnStart(void) { LoadEdges(); return true; } void AutoPacketGraph::AutoFilter(AutoPacket& packet) { packet.AddTeardownListener([this, &packet] () { for (auto& cur : packet.GetDecorations()) { auto& decoration = cur.second; auto type = &decoration.GetKey().ti; for (auto& publisher : decoration.m_publishers) { if (!publisher->remaining) { RecordDelivery(type, *publisher, false); } } for (auto& subscriber : decoration.m_subscribers) { // Skip the AutoPacketGraph const std::type_info& descType = m_factory->GetContext()->GetAutoTypeId(subscriber->GetAutoFilter()); if (descType == typeid(AutoPacketGraph)) { continue; } if (subscriber->remaining) { RecordDelivery(type, *subscriber, true); } } } }); } bool AutoPacketGraph::WriteGV(const std::string& filename, bool numPackets) const { std::ofstream file(filename.c_str()); if (!file && !file.good()) { return false; } file << "digraph \"" << autowiring::demangle(CoreContext::CurrentContext()->GetSigilType()) << " context\" {" << std::endl; std::lock_guard<std::mutex> lk(m_lock); // Containers for the unique types and descriptors std::unordered_set<std::string> typeNames; std::unordered_set<std::string> descriptorNames; for (auto& itr : m_deliveryGraph) { auto& edge = itr.first; auto type = edge.type_info; auto& descriptor = edge.descriptor; auto count = itr.second; // Skip the AutoPacketGraph const std::type_info& descType = m_factory->GetContext()->GetAutoTypeId(descriptor.GetAutoFilter()); if (descType == typeid(AutoPacketGraph)) { continue; } std::string typeName = DemangleTypeName(type); std::string descriptorName = autowiring::demangle(descType); // Get a unique set of types/descriptors if (typeNames.find(typeName) == typeNames.end()) typeNames.insert(typeName); if (descriptorNames.find(descriptorName) == descriptorNames.end()) descriptorNames.insert(descriptorName); // string format: "type" -> "AutoFilter" (or vice versa) std::stringstream ss; ss << " \""; if (edge.input) { ss << typeName << "\" -> \"" << descriptorName << "\""; } else { ss << descriptorName << "\" -> \"" << typeName << "\""; } if (numPackets) ss << "[label=\"" << count << "\"];"; ss << std::endl; file << ss.str(); } file << std::endl; // Setup the shapes for the types and descriptors for (auto& typeName : typeNames) file << " \"" << typeName << "\" [shape=box];" << std::endl; for (auto& descriptorName : descriptorNames) file << " \"" << descriptorName << "\" [shape=ellipse];" << std::endl; file << "}\n"; return true; } <|endoftext|>
<commit_before>// Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved. #include "stdafx.h" #include "AutowiringDebug.h" #include "Autowired.h" #include <iomanip> #include <iostream> #include <sstream> using namespace autowiring; using namespace autowiring::dbg; #ifdef _MSC_VER // On Windows, lambda functions start with the key string "class <" bool autowiring::dbg::IsLambda(const std::type_info& ti) { return demangle(ti).compare(0, 7, "class <") == 0; } #else // On other platforms, try to find lambda functions by the presence of forbidden characters bool autowiring::dbg::IsLambda(const std::type_info& ti) { auto name = demangle(ti); for (auto cur : name) if ( !('a' <= cur && cur <= 'z') && !('A' <= cur && cur <= 'Z') && !('0' <= cur && cur <= '9') && cur != '_' && cur != ':' && cur != '<' && cur != '>' && cur != ',' && cur != ' ' ) return true; return false; } #endif static std::string TrimPrefix(std::string name) { #ifdef _MSC_VER // "class" or "struct" prefixes should be eliminated if (name.compare(0, 6, "class ")) name = name.substr(5); if (name.compare(0, 7, "struct ")) name = name.substr(6); #endif return name; } static std::string DemangleWithAutoID(const std::type_info& ti) { auto retVal = demangle(ti); // prefix is at the beginning of the string, skip over it static const char prefix [] = "struct auto_id<"; if (retVal.compare(0, sizeof(prefix) - 1, prefix) == 0) { size_t off = sizeof(prefix) - 1; retVal = retVal.substr(off, retVal.length() - off - 2); } return TrimPrefix(retVal); } std::string autowiring::dbg::ContextName(void) { AutoCurrentContext ctxt; return autowiring::demangle(ctxt->GetSigilType()); } AutoPacket* autowiring::dbg::CurrentPacket(void) { Autowired<AutoPacketFactory> factory; if (!factory) return nullptr; return factory->CurrentPacket().get(); } static const AutoFilterDescriptor* DescriptorByName(const char* name, const std::vector<AutoFilterDescriptor>& filters) { for (const auto& filter : filters) { auto type = filter.GetType(); if (!type) continue; auto curName = TrimPrefix(demangle(type)); if (!curName.compare(name)) return &filter; } return nullptr; } const AutoFilterDescriptor* autowiring::dbg::DescriptorByName(const char* name) { Autowired<AutoPacketFactory> factory; if (!factory) return nullptr; return DescriptorByName(name, factory->GetAutoFilters()); } std::string autowiring::dbg::AutoFilterInfo(const char* name) { Autowired<AutoPacketFactory> factory; if (!factory) return "No factory detected in this context"; // Obtain all descriptors: const std::vector<AutoFilterDescriptor> descs = factory->GetAutoFilters(); // Need the root descriptor first const AutoFilterDescriptor* desc = DescriptorByName(name, descs); if (!desc) return "Filter not found"; std::ostringstream os; std::function<void(const AutoFilterDescriptor&, int)> fnCall = [&](const AutoFilterDescriptor& desc, size_t nLevels) { auto args = desc.GetAutoFilterArguments(); for (size_t i = 0; i < desc.GetArity(); i++) { // Argument must be an input to the filter we want to know more about if (!args[i].is_input) continue; // Who provides this input? for (const auto& providerDesc : descs) { auto providerArg = providerDesc.GetArgumentType(args[i].ti); if (providerArg && providerArg->is_output) { // Need to print information about this provider: os << demangle(*args[i].ti) << ' ' << std::string(' ', nLevels) << demangle(*providerDesc.GetType()) << std::endl; // The current descriptor provides an input to the parent, recurse fnCall(providerDesc, nLevels + 1); } } } }; // Root typename print first: os << demangle(desc->GetType()) << std::endl; fnCall(*desc, 1); auto retVal = os.str(); return retVal; } std::vector<std::string> autowiring::dbg::ListRootDecorations(void) { Autowired<AutoPacketFactory> factory; if (!factory) return std::vector<std::string>{}; // Obtain all descriptors: const std::vector<AutoFilterDescriptor> descs = factory->GetAutoFilters(); // Get all baseline descriptor types, figure out what isn't satisfied: std::unordered_map<std::type_index, const std::type_info*> outputs; std::unordered_map<std::type_index, const std::type_info*> inputs; for (const auto& desc : descs) { auto args = desc.GetAutoFilterArguments(); for (size_t i = 0; i < desc.GetArity(); i++) (args[i].is_output ? outputs : inputs)[*args[i].ti] = args[i].ti; } // Remove all inputs that exist in the outputs set: for (auto& output : outputs) inputs.erase(*output.second); // Any remaining inputs are unsatisfied std::vector<std::string> retVal; for (auto& input : inputs) if (input.second) retVal.push_back(DemangleWithAutoID(*input.second)); return retVal; } void autowiring::dbg::DebugInit(void) { }<commit_msg>Make DemangleWithAutoID work correctly with mac and linux<commit_after>// Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved. #include "stdafx.h" #include "AutowiringDebug.h" #include "Autowired.h" #include <iomanip> #include <iostream> #include <sstream> using namespace autowiring; using namespace autowiring::dbg; #ifdef _MSC_VER // On Windows, lambda functions start with the key string "class <" bool autowiring::dbg::IsLambda(const std::type_info& ti) { return demangle(ti).compare(0, 7, "class <") == 0; } #else // On other platforms, try to find lambda functions by the presence of forbidden characters bool autowiring::dbg::IsLambda(const std::type_info& ti) { auto name = demangle(ti); for (auto cur : name) if ( !('a' <= cur && cur <= 'z') && !('A' <= cur && cur <= 'Z') && !('0' <= cur && cur <= '9') && cur != '_' && cur != ':' && cur != '<' && cur != '>' && cur != ',' && cur != ' ' ) return true; return false; } #endif static std::string TrimPrefix(std::string name) { #ifdef _MSC_VER // "class" or "struct" prefixes should be eliminated if (name.compare(0, 6, "class ")) name = name.substr(5); if (name.compare(0, 7, "struct ")) name = name.substr(6); #endif return name; } static std::string DemangleWithAutoID(const std::type_info& ti) { auto retVal = demangle(ti); // prefix is at the beginning of the string, skip over it #ifdef _MSC_VER static const char prefix [] = "struct auto_id<"; #else static const char prefix [] = "auto_id<"; #endif if (retVal.compare(0, sizeof(prefix) - 1, prefix) == 0) { size_t off = sizeof(prefix) - 1; retVal = retVal.substr(off, retVal.length() - off - 2); } return TrimPrefix(retVal); } std::string autowiring::dbg::ContextName(void) { AutoCurrentContext ctxt; return autowiring::demangle(ctxt->GetSigilType()); } AutoPacket* autowiring::dbg::CurrentPacket(void) { Autowired<AutoPacketFactory> factory; if (!factory) return nullptr; return factory->CurrentPacket().get(); } static const AutoFilterDescriptor* DescriptorByName(const char* name, const std::vector<AutoFilterDescriptor>& filters) { for (const auto& filter : filters) { auto type = filter.GetType(); if (!type) continue; auto curName = TrimPrefix(demangle(type)); if (!curName.compare(name)) return &filter; } return nullptr; } const AutoFilterDescriptor* autowiring::dbg::DescriptorByName(const char* name) { Autowired<AutoPacketFactory> factory; if (!factory) return nullptr; return DescriptorByName(name, factory->GetAutoFilters()); } std::string autowiring::dbg::AutoFilterInfo(const char* name) { Autowired<AutoPacketFactory> factory; if (!factory) return "No factory detected in this context"; // Obtain all descriptors: const std::vector<AutoFilterDescriptor> descs = factory->GetAutoFilters(); // Need the root descriptor first const AutoFilterDescriptor* desc = DescriptorByName(name, descs); if (!desc) return "Filter not found"; std::ostringstream os; std::function<void(const AutoFilterDescriptor&, int)> fnCall = [&](const AutoFilterDescriptor& desc, size_t nLevels) { auto args = desc.GetAutoFilterArguments(); for (size_t i = 0; i < desc.GetArity(); i++) { // Argument must be an input to the filter we want to know more about if (!args[i].is_input) continue; // Who provides this input? for (const auto& providerDesc : descs) { auto providerArg = providerDesc.GetArgumentType(args[i].ti); if (providerArg && providerArg->is_output) { // Need to print information about this provider: os << demangle(*args[i].ti) << ' ' << std::string(' ', nLevels) << demangle(*providerDesc.GetType()) << std::endl; // The current descriptor provides an input to the parent, recurse fnCall(providerDesc, nLevels + 1); } } } }; // Root typename print first: os << demangle(desc->GetType()) << std::endl; fnCall(*desc, 1); auto retVal = os.str(); return retVal; } std::vector<std::string> autowiring::dbg::ListRootDecorations(void) { Autowired<AutoPacketFactory> factory; if (!factory) return std::vector<std::string>{}; // Obtain all descriptors: const std::vector<AutoFilterDescriptor> descs = factory->GetAutoFilters(); // Get all baseline descriptor types, figure out what isn't satisfied: std::unordered_map<std::type_index, const std::type_info*> outputs; std::unordered_map<std::type_index, const std::type_info*> inputs; for (const auto& desc : descs) { auto args = desc.GetAutoFilterArguments(); for (size_t i = 0; i < desc.GetArity(); i++) (args[i].is_output ? outputs : inputs)[*args[i].ti] = args[i].ti; } // Remove all inputs that exist in the outputs set: for (auto& output : outputs) inputs.erase(*output.second); // Any remaining inputs are unsatisfied std::vector<std::string> retVal; for (auto& input : inputs) if (input.second) retVal.push_back(DemangleWithAutoID(*input.second)); return retVal; } void autowiring::dbg::DebugInit(void) { }<|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: sfxdefs.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: obo $ $Date: 2008-01-07 09:02:48 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SFXDEFS_HXX #define _SFXDEFS_HXX #define MESSAGEFILE_SDM_EXT "sdm" // Extension des neuen Formats #define MESSAGEFILE_EXT "smd" // Extension der Single-Mail/News-Files #define MESSAGETEMPFILE_EXT "sd~" // Extension f"ur Mail/News-TempFiles #define SfxFilterFlags ULONG #define PRODUCT_VERSION "5.0" #endif <commit_msg>INTEGRATION: CWS changefileheader (1.3.80); FILE MERGED 2008/03/31 13:37:57 rt 1.3.80.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: sfxdefs.hxx,v $ * $Revision: 1.4 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org 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 version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _SFXDEFS_HXX #define _SFXDEFS_HXX #define MESSAGEFILE_SDM_EXT "sdm" // Extension des neuen Formats #define MESSAGEFILE_EXT "smd" // Extension der Single-Mail/News-Files #define MESSAGETEMPFILE_EXT "sd~" // Extension f"ur Mail/News-TempFiles #define SfxFilterFlags ULONG #define PRODUCT_VERSION "5.0" #endif <|endoftext|>
<commit_before>#ifndef __Data_course__ #define __Data_course__ #include "data-general.hpp" #include "data-major.hpp" #include "data-department.hpp" using namespace std; class Course { protected: string ID; int number; string title; string description; char section; vector<Major> majors; Department* department; string concentrations; string conversations; string professor; int half_semester; bool pass_fail; float credits; string location; bool lab; GenEd* geneds; bool days[7]; float time[7]; public: Course(istream &is) { if (!is) return; string tmpLine; getline(is, tmpLine); vector<string> record = split(tmpLine, ','); for (vector<string>::iterator i=record.begin(); i != record.end(); ++i) *i=removeAllQuotes(*i); // Ignore the first column; record.at(0); // Second column has the course ID, //number = stringToInt(record.at(1)); ID = record.at(1); number = parseID(ID); // Third column has the section, section = record.at(2)[0]; // Fourth holds the lab boolean, if (record.at(3).empty()) lab = false; else lab = true; // while Fifth contains the title of the course; title = record.at(4); // Sixth hands over the length (half semester or not) // it's actually an int that tells us how many times the course is offered per semester. half_semester = stringToInt(record.at(5)); // Seventh tells us the number of credits, credits = stringToFloat(record.at(6)); // Eighth shows us if it can be taken pass/no-pass, if (record.at(7) == "Y") pass_fail = true; else pass_fail = false; // while Nine gives us the GEs of the course, // GEreqs = record.at(9); // and Ten spits out the days and times; // Times = record.at(10); // Eleven holds the location, location = record.at(11); // and Twelve knows who teaches. professor = record.at(12); } int parseID(string s) { // return stringToInt(s.substr(s.find(' ')+1,3)); // Xandra, what is this? string tempDept; unsigned int found = tempDept.find('/'); tempDept = s.substr(0,s.find(' ')-1); if (found != s.npos) { department = new Department[2]; string tmp = tempDept.substr(0,2); if ( tmp == "AS" ) department[0] = ASIAN; else if ( tmp == "BI" ) department[0] = BIO; else if ( tmp == "CH" ) department[0] = CHEM; else if ( tmp == "ES" ) department[0] = ENVST; else if ( tmp == "HI" ) department[0] = HIST; else if ( tmp == "RE" ) department[0] = REL; tmp = tempDept.substr(3,2); if ( tmp == "AS" ) department[1] = ASIAN; else if ( tmp == "BI" ) department[1] = BIO; else if ( tmp == "CH" ) department[1] = CHEM; else if ( tmp == "ES" ) department[1] = ENVST; else if ( tmp == "HI" ) department[1] = HIST; else if ( tmp == "RE" ) department[1] = REL; } else { if ( tempDept == "AFAM" ) department = AFAM; else if ( tempDept == "ALSO" ) department = ALSO; else if ( tempDept == "AMCON" ) department = AMCON; else if ( tempDept == "AMST" ) department = AMST; else if ( tempDept == "ARMS" ) department = ARMS; else if ( tempDept == "ART" ) department = ART; else if ( tempDept == "ASIAN" ) department = ASIAN; else if ( tempDept == "BIO" ) department = BIO; else if ( tempDept == "BMOLS" ) department = BMOLS; else if ( tempDept == "CHEM" ) department = CHEM; else if ( tempDept == "CHIN" ) department = CHIN; else if ( tempDept == "CLASS" ) department = CLASS; else if ( tempDept == "CSCI" ) department = CSCI; else if ( tempDept == "DANCE" ) department = DANCE; else if ( tempDept == "ECON" ) department = ECON; else if ( tempDept == "EDUC" ) department = EDUC; else if ( tempDept == "ENGL" ) department = ENGL; else if ( tempDept == "ENVST" ) department = ENVST; else if ( tempDept == "ESAC" ) department = ESAC; else if ( tempDept == "ESTH" ) department = ESTH; else if ( tempDept == "FAMST" ) department = FAMST; else if ( tempDept == "FILM" ) department = FILM; else if ( tempDept == "FREN" ) department = FREN; else if ( tempDept == "GCON" ) department = GCON; else if ( tempDept == "GERM" ) department = GERM; else if ( tempDept == "GREEK" ) department = GREEK; else if ( tempDept == "HIST" ) department = HIST; else if ( tempDept == "HSPST" ) department = HSPST; else if ( tempDept == "ID" ) department = ID; else if ( tempDept == "IDFA" ) department = IDFA; else if ( tempDept == "INTD" ) department = INTD; else if ( tempDept == "IS" ) department = IS; else if ( tempDept == "JAPAN" ) department = JAPAN; else if ( tempDept == "LATIN" ) department = LATIN; else if ( tempDept == "MATH" ) department = MATH; else if ( tempDept == "MEDIA" ) department = MEDIA; else if ( tempDept == "MEDVL" ) department = MEDVL; else if ( tempDept == "MGMT" ) department = MGMT; else if ( tempDept == "MUSIC" ) department = MUSIC; else if ( tempDept == "MUSPF" ) department = MUSPF; else if ( tempDept == "NEURO" ) department = NEURO; else if ( tempDept == "NORW" ) department = NORW; else if ( tempDept == "NURS" ) department = NURS; else if ( tempDept == "PHIL" ) department = PHIL; else if ( tempDept == "PHYS" ) department = PHYS; else if ( tempDept == "PSCI" ) department = PSCI; else if ( tempDept == "PSYCH" ) department = PSYCH; else if ( tempDept == "REL" ) department = REL; else if ( tempDept == "RUSSN" ) department = RUSSN; else if ( tempDept == "SCICN" ) department = SCICN; else if ( tempDept == "SOAN" ) department = SOAN; else if ( tempDept == "SPAN" ) department = SPAN; else if ( tempDept == "STAT" ) department = STAT; else if ( tempDept == "SWRK" ) department = SWRK; else if ( tempDept == "THEAT" ) department = THEAT; else if ( tempDept == "WMGST" ) department = WMGST; else if ( tempDept == "WRIT" ) department = WRIT; } } void updateID() { string dept; for (std::vector<Department>::iterator i = department.begin(); i != department.end(); ++i) dept += i->getName(); ID = dept + tostring(number) + section; } string getID() { return ID; } ostream& getData(ostream &os) { os << ID << section << " "; os << title << "/"; /*for (vector<Instructor>::iterator i = professor.begin(); i != professor.end(); ++i) { os << i->name << " "; }*/ return os; } void display(); }; ostream &operator<<(ostream &os, Course &item) { return item.getData(os); } void Course::display() { if(this==0) cout << *this << endl; } #endif <commit_msg>Add a comment in getCourse<commit_after>#ifndef __Data_course__ #define __Data_course__ #include "data-general.hpp" #include "data-major.hpp" #include "data-department.hpp" using namespace std; class Course { protected: string ID; int number; string title; string description; char section; vector<Major> majors; Department* department; string concentrations; string conversations; string professor; int half_semester; bool pass_fail; float credits; string location; bool lab; GenEd* geneds; bool days[7]; float time[7]; public: Course(istream &is) { if (!is) return; string tmpLine; getline(is, tmpLine); // remove the extra data of course status vector<string> record = split(tmpLine, ','); for (vector<string>::iterator i=record.begin(); i != record.end(); ++i) *i=removeAllQuotes(*i); // Ignore the first column; record.at(0); // Second column has the course ID, //number = stringToInt(record.at(1)); ID = record.at(1); number = parseID(ID); // Third column has the section, section = record.at(2)[0]; // Fourth holds the lab boolean, if (record.at(3).empty()) lab = false; else lab = true; // while Fifth contains the title of the course; title = record.at(4); // Sixth hands over the length (half semester or not) // it's actually an int that tells us how many times the course is offered per semester. half_semester = stringToInt(record.at(5)); // Seventh tells us the number of credits, credits = stringToFloat(record.at(6)); // Eighth shows us if it can be taken pass/no-pass, if (record.at(7) == "Y") pass_fail = true; else pass_fail = false; // while Nine gives us the GEs of the course, // GEreqs = record.at(9); // and Ten spits out the days and times; // Times = record.at(10); // Eleven holds the location, location = record.at(11); // and Twelve knows who teaches. professor = record.at(12); } int parseID(string s) { // return stringToInt(s.substr(s.find(' ')+1,3)); // Xandra, what is this? string tempDept; unsigned int found = tempDept.find('/'); tempDept = s.substr(0,s.find(' ')-1); if (found != s.npos) { department = new Department[2]; string tmp = tempDept.substr(0,2); if ( tmp == "AS" ) department[0] = ASIAN; else if ( tmp == "BI" ) department[0] = BIO; else if ( tmp == "CH" ) department[0] = CHEM; else if ( tmp == "ES" ) department[0] = ENVST; else if ( tmp == "HI" ) department[0] = HIST; else if ( tmp == "RE" ) department[0] = REL; tmp = tempDept.substr(3,2); if ( tmp == "AS" ) department[1] = ASIAN; else if ( tmp == "BI" ) department[1] = BIO; else if ( tmp == "CH" ) department[1] = CHEM; else if ( tmp == "ES" ) department[1] = ENVST; else if ( tmp == "HI" ) department[1] = HIST; else if ( tmp == "RE" ) department[1] = REL; } else { if ( tempDept == "AFAM" ) department = AFAM; else if ( tempDept == "ALSO" ) department = ALSO; else if ( tempDept == "AMCON" ) department = AMCON; else if ( tempDept == "AMST" ) department = AMST; else if ( tempDept == "ARMS" ) department = ARMS; else if ( tempDept == "ART" ) department = ART; else if ( tempDept == "ASIAN" ) department = ASIAN; else if ( tempDept == "BIO" ) department = BIO; else if ( tempDept == "BMOLS" ) department = BMOLS; else if ( tempDept == "CHEM" ) department = CHEM; else if ( tempDept == "CHIN" ) department = CHIN; else if ( tempDept == "CLASS" ) department = CLASS; else if ( tempDept == "CSCI" ) department = CSCI; else if ( tempDept == "DANCE" ) department = DANCE; else if ( tempDept == "ECON" ) department = ECON; else if ( tempDept == "EDUC" ) department = EDUC; else if ( tempDept == "ENGL" ) department = ENGL; else if ( tempDept == "ENVST" ) department = ENVST; else if ( tempDept == "ESAC" ) department = ESAC; else if ( tempDept == "ESTH" ) department = ESTH; else if ( tempDept == "FAMST" ) department = FAMST; else if ( tempDept == "FILM" ) department = FILM; else if ( tempDept == "FREN" ) department = FREN; else if ( tempDept == "GCON" ) department = GCON; else if ( tempDept == "GERM" ) department = GERM; else if ( tempDept == "GREEK" ) department = GREEK; else if ( tempDept == "HIST" ) department = HIST; else if ( tempDept == "HSPST" ) department = HSPST; else if ( tempDept == "ID" ) department = ID; else if ( tempDept == "IDFA" ) department = IDFA; else if ( tempDept == "INTD" ) department = INTD; else if ( tempDept == "IS" ) department = IS; else if ( tempDept == "JAPAN" ) department = JAPAN; else if ( tempDept == "LATIN" ) department = LATIN; else if ( tempDept == "MATH" ) department = MATH; else if ( tempDept == "MEDIA" ) department = MEDIA; else if ( tempDept == "MEDVL" ) department = MEDVL; else if ( tempDept == "MGMT" ) department = MGMT; else if ( tempDept == "MUSIC" ) department = MUSIC; else if ( tempDept == "MUSPF" ) department = MUSPF; else if ( tempDept == "NEURO" ) department = NEURO; else if ( tempDept == "NORW" ) department = NORW; else if ( tempDept == "NURS" ) department = NURS; else if ( tempDept == "PHIL" ) department = PHIL; else if ( tempDept == "PHYS" ) department = PHYS; else if ( tempDept == "PSCI" ) department = PSCI; else if ( tempDept == "PSYCH" ) department = PSYCH; else if ( tempDept == "REL" ) department = REL; else if ( tempDept == "RUSSN" ) department = RUSSN; else if ( tempDept == "SCICN" ) department = SCICN; else if ( tempDept == "SOAN" ) department = SOAN; else if ( tempDept == "SPAN" ) department = SPAN; else if ( tempDept == "STAT" ) department = STAT; else if ( tempDept == "SWRK" ) department = SWRK; else if ( tempDept == "THEAT" ) department = THEAT; else if ( tempDept == "WMGST" ) department = WMGST; else if ( tempDept == "WRIT" ) department = WRIT; } } void updateID() { string dept; for (std::vector<Department>::iterator i = department.begin(); i != department.end(); ++i) dept += i->getName(); ID = dept + tostring(number) + section; } string getID() { return ID; } ostream& getData(ostream &os) { os << ID << section << " "; os << title << "/"; /*for (vector<Instructor>::iterator i = professor.begin(); i != professor.end(); ++i) { os << i->name << " "; }*/ return os; } void display(); }; ostream &operator<<(ostream &os, Course &item) { return item.getData(os); } void Course::display() { if(this==0) cout << *this << endl; } #endif <|endoftext|>
<commit_before>#include "configure.hpp" #include <silicium/file_operations.hpp> #include <silicium/cmake.hpp> #include <fstream> namespace { Si::absolute_path build_configure( Si::absolute_path const &application_source, Si::absolute_path const &temporary, Si::optional<Si::absolute_path> const &boost_root, Si::Sink<char, Si::success>::interface &output) { Si::absolute_path const repository = Si::parent( Si::parent(*Si::absolute_path::create(__FILE__)).or_throw( []{ throw std::runtime_error("Could not find parent directory of this file: " __FILE__); } ) ).or_throw( []{ throw std::runtime_error("Could not find the repository directory"); } ); Si::absolute_path const original_main_cpp = repository / Si::relative_path("configure_cmdline/main.cpp"); Si::absolute_path const source = temporary / Si::relative_path("source"); Si::recreate_directories(source, Si::throw_); Si::absolute_path const copied_main_cpp = source / Si::relative_path("main.cpp"); Si::copy(original_main_cpp, copied_main_cpp, Si::throw_); { Si::absolute_path const cmakeLists = source / Si::relative_path("CMakeLists.txt"); std::ofstream cmakeListsFile(cmakeLists.c_str()); cmakeListsFile << "cmake_minimum_required(VERSION 2.8)\n"; cmakeListsFile << "project(configure_cmdline_generated)\n"; cmakeListsFile << "if(UNIX)\n"; cmakeListsFile << " execute_process(COMMAND ${CMAKE_CXX_COMPILER} -dumpversion OUTPUT_VARIABLE GCC_VERSION)\n"; cmakeListsFile << " if(GCC_VERSION VERSION_GREATER 4.7)\n"; cmakeListsFile << " add_definitions(-std=c++1y)\n"; cmakeListsFile << " else()\n"; cmakeListsFile << " add_definitions(-std=c++0x)\n"; cmakeListsFile << " endif()\n"; cmakeListsFile << "endif()\n"; cmakeListsFile << "if(MSVC)\n"; cmakeListsFile << " set(Boost_USE_STATIC_LIBS ON)\n"; cmakeListsFile << " set(CMAKE_EXE_LINKER_FLAGS \"${CMAKE_EXE_LINKER_FLAGS} /SAFESEH:NO\")\n"; cmakeListsFile << "endif()\n"; cmakeListsFile << "find_package(Boost REQUIRED filesystem coroutine program_options thread context system)\n"; cmakeListsFile << "include_directories(SYSTEM ${SILICIUM_INCLUDE_DIR} ${Boost_INCLUDE_DIR} ${CDM_CONFIGURE_INCLUDE_DIRS})\n"; cmakeListsFile << "link_directories(${Boost_LIBRARY_DIR})\n"; cmakeListsFile << "add_executable(configure main.cpp)\n"; cmakeListsFile << "target_link_libraries(configure ${Boost_LIBRARIES})\n"; if (!cmakeListsFile) { throw std::runtime_error(("Could not generate " + Si::to_utf8_string(cmakeLists)).c_str()); } } Si::absolute_path const build = temporary / Si::relative_path("build"); Si::recreate_directories(build, Si::throw_); { std::vector<Si::os_string> arguments; { Si::absolute_path const silicium = repository / Si::relative_path("dependencies/silicium"); arguments.emplace_back(SILICIUM_SYSTEM_LITERAL("-DSILICIUM_INCLUDE_DIR=") + to_os_string(silicium)); } if (boost_root) { arguments.emplace_back(SILICIUM_SYSTEM_LITERAL("-DBOOST_ROOT=") + to_os_string(*boost_root)); } Si::absolute_path const modules = repository / Si::relative_path("modules"); arguments.emplace_back( SILICIUM_SYSTEM_LITERAL("-DCDM_CONFIGURE_INCLUDE_DIRS=") + Si::to_os_string(application_source) + SILICIUM_SYSTEM_LITERAL(";") + Si::to_os_string(modules) + SILICIUM_SYSTEM_LITERAL(";") + Si::to_os_string(repository) ); arguments.emplace_back(Si::to_os_string(source)); #ifdef _MSC_VER arguments.emplace_back(SILICIUM_SYSTEM_LITERAL("-G \"Visual Studio 12 2013\"")); #endif if (Si::run_process(Si::cmake_exe, arguments, build, output).get() != 0) { throw std::runtime_error("Could not CMake-configure the cdm configure executable"); } } { std::vector<Si::os_string> arguments; arguments.emplace_back(SILICIUM_SYSTEM_LITERAL("--build")); arguments.emplace_back(SILICIUM_SYSTEM_LITERAL(".")); if (Si::run_process(Si::cmake_exe, arguments, build, output).get() != 0) { throw std::runtime_error("Could not CMake --build the cdm configure executable"); } } Si::absolute_path built_executable = build / Si::relative_path( #ifdef _MSC_VER SILICIUM_SYSTEM_LITERAL("Debug/") #endif SILICIUM_SYSTEM_LITERAL("configure") #ifdef _WIN32 SILICIUM_SYSTEM_LITERAL(".exe") #endif ); return built_executable; } void run_configure( Si::absolute_path const &configure_executable, Si::absolute_path const &module_permanent, Si::absolute_path const &application_source, Si::absolute_path const &application_build_dir, Si::Sink<char, Si::success>::interface &output) { Si::create_directories(module_permanent, Si::throw_); Si::create_directories(application_build_dir, Si::throw_); std::vector<Si::os_string> arguments; arguments.emplace_back(SILICIUM_SYSTEM_LITERAL("-m")); arguments.emplace_back(Si::to_os_string(module_permanent)); arguments.emplace_back(SILICIUM_SYSTEM_LITERAL("-a")); arguments.emplace_back(Si::to_os_string(application_source)); arguments.emplace_back(SILICIUM_SYSTEM_LITERAL("-b")); arguments.emplace_back(Si::to_os_string(application_build_dir)); int const rc = Si::run_process(configure_executable, arguments, application_build_dir, output).get(); if (rc != 0) { throw std::runtime_error("Could not configure the application: " + boost::lexical_cast<std::string>(rc)); } } } namespace cdm { void do_configure( Si::absolute_path const &temporary, Si::absolute_path const &module_permanent, Si::absolute_path const &application_source, Si::absolute_path const &application_build_dir, Si::optional<Si::absolute_path> const &boost_root, Si::Sink<char, Si::success>::interface &output ) { Si::absolute_path const configure_executable = build_configure(application_source, temporary, boost_root, output); run_configure(configure_executable, module_permanent, application_source, application_build_dir, output); } } <commit_msg>add compiler flag for get_home on Windows<commit_after>#include "configure.hpp" #include <silicium/file_operations.hpp> #include <silicium/cmake.hpp> #include <fstream> namespace { Si::absolute_path build_configure( Si::absolute_path const &application_source, Si::absolute_path const &temporary, Si::optional<Si::absolute_path> const &boost_root, Si::Sink<char, Si::success>::interface &output) { Si::absolute_path const repository = Si::parent( Si::parent(*Si::absolute_path::create(__FILE__)).or_throw( []{ throw std::runtime_error("Could not find parent directory of this file: " __FILE__); } ) ).or_throw( []{ throw std::runtime_error("Could not find the repository directory"); } ); Si::absolute_path const original_main_cpp = repository / Si::relative_path("configure_cmdline/main.cpp"); Si::absolute_path const source = temporary / Si::relative_path("source"); Si::recreate_directories(source, Si::throw_); Si::absolute_path const copied_main_cpp = source / Si::relative_path("main.cpp"); Si::copy(original_main_cpp, copied_main_cpp, Si::throw_); { Si::absolute_path const cmakeLists = source / Si::relative_path("CMakeLists.txt"); std::ofstream cmakeListsFile(cmakeLists.c_str()); cmakeListsFile << "cmake_minimum_required(VERSION 2.8)\n"; cmakeListsFile << "project(configure_cmdline_generated)\n"; cmakeListsFile << "if(UNIX)\n"; cmakeListsFile << " execute_process(COMMAND ${CMAKE_CXX_COMPILER} -dumpversion OUTPUT_VARIABLE GCC_VERSION)\n"; cmakeListsFile << " if(GCC_VERSION VERSION_GREATER 4.7)\n"; cmakeListsFile << " add_definitions(-std=c++1y)\n"; cmakeListsFile << " else()\n"; cmakeListsFile << " add_definitions(-std=c++0x)\n"; cmakeListsFile << " endif()\n"; cmakeListsFile << "endif()\n"; cmakeListsFile << "if(MSVC)\n"; cmakeListsFile << " set(Boost_USE_STATIC_LIBS ON)\n"; cmakeListsFile << " set(CMAKE_EXE_LINKER_FLAGS \"${CMAKE_EXE_LINKER_FLAGS} /SAFESEH:NO\")\n"; cmakeListsFile << " add_definitions(-D_WIN32_WINDOWS)\n"; cmakeListsFile << "endif()\n"; cmakeListsFile << "find_package(Boost REQUIRED filesystem coroutine program_options thread context system)\n"; cmakeListsFile << "include_directories(SYSTEM ${SILICIUM_INCLUDE_DIR} ${Boost_INCLUDE_DIR} ${CDM_CONFIGURE_INCLUDE_DIRS})\n"; cmakeListsFile << "link_directories(${Boost_LIBRARY_DIR})\n"; cmakeListsFile << "add_executable(configure main.cpp)\n"; cmakeListsFile << "target_link_libraries(configure ${Boost_LIBRARIES})\n"; if (!cmakeListsFile) { throw std::runtime_error(("Could not generate " + Si::to_utf8_string(cmakeLists)).c_str()); } } Si::absolute_path const build = temporary / Si::relative_path("build"); Si::recreate_directories(build, Si::throw_); { std::vector<Si::os_string> arguments; { Si::absolute_path const silicium = repository / Si::relative_path("dependencies/silicium"); arguments.emplace_back(SILICIUM_SYSTEM_LITERAL("-DSILICIUM_INCLUDE_DIR=") + to_os_string(silicium)); } if (boost_root) { arguments.emplace_back(SILICIUM_SYSTEM_LITERAL("-DBOOST_ROOT=") + to_os_string(*boost_root)); } Si::absolute_path const modules = repository / Si::relative_path("modules"); arguments.emplace_back( SILICIUM_SYSTEM_LITERAL("-DCDM_CONFIGURE_INCLUDE_DIRS=") + Si::to_os_string(application_source) + SILICIUM_SYSTEM_LITERAL(";") + Si::to_os_string(modules) + SILICIUM_SYSTEM_LITERAL(";") + Si::to_os_string(repository) ); arguments.emplace_back(Si::to_os_string(source)); #ifdef _MSC_VER arguments.emplace_back(SILICIUM_SYSTEM_LITERAL("-G \"Visual Studio 12 2013\"")); #endif if (Si::run_process(Si::cmake_exe, arguments, build, output).get() != 0) { throw std::runtime_error("Could not CMake-configure the cdm configure executable"); } } { std::vector<Si::os_string> arguments; arguments.emplace_back(SILICIUM_SYSTEM_LITERAL("--build")); arguments.emplace_back(SILICIUM_SYSTEM_LITERAL(".")); if (Si::run_process(Si::cmake_exe, arguments, build, output).get() != 0) { throw std::runtime_error("Could not CMake --build the cdm configure executable"); } } Si::absolute_path built_executable = build / Si::relative_path( #ifdef _MSC_VER SILICIUM_SYSTEM_LITERAL("Debug/") #endif SILICIUM_SYSTEM_LITERAL("configure") #ifdef _WIN32 SILICIUM_SYSTEM_LITERAL(".exe") #endif ); return built_executable; } void run_configure( Si::absolute_path const &configure_executable, Si::absolute_path const &module_permanent, Si::absolute_path const &application_source, Si::absolute_path const &application_build_dir, Si::Sink<char, Si::success>::interface &output) { Si::create_directories(module_permanent, Si::throw_); Si::create_directories(application_build_dir, Si::throw_); std::vector<Si::os_string> arguments; arguments.emplace_back(SILICIUM_SYSTEM_LITERAL("-m")); arguments.emplace_back(Si::to_os_string(module_permanent)); arguments.emplace_back(SILICIUM_SYSTEM_LITERAL("-a")); arguments.emplace_back(Si::to_os_string(application_source)); arguments.emplace_back(SILICIUM_SYSTEM_LITERAL("-b")); arguments.emplace_back(Si::to_os_string(application_build_dir)); int const rc = Si::run_process(configure_executable, arguments, application_build_dir, output).get(); if (rc != 0) { throw std::runtime_error("Could not configure the application: " + boost::lexical_cast<std::string>(rc)); } } } namespace cdm { void do_configure( Si::absolute_path const &temporary, Si::absolute_path const &module_permanent, Si::absolute_path const &application_source, Si::absolute_path const &application_build_dir, Si::optional<Si::absolute_path> const &boost_root, Si::Sink<char, Si::success>::interface &output ) { Si::absolute_path const configure_executable = build_configure(application_source, temporary, boost_root, output); run_configure(configure_executable, module_permanent, application_source, application_build_dir, output); } } <|endoftext|>
<commit_before>/* * MiniSatWrapper.cpp - MiniSat wrapper * * This source code is licensed under the MIT License. * See the file COPYING for more details. * * @author: Taku Fukushima <tfukushima@dcl.info.waseda.ac.jp> */ #include <Solver.h> #include "minisat.h" using namespace Minisat // Variable extern "C" int minisat_lit_pos_var(int value) { return toInt(mkLit(value, false)); } extern "C" int minisat_lit_neg_var(int value) { return toInt(mkLit(value, true)); } // Solver extern "C" minisat_solver minisat_new() { return (minisat_solver) new Solver(); } extern "C" void minisat_free(minisat_solver solver) { delete (Solver*) solver; } // Problem specification extern "C" int minisat_new_var(minisat_solver solver) { return ((Solver*) solver)->newVar(); } extern "C" int minisat_add_clause(minisat_solver solver, int *lits, int len) { if (lits == NULL && len == 0) { ((Solver *)solver)->addEmptyClause(); } else { vec<Lit> clause; for (int i = 0; i < len; i++) clause.push(toLit(lits[i])); ((Solver *)solver)->addClause(clause); } return ((Solver *) solver)->okay() ? 1 : 0; } // Solving extern "C" int minisat_solve(minisat_solver solver, int *lits, int len) { vec<Lit> assumptions; for (int i = 0; i < len; i++) assumptions.push(toLit(lits[i])); return ((Solver *)solver)->solve(assumptions) ? 1 : 0; } extern "C" int minisat_simplify(minisat_solver solver) { return ((Solver *) solver)->simplify() ? 1 : 0; } // State extern "C" int minisat_model_value(minisat_solver solver, int var) { lbool lb = ((Solver *)solver)->modelValue(var); return (lb == l_True) ? 0 : (lb == l_False)? 1 : 2; } extern "C" int minisat_assigned_size(minisat_solver solver) { return ((Solver *)solver)->nAssigns(); } extern "C" int minisat_var_size(minisat_solver solver) { return ((Solver *)solver)->nVars(); } extern "C" int minisat_clause_size(minisat_solver solver) { return ((Solver *)solver)->nClauses(); } <commit_msg>[Fix] typo<commit_after>/* * MiniSatWrapper.cpp - MiniSat wrapper * * This source code is licensed under the MIT License. * See the file COPYING for more details. * * @author: Taku Fukushima <tfukushima@dcl.info.waseda.ac.jp> */ #include <Solver.h> #include "minisat.h" using namespace Minisat; // Variable extern "C" int minisat_lit_pos_var(int value) { return toInt(mkLit(value, false)); } extern "C" int minisat_lit_neg_var(int value) { return toInt(mkLit(value, true)); } // Solver extern "C" minisat_solver minisat_new() { return (minisat_solver) new Solver(); } extern "C" void minisat_free(minisat_solver solver) { delete (Solver*) solver; } // Problem specification extern "C" int minisat_new_var(minisat_solver solver) { return ((Solver*) solver)->newVar(); } extern "C" int minisat_add_clause(minisat_solver solver, int *lits, int len) { if (lits == NULL && len == 0) { ((Solver *)solver)->addEmptyClause(); } else { vec<Lit> clause; for (int i = 0; i < len; i++) clause.push(toLit(lits[i])); ((Solver *)solver)->addClause(clause); } return ((Solver *) solver)->okay() ? 1 : 0; } // Solving extern "C" int minisat_solve(minisat_solver solver, int *lits, int len) { vec<Lit> assumptions; for (int i = 0; i < len; i++) assumptions.push(toLit(lits[i])); return ((Solver *)solver)->solve(assumptions) ? 1 : 0; } extern "C" int minisat_simplify(minisat_solver solver) { return ((Solver *) solver)->simplify() ? 1 : 0; } // State extern "C" int minisat_model_value(minisat_solver solver, int var) { lbool lb = ((Solver *)solver)->modelValue(var); return (lb == l_True) ? 0 : (lb == l_False)? 1 : 2; } extern "C" int minisat_assigned_size(minisat_solver solver) { return ((Solver *)solver)->nAssigns(); } extern "C" int minisat_var_size(minisat_solver solver) { return ((Solver *)solver)->nVars(); } extern "C" int minisat_clause_size(minisat_solver solver) { return ((Solver *)solver)->nClauses(); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: canvasfont.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2004-11-26 17:11:53 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _CANVASFONT_HXX #define _CANVASFONT_HXX #ifndef _COMPHELPER_IMPLEMENTATIONREFERENCE_HXX #include <comphelper/implementationreference.hxx> #endif #ifndef _CPPUHELPER_COMPBASE2_HXX_ #include <cppuhelper/compbase2.hxx> #endif #ifndef _COMPHELPER_BROADCASTHELPER_HXX_ #include <comphelper/broadcasthelper.hxx> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _DRAFTS_COM_SUN_STAR_RENDERING_XCANVASFONT_HPP_ #include <drafts/com/sun/star/rendering/XCanvasFont.hpp> #endif #ifndef _SV_FONT_HXX #include <vcl/font.hxx> #endif #include <canvas/vclwrapper.hxx> #include "canvashelper.hxx" #include "impltools.hxx" #define CANVASFONT_IMPLEMENTATION_NAME "VCLCanvas::CanvasFont" /* Definition of CanvasFont class */ namespace vclcanvas { typedef ::cppu::WeakComponentImplHelper2< ::drafts::com::sun::star::rendering::XCanvasFont, ::com::sun::star::lang::XServiceInfo > CanvasFont_Base; class CanvasFont : public ::comphelper::OBaseMutex, public CanvasFont_Base { public: typedef ::comphelper::ImplementationReference< CanvasFont, ::drafts::com::sun::star::rendering::XCanvasFont > ImplRef; CanvasFont( const ::drafts::com::sun::star::rendering::FontRequest& fontRequest, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& extraFontProperties, const ::drafts::com::sun::star::geometry::Matrix2D& rFontMatrix, const OutDevProviderSharedPtr& rDevice ); /// Dispose all internal references virtual void SAL_CALL disposing(); // XCanvasFont virtual ::com::sun::star::uno::Reference< ::drafts::com::sun::star::rendering::XTextLayout > SAL_CALL createTextLayout( const ::drafts::com::sun::star::rendering::StringContext& aText, sal_Int8 nDirection, sal_Int64 nRandomSeed ) throw (::com::sun::star::uno::RuntimeException); virtual ::drafts::com::sun::star::rendering::FontRequest SAL_CALL getFontRequest( ) throw (::com::sun::star::uno::RuntimeException); virtual ::drafts::com::sun::star::rendering::FontMetrics SAL_CALL getFontMetrics( ) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< double > SAL_CALL getAvailableSizes( ) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > SAL_CALL getExtraFontProperties( ) throw (::com::sun::star::uno::RuntimeException); // XServiceInfo virtual ::rtl::OUString SAL_CALL getImplementationName() throw( ::com::sun::star::uno::RuntimeException ); virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw( ::com::sun::star::uno::RuntimeException ); virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw( ::com::sun::star::uno::RuntimeException ); ::Font getVCLFont() const; protected: ~CanvasFont(); // we're a ref-counted UNO class. _We_ destroy ourselves. private: // default: disabled copy/assignment CanvasFont(const CanvasFont&); CanvasFont& operator=( const CanvasFont& ); ::canvas::vcltools::VCLObject<Font> maFont; ::drafts::com::sun::star::rendering::FontRequest maFontRequest; OutDevProviderSharedPtr mpRefDevice; }; } #endif /* _CANVASFONT_HXX */ <commit_msg>INTEGRATION: CWS presfixes01 (1.3.10); FILE MERGED 2005/02/16 11:14:07 fs 1.3.10.1: #i42558# drafts.com.sun.star.drawing/rendering/geometry moved to com.sun.star.*<commit_after>/************************************************************************* * * $RCSfile: canvasfont.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: vg $ $Date: 2005-03-10 11:58:40 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _CANVASFONT_HXX #define _CANVASFONT_HXX #ifndef _COMPHELPER_IMPLEMENTATIONREFERENCE_HXX #include <comphelper/implementationreference.hxx> #endif #ifndef _CPPUHELPER_COMPBASE2_HXX_ #include <cppuhelper/compbase2.hxx> #endif #ifndef _COMPHELPER_BROADCASTHELPER_HXX_ #include <comphelper/broadcasthelper.hxx> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COM_SUN_STAR_RENDERING_XCANVASFONT_HPP_ #include <com/sun/star/rendering/XCanvasFont.hpp> #endif #ifndef _SV_FONT_HXX #include <vcl/font.hxx> #endif #include <canvas/vclwrapper.hxx> #include "canvashelper.hxx" #include "impltools.hxx" #define CANVASFONT_IMPLEMENTATION_NAME "VCLCanvas::CanvasFont" /* Definition of CanvasFont class */ namespace vclcanvas { typedef ::cppu::WeakComponentImplHelper2< ::com::sun::star::rendering::XCanvasFont, ::com::sun::star::lang::XServiceInfo > CanvasFont_Base; class CanvasFont : public ::comphelper::OBaseMutex, public CanvasFont_Base { public: typedef ::comphelper::ImplementationReference< CanvasFont, ::com::sun::star::rendering::XCanvasFont > ImplRef; CanvasFont( const ::com::sun::star::rendering::FontRequest& fontRequest, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& extraFontProperties, const ::com::sun::star::geometry::Matrix2D& rFontMatrix, const OutDevProviderSharedPtr& rDevice ); /// Dispose all internal references virtual void SAL_CALL disposing(); // XCanvasFont virtual ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XTextLayout > SAL_CALL createTextLayout( const ::com::sun::star::rendering::StringContext& aText, sal_Int8 nDirection, sal_Int64 nRandomSeed ) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::rendering::FontRequest SAL_CALL getFontRequest( ) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::rendering::FontMetrics SAL_CALL getFontMetrics( ) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< double > SAL_CALL getAvailableSizes( ) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > SAL_CALL getExtraFontProperties( ) throw (::com::sun::star::uno::RuntimeException); // XServiceInfo virtual ::rtl::OUString SAL_CALL getImplementationName() throw( ::com::sun::star::uno::RuntimeException ); virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw( ::com::sun::star::uno::RuntimeException ); virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw( ::com::sun::star::uno::RuntimeException ); ::Font getVCLFont() const; protected: ~CanvasFont(); // we're a ref-counted UNO class. _We_ destroy ourselves. private: // default: disabled copy/assignment CanvasFont(const CanvasFont&); CanvasFont& operator=( const CanvasFont& ); ::canvas::vcltools::VCLObject<Font> maFont; ::com::sun::star::rendering::FontRequest maFontRequest; OutDevProviderSharedPtr mpRefDevice; }; } #endif /* _CANVASFONT_HXX */ <|endoftext|>
<commit_before>#include "HTTPSession.hpp" #include <boost/beast/http/read.hpp> #include <boost/beast/http/write.hpp> #include <boost/asio/connect.hpp> #include <boost/asio/ssl/rfc2818_verification.hpp> const int DEFAULT_HTTP_VERSION = 11; RequestSession::RequestSession(boost::asio::io_context& ioc) : m_resolver(ioc) { boost::asio::ssl::context ctx{boost::asio::ssl::context::sslv23_client}; ctx.set_default_verify_paths(); ctx.set_verify_mode(boost::asio::ssl::verify_peer); m_socket = std::make_unique<boost::asio::ssl::stream<boost::asio::ip::tcp::socket>>(ioc, ctx); m_response.body_limit(std::numeric_limits<std::uint64_t>::max()); } boost::future<HTTPResponseResult> RequestSession::send(http::verb method, const Url& url, const std::string& body) { m_request = createRequest(method, url.host, url.target, body); m_scheme = url.scheme; m_socket->set_verify_callback(ssl::rfc2818_verification(url.host)); resolve(url.host, url.port, std::bind(&RequestSession::onResolved, shared_from_this(), std::placeholders::_1, std::placeholders::_2)); return m_result.get_future(); } http::request<http::string_body> RequestSession::createRequest(http::verb method, const std::string& host, const std::string& target, const std::string& body) { http::request<http::string_body> request; request.method(method); request.target(target); request.version(DEFAULT_HTTP_VERSION); request.set(http::field::host, host); request.body() = body; request.prepare_payload(); return request; } template<typename Callback> void RequestSession::resolve(const Url::Host& host, unsigned short port, Callback callback) { m_resolver.async_resolve(std::string{host}, std::to_string(port), ip::resolver_base::numeric_service, callback); } void RequestSession::onResolved(const boost::system::error_code& ec, ip::tcp::resolver::results_type results) { if(!ec) { connect(results, std::bind(&RequestSession::onConnected, shared_from_this(), std::placeholders::_1, std::placeholders::_2)); } else { sessionFinished(ec); } } template<typename Callback> void RequestSession::connect(ip::tcp::resolver::results_type results, Callback callback) { asio::async_connect(m_socket->next_layer(), results.begin(), results.end(), callback); } void RequestSession::onConnected(const boost::system::error_code& ec, ip::tcp::resolver::iterator) { if(!ec) { if(m_scheme == Url::Scheme::HTTPS) { handshake(std::bind(&RequestSession::onHandshaked, shared_from_this(), std::placeholders::_1)); } else { write(std::bind(&RequestSession::onWritten, shared_from_this(), std::placeholders::_1, std::placeholders::_2)); } } else { sessionFinished(ec); } } template<typename Callback> void RequestSession::handshake(Callback callback) { m_socket->async_handshake(ssl::stream_base::client, callback); } void RequestSession::onHandshaked(const boost::system::error_code& ec) { if(!ec) { write(std::bind(&RequestSession::onWritten, shared_from_this(), std::placeholders::_1, std::placeholders::_2)); } else { sessionFinished(ec); } } template<typename Callback> void RequestSession::write(Callback callback) { if(m_scheme == Url::Scheme::HTTPS) { http::async_write(*m_socket, m_request, callback); } else { http::async_write(m_socket->next_layer(), m_request, callback); } } void RequestSession::onWritten(const boost::system::error_code& ec, std::size_t /*bytes*/) { if(!ec) { read(std::bind(&RequestSession::onRead, shared_from_this(), std::placeholders::_1, std::placeholders::_2)); } else { sessionFinished(ec); } } template<typename Callback> void RequestSession::read(Callback callback) { if(m_scheme == Url::Scheme::HTTPS) { http::async_read(*m_socket, m_buffer, m_response, callback); } else { http::async_read(m_socket->next_layer(), m_buffer, m_response, callback); } } void RequestSession::onRead(const boost::system::error_code& ec, std::size_t /*bytes*/) { sessionFinished(ec); } void RequestSession::sessionFinished(const boost::system::error_code& ec) { PlayerError error = ec ? PlayerError{PlayerError::Type::HTTP, ec.message()} : PlayerError{}; m_result.set_value(HTTPResponseResult{error, m_response.get().body()}); } <commit_msg>[Issue #173] sessionFinished refactored<commit_after>#include "HTTPSession.hpp" #include <boost/beast/http/read.hpp> #include <boost/beast/http/write.hpp> #include <boost/asio/connect.hpp> #include <boost/asio/ssl/rfc2818_verification.hpp> const int DEFAULT_HTTP_VERSION = 11; RequestSession::RequestSession(boost::asio::io_context& ioc) : m_resolver(ioc) { boost::asio::ssl::context ctx{boost::asio::ssl::context::sslv23_client}; ctx.set_default_verify_paths(); ctx.set_verify_mode(boost::asio::ssl::verify_peer); m_socket = std::make_unique<boost::asio::ssl::stream<boost::asio::ip::tcp::socket>>(ioc, ctx); m_response.body_limit(std::numeric_limits<std::uint64_t>::max()); } boost::future<HTTPResponseResult> RequestSession::send(http::verb method, const Url& url, const std::string& body) { m_request = createRequest(method, url.host, url.target, body); m_scheme = url.scheme; m_socket->set_verify_callback(ssl::rfc2818_verification(url.host)); resolve(url.host, url.port, std::bind(&RequestSession::onResolved, shared_from_this(), std::placeholders::_1, std::placeholders::_2)); return m_result.get_future(); } http::request<http::string_body> RequestSession::createRequest(http::verb method, const std::string& host, const std::string& target, const std::string& body) { http::request<http::string_body> request; request.method(method); request.target(target); request.version(DEFAULT_HTTP_VERSION); request.set(http::field::host, host); request.body() = body; request.prepare_payload(); return request; } template<typename Callback> void RequestSession::resolve(const Url::Host& host, unsigned short port, Callback callback) { m_resolver.async_resolve(std::string{host}, std::to_string(port), ip::resolver_base::numeric_service, callback); } void RequestSession::onResolved(const boost::system::error_code& ec, ip::tcp::resolver::results_type results) { if(!ec) { connect(results, std::bind(&RequestSession::onConnected, shared_from_this(), std::placeholders::_1, std::placeholders::_2)); } else { sessionFinished(ec); } } template<typename Callback> void RequestSession::connect(ip::tcp::resolver::results_type results, Callback callback) { asio::async_connect(m_socket->next_layer(), results.begin(), results.end(), callback); } void RequestSession::onConnected(const boost::system::error_code& ec, ip::tcp::resolver::iterator) { if(!ec) { if(m_scheme == Url::Scheme::HTTPS) { handshake(std::bind(&RequestSession::onHandshaked, shared_from_this(), std::placeholders::_1)); } else { write(std::bind(&RequestSession::onWritten, shared_from_this(), std::placeholders::_1, std::placeholders::_2)); } } else { sessionFinished(ec); } } template<typename Callback> void RequestSession::handshake(Callback callback) { m_socket->async_handshake(ssl::stream_base::client, callback); } void RequestSession::onHandshaked(const boost::system::error_code& ec) { if(!ec) { write(std::bind(&RequestSession::onWritten, shared_from_this(), std::placeholders::_1, std::placeholders::_2)); } else { sessionFinished(ec); } } template<typename Callback> void RequestSession::write(Callback callback) { if(m_scheme == Url::Scheme::HTTPS) { http::async_write(*m_socket, m_request, callback); } else { http::async_write(m_socket->next_layer(), m_request, callback); } } void RequestSession::onWritten(const boost::system::error_code& ec, std::size_t /*bytes*/) { if(!ec) { read(std::bind(&RequestSession::onRead, shared_from_this(), std::placeholders::_1, std::placeholders::_2)); } else { sessionFinished(ec); } } template<typename Callback> void RequestSession::read(Callback callback) { if(m_scheme == Url::Scheme::HTTPS) { http::async_read(*m_socket, m_buffer, m_response, callback); } else { http::async_read(m_socket->next_layer(), m_buffer, m_response, callback); } } void RequestSession::onRead(const boost::system::error_code& ec, std::size_t /*bytes*/) { sessionFinished(ec); } void RequestSession::sessionFinished(const boost::system::error_code& ec) { if(!ec) { m_result.set_value(HTTPResponseResult{PlayerError{}, m_response.get().body()}); } else { PlayerError error{PlayerError::Type::HTTP, ec.message()}; m_result.set_value(HTTPResponseResult{error, {}}); } } <|endoftext|>
<commit_before>#include "pldm_fw_update_cmd.hpp" #include "libpldm/firmware_update.h" #include "common/utils.hpp" #include "pldm_cmd_helper.hpp" namespace pldmtool { namespace fw_update { namespace { using namespace pldmtool::helper; std::vector<std::unique_ptr<CommandInterface>> commands; } // namespace const std::map<uint8_t, std::string> fdStateMachine{ {PLDM_FD_STATE_IDLE, "IDLE"}, {PLDM_FD_STATE_LEARN_COMPONENTS, "LEARN COMPONENTS"}, {PLDM_FD_STATE_READY_XFER, "READY XFER"}, {PLDM_FD_STATE_DOWNLOAD, "DOWNLOAD"}, {PLDM_FD_STATE_VERIFY, "VERIFY"}, {PLDM_FD_STATE_APPLY, "APPLY"}, {PLDM_FD_STATE_ACTIVATE, "ACTIVATE"}}; const std::map<uint8_t, const char*> fdAuxState{ {PLDM_FD_OPERATION_IN_PROGRESS, "Operation in progress"}, {PLDM_FD_OPERATION_SUCCESSFUL, "Operation successful"}, {PLDM_FD_OPERATION_FAILED, "Operation Failed"}, {PLDM_FD_IDLE_LEARN_COMPONENTS_READ_XFER, "Not applicable in current state"}}; const std::map<uint8_t, const char*> fdAuxStateStatus{ {PLDM_FD_AUX_STATE_IN_PROGRESS_OR_SUCCESS, "AuxState is In Progress or Success"}, {PLDM_FD_TIMEOUT, "Timeout occurred while performing action"}, {PLDM_FD_GENERIC_ERROR, "Generic Error has occured"}}; const std::map<uint8_t, const char*> fdReasonCode{ {PLDM_FD_INITIALIZATION, "Initialization of firmware device has occurred"}, {PLDM_FD_ACTIVATE_FW, "ActivateFirmware command was received"}, {PLDM_FD_CANCEL_UPDATE, "CancelUpdate command was received"}, {PLDM_FD_TIMEOUT_LEARN_COMPONENT, "Timeout occurred when in LEARN COMPONENT state"}, {PLDM_FD_TIMEOUT_READY_XFER, "Timeout occurred when in READY XFER state"}, {PLDM_FD_TIMEOUT_DOWNLOAD, "Timeout occurred when in DOWNLOAD state"}, {PLDM_FD_TIMEOUT_VERIFY, "Timeout occurred when in VERIFY state"}, {PLDM_FD_TIMEOUT_APPLY, "Timeout occurred when in APPLY state"}}; class GetStatus : public CommandInterface { public: ~GetStatus() = default; GetStatus() = delete; GetStatus(const GetStatus&) = delete; GetStatus(GetStatus&&) = default; GetStatus& operator=(const GetStatus&) = delete; GetStatus& operator=(GetStatus&&) = default; using CommandInterface::CommandInterface; std::pair<int, std::vector<uint8_t>> createRequestMsg() override { std::vector<uint8_t> requestMsg(sizeof(pldm_msg_hdr) + PLDM_GET_STATUS_REQ_BYTES); auto request = reinterpret_cast<pldm_msg*>(requestMsg.data()); auto rc = encode_get_status_req(instanceId, request, PLDM_GET_STATUS_REQ_BYTES); return {rc, requestMsg}; } void parseResponseMsg(pldm_msg* responsePtr, size_t payloadLength) override { uint8_t completionCode = 0; uint8_t currentState = 0; uint8_t previousState = 0; uint8_t auxState = 0; uint8_t auxStateStatus = 0; uint8_t progressPercent = 0; uint8_t reasonCode = 0; bitfield32_t updateOptionFlagsEnabled{0}; auto rc = decode_get_status_resp( responsePtr, payloadLength, &completionCode, &currentState, &previousState, &auxState, &auxStateStatus, &progressPercent, &reasonCode, &updateOptionFlagsEnabled); if (rc != PLDM_SUCCESS || completionCode != PLDM_SUCCESS) { std::cerr << "Response Message Error: " << "rc=" << rc << ",cc=" << (int)completionCode << "\n"; return; } ordered_json data; data["CurrentState"] = fdStateMachine.at(currentState); data["PreviousState"] = fdStateMachine.at(previousState); data["AuxState"] = fdAuxState.at(auxState); if (auxStateStatus >= PLDM_FD_VENDOR_DEFINED_STATUS_CODE_START && auxStateStatus <= PLDM_FD_VENDOR_DEFINED_STATUS_CODE_END) { data["AuxStateStatus"] = auxStateStatus; } else { data["AuxStateStatus"] = fdAuxStateStatus.at(auxStateStatus); } data["ProgressPercent"] = progressPercent; if (reasonCode >= PLDM_FD_STATUS_VENDOR_DEFINED_MIN && reasonCode <= PLDM_FD_STATUS_VENDOR_DEFINED_MAX) { data["ReasonCode"] = reasonCode; } else { data["ReasonCode"] = fdReasonCode.at(reasonCode); } data["UpdateOptionFlagsEnabled"] = updateOptionFlagsEnabled.value; pldmtool::helper::DisplayInJson(data); } }; void registerCommand(CLI::App& app) { auto fwUpdate = app.add_subcommand("fw_update", "firmware update type commands"); fwUpdate->require_subcommand(1); auto getStatus = fwUpdate->add_subcommand("GetStatus", "Status of the FD"); commands.push_back( std::make_unique<GetStatus>("fw_update", "GetStatus", getStatus)); } } // namespace fw_update } // namespace pldmtool<commit_msg>pldmtool: Add GetFirmwareParameters firmware update command<commit_after>#include "pldm_fw_update_cmd.hpp" #include "libpldm/firmware_update.h" #include "common/utils.hpp" #include "pldm_cmd_helper.hpp" namespace pldmtool { namespace fw_update { namespace { using namespace pldmtool::helper; std::vector<std::unique_ptr<CommandInterface>> commands; } // namespace const std::map<uint8_t, std::string> fdStateMachine{ {PLDM_FD_STATE_IDLE, "IDLE"}, {PLDM_FD_STATE_LEARN_COMPONENTS, "LEARN COMPONENTS"}, {PLDM_FD_STATE_READY_XFER, "READY XFER"}, {PLDM_FD_STATE_DOWNLOAD, "DOWNLOAD"}, {PLDM_FD_STATE_VERIFY, "VERIFY"}, {PLDM_FD_STATE_APPLY, "APPLY"}, {PLDM_FD_STATE_ACTIVATE, "ACTIVATE"}}; const std::map<uint8_t, const char*> fdAuxState{ {PLDM_FD_OPERATION_IN_PROGRESS, "Operation in progress"}, {PLDM_FD_OPERATION_SUCCESSFUL, "Operation successful"}, {PLDM_FD_OPERATION_FAILED, "Operation Failed"}, {PLDM_FD_IDLE_LEARN_COMPONENTS_READ_XFER, "Not applicable in current state"}}; const std::map<uint8_t, const char*> fdAuxStateStatus{ {PLDM_FD_AUX_STATE_IN_PROGRESS_OR_SUCCESS, "AuxState is In Progress or Success"}, {PLDM_FD_TIMEOUT, "Timeout occurred while performing action"}, {PLDM_FD_GENERIC_ERROR, "Generic Error has occured"}}; const std::map<uint8_t, const char*> fdReasonCode{ {PLDM_FD_INITIALIZATION, "Initialization of firmware device has occurred"}, {PLDM_FD_ACTIVATE_FW, "ActivateFirmware command was received"}, {PLDM_FD_CANCEL_UPDATE, "CancelUpdate command was received"}, {PLDM_FD_TIMEOUT_LEARN_COMPONENT, "Timeout occurred when in LEARN COMPONENT state"}, {PLDM_FD_TIMEOUT_READY_XFER, "Timeout occurred when in READY XFER state"}, {PLDM_FD_TIMEOUT_DOWNLOAD, "Timeout occurred when in DOWNLOAD state"}, {PLDM_FD_TIMEOUT_VERIFY, "Timeout occurred when in VERIFY state"}, {PLDM_FD_TIMEOUT_APPLY, "Timeout occurred when in APPLY state"}}; class GetStatus : public CommandInterface { public: ~GetStatus() = default; GetStatus() = delete; GetStatus(const GetStatus&) = delete; GetStatus(GetStatus&&) = default; GetStatus& operator=(const GetStatus&) = delete; GetStatus& operator=(GetStatus&&) = default; using CommandInterface::CommandInterface; std::pair<int, std::vector<uint8_t>> createRequestMsg() override { std::vector<uint8_t> requestMsg(sizeof(pldm_msg_hdr) + PLDM_GET_STATUS_REQ_BYTES); auto request = reinterpret_cast<pldm_msg*>(requestMsg.data()); auto rc = encode_get_status_req(instanceId, request, PLDM_GET_STATUS_REQ_BYTES); return {rc, requestMsg}; } void parseResponseMsg(pldm_msg* responsePtr, size_t payloadLength) override { uint8_t completionCode = 0; uint8_t currentState = 0; uint8_t previousState = 0; uint8_t auxState = 0; uint8_t auxStateStatus = 0; uint8_t progressPercent = 0; uint8_t reasonCode = 0; bitfield32_t updateOptionFlagsEnabled{0}; auto rc = decode_get_status_resp( responsePtr, payloadLength, &completionCode, &currentState, &previousState, &auxState, &auxStateStatus, &progressPercent, &reasonCode, &updateOptionFlagsEnabled); if (rc != PLDM_SUCCESS || completionCode != PLDM_SUCCESS) { std::cerr << "Response Message Error: " << "rc=" << rc << ",cc=" << (int)completionCode << "\n"; return; } ordered_json data; data["CurrentState"] = fdStateMachine.at(currentState); data["PreviousState"] = fdStateMachine.at(previousState); data["AuxState"] = fdAuxState.at(auxState); if (auxStateStatus >= PLDM_FD_VENDOR_DEFINED_STATUS_CODE_START && auxStateStatus <= PLDM_FD_VENDOR_DEFINED_STATUS_CODE_END) { data["AuxStateStatus"] = auxStateStatus; } else { data["AuxStateStatus"] = fdAuxStateStatus.at(auxStateStatus); } data["ProgressPercent"] = progressPercent; if (reasonCode >= PLDM_FD_STATUS_VENDOR_DEFINED_MIN && reasonCode <= PLDM_FD_STATUS_VENDOR_DEFINED_MAX) { data["ReasonCode"] = reasonCode; } else { data["ReasonCode"] = fdReasonCode.at(reasonCode); } data["UpdateOptionFlagsEnabled"] = updateOptionFlagsEnabled.value; pldmtool::helper::DisplayInJson(data); } }; const std::map<uint16_t, std::string> componentClassification{ {PLDM_COMP_UNKNOWN, "Unknown"}, {PLDM_COMP_OTHER, "Other"}, {PLDM_COMP_DRIVER, "Driver"}, {PLDM_COMP_CONFIGURATION_SOFTWARE, "Configuration Software"}, {PLDM_COMP_APPLICATION_SOFTWARE, "Application Software"}, {PLDM_COMP_INSTRUMENTATION, "Instrumentation"}, {PLDM_COMP_FIRMWARE_OR_BIOS, "Firmware/BIOS"}, {PLDM_COMP_DIAGNOSTIC_SOFTWARE, "Diagnostic Software"}, {PLDM_COMP_OPERATING_SYSTEM, "Operating System"}, {PLDM_COMP_MIDDLEWARE, "Middleware"}, {PLDM_COMP_FIRMWARE, "Firmware"}, {PLDM_COMP_BIOS_OR_FCODE, "BIOS/FCode"}, {PLDM_COMP_SUPPORT_OR_SERVICEPACK, "Support/Service Pack"}, {PLDM_COMP_SOFTWARE_BUNDLE, "Software Bundle"}, {PLDM_COMP_DOWNSTREAM_DEVICE, "Downstream Device"}}; class GetFwParams : public CommandInterface { public: ~GetFwParams() = default; GetFwParams() = delete; GetFwParams(const GetFwParams&) = delete; GetFwParams(GetFwParams&&) = default; GetFwParams& operator=(const GetFwParams&) = delete; GetFwParams& operator=(GetFwParams&&) = default; using CommandInterface::CommandInterface; std::pair<int, std::vector<uint8_t>> createRequestMsg() override { std::vector<uint8_t> requestMsg(sizeof(pldm_msg_hdr) + PLDM_GET_FIRMWARE_PARAMETERS_REQ_BYTES); auto request = reinterpret_cast<pldm_msg*>(requestMsg.data()); auto rc = encode_get_firmware_parameters_req( instanceId, PLDM_GET_FIRMWARE_PARAMETERS_REQ_BYTES, request); return {rc, requestMsg}; } void parseResponseMsg(pldm_msg* responsePtr, size_t payloadLength) override { pldm_get_firmware_parameters_resp fwParams{}; variable_field activeCompImageSetVersion{}; variable_field pendingCompImageSetVersion{}; variable_field compParameterTable{}; auto rc = decode_get_firmware_parameters_resp( responsePtr, payloadLength, &fwParams, &activeCompImageSetVersion, &pendingCompImageSetVersion, &compParameterTable); if (rc != PLDM_SUCCESS || fwParams.completion_code != PLDM_SUCCESS) { std::cerr << "Response Message Error: " << "rc=" << rc << ",cc=" << (int)fwParams.completion_code << "\n"; return; } ordered_json capabilitiesDuringUpdate; if (fwParams.capabilities_during_update.bits.bit0) { capabilitiesDuringUpdate ["Component Update Failure Recovery Capability"] = "Device will not revert to previous component image upon failure, timeout or cancellation of the transfer."; } else { capabilitiesDuringUpdate ["Component Update Failure Recovery Capability"] = "Device will revert to previous component image upon failure, timeout or cancellation of the transfer."; } if (fwParams.capabilities_during_update.bits.bit1) { capabilitiesDuringUpdate["Component Update Failure Retry Capability"] = "Device will not be able to update component again unless it exits update mode and the UA sends a new Request Update command."; } else { capabilitiesDuringUpdate["Component Update Failure Retry Capability"] = " Device can have component updated again without exiting update mode and restarting transfer via RequestUpdate command."; } if (fwParams.capabilities_during_update.bits.bit2) { capabilitiesDuringUpdate["Firmware Device Partial Updates"] = "Firmware Device can support a partial update, whereby a package which contains a component image set that is a subset of all components currently residing on the FD, can be transferred."; } else { capabilitiesDuringUpdate["Firmware Device Partial Updates"] = "Firmware Device cannot accept a partial update and all components present on the FD shall be updated."; } if (fwParams.capabilities_during_update.bits.bit3) { capabilitiesDuringUpdate ["Firmware Device Host Functionality during Firmware Update"] = "Device will not revert to previous component image upon failure, timeout or cancellation of the transfer"; } else { capabilitiesDuringUpdate ["Firmware Device Host Functionality during Firmware Update"] = "Device will revert to previous component image upon failure, timeout or cancellation of the transfer"; } if (fwParams.capabilities_during_update.bits.bit4) { capabilitiesDuringUpdate["Firmware Device Update Mode Restrictions"] = "Firmware device unable to enter update mode if host OS environment is active."; } else { capabilitiesDuringUpdate ["Firmware Device Update Mode Restrictions"] = "No host OS environment restriction for update mode"; } ordered_json data; data["CapabilitiesDuringUpdate"] = capabilitiesDuringUpdate; data["ComponentCount"] = static_cast<uint16_t>(fwParams.comp_count); data["ActiveComponentImageSetVersionString"] = pldm::utils::toString(activeCompImageSetVersion); data["PendingComponentImageSetVersionString"] = pldm::utils::toString(pendingCompImageSetVersion); auto compParamPtr = compParameterTable.ptr; auto compParamTableLen = compParameterTable.length; pldm_component_parameter_entry compEntry{}; variable_field activeCompVerStr{}; variable_field pendingCompVerStr{}; ordered_json compDataEntries; while (fwParams.comp_count-- && (compParamTableLen > 0)) { ordered_json compData; auto rc = decode_get_firmware_parameters_resp_comp_entry( compParamPtr, compParamTableLen, &compEntry, &activeCompVerStr, &pendingCompVerStr); if (rc) { std::cerr << "Decoding component parameter table entry failed, RC=" << rc << "\n"; return; } if (componentClassification.contains(compEntry.comp_classification)) { compData["ComponentClassification"] = componentClassification.at(compEntry.comp_classification); } else { compData["ComponentClassification"] = static_cast<uint16_t>(compEntry.comp_classification); } compData["ComponentIdentifier"] = static_cast<uint16_t>(compEntry.comp_identifier); compData["ComponentClassificationIndex"] = static_cast<uint8_t>(compEntry.comp_classification_index); compData["ActiveComponentComparisonStamp"] = static_cast<uint32_t>(compEntry.active_comp_comparison_stamp); // ActiveComponentReleaseData std::array<uint8_t, 8> noReleaseData{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; if (std::equal(noReleaseData.begin(), noReleaseData.end(), compEntry.active_comp_release_date)) { compData["ActiveComponentReleaseDate"] = ""; } else { std::string activeComponentReleaseDate( reinterpret_cast<const char*>( compEntry.active_comp_release_date), sizeof(compEntry.active_comp_release_date)); compData["ActiveComponentReleaseDate"] = activeComponentReleaseDate; } compData["PendingComponentComparisonStamp"] = static_cast<uint32_t>(compEntry.pending_comp_comparison_stamp); // PendingComponentReleaseData if (std::equal(noReleaseData.begin(), noReleaseData.end(), compEntry.pending_comp_release_date)) { compData["PendingComponentReleaseDate"] = ""; } else { std::string pendingComponentReleaseDate( reinterpret_cast<const char*>( compEntry.pending_comp_release_date), sizeof(compEntry.pending_comp_release_date)); compData["PendingComponentReleaseDate"] = pendingComponentReleaseDate; } // ComponentActivationMethods ordered_json componentActivationMethods; if (compEntry.comp_activation_methods.bits.bit0) { componentActivationMethods.push_back("Automatic"); } else if (compEntry.comp_activation_methods.bits.bit1) { componentActivationMethods.push_back("Self-Contained"); } else if (compEntry.comp_activation_methods.bits.bit2) { componentActivationMethods.push_back("Medium-specific reset"); } else if (compEntry.comp_activation_methods.bits.bit3) { componentActivationMethods.push_back("System reboot"); } else if (compEntry.comp_activation_methods.bits.bit4) { componentActivationMethods.push_back("DC power cycel"); } else if (compEntry.comp_activation_methods.bits.bit5) { componentActivationMethods.push_back("AC power cycle"); } compData["ComponentActivationMethods"] = componentActivationMethods; // CapabilitiesDuringUpdate ordered_json compCapabilitiesDuringUpdate; if (compEntry.capabilities_during_update.bits.bit0) { compCapabilitiesDuringUpdate ["Firmware Device apply state functionality"] = "Firmware Device performs an auto-apply during transfer phase and apply step will be completed immediately."; } else { compCapabilitiesDuringUpdate ["Firmware Device apply state functionality"] = " Firmware Device will execute an operation during the APPLY state which will include migrating the new component image to its final non-volatile storage destination."; } compData["CapabilitiesDuringUpdate"] = compCapabilitiesDuringUpdate; compData["ActiveComponentVersionString"] = pldm::utils::toString(activeCompVerStr); compData["PendingComponentVersionString"] = pldm::utils::toString(pendingCompVerStr); compParamPtr += sizeof(pldm_component_parameter_entry) + activeCompVerStr.length + pendingCompVerStr.length; compParamTableLen -= sizeof(pldm_component_parameter_entry) + activeCompVerStr.length + pendingCompVerStr.length; compDataEntries.push_back(compData); } data["ComponentParameterEntries"] = compDataEntries; pldmtool::helper::DisplayInJson(data); } }; void registerCommand(CLI::App& app) { auto fwUpdate = app.add_subcommand("fw_update", "firmware update type commands"); fwUpdate->require_subcommand(1); auto getStatus = fwUpdate->add_subcommand("GetStatus", "Status of the FD"); commands.push_back( std::make_unique<GetStatus>("fw_update", "GetStatus", getStatus)); auto getFwParams = fwUpdate->add_subcommand( "GetFwParams", "To get the component details of the FD"); commands.push_back( std::make_unique<GetFwParams>("fw_update", "GetFwParams", getFwParams)); } } // namespace fw_update } // namespace pldmtool<|endoftext|>
<commit_before>/* Copyright (C) 2001 by Jorrit Tyberghein Copyright (C) 2000 by W.C.A. Wijngaards This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "cssysdef.h" #include "isomater.h" #include "ivideo/txtmgr.h" #include "ivideo/texture.h" SCF_IMPLEMENT_IBASE (csIsoMaterial) SCF_IMPLEMENTS_INTERFACE (iMaterial) SCF_IMPLEMENT_IBASE_END csIsoMaterial::csIsoMaterial () : texture(0), diffuse(CS_DEFMAT_DIFFUSE), ambient(CS_DEFMAT_AMBIENT), reflection(CS_DEFMAT_REFLECTION) { SCF_CONSTRUCT_IBASE (NULL); flat_color.Set (255, 255, 255); // Default state is white, flat-shaded. } csIsoMaterial::csIsoMaterial (iTextureHandle* w) : texture(w), diffuse(CS_DEFMAT_DIFFUSE), ambient(CS_DEFMAT_AMBIENT), reflection(CS_DEFMAT_REFLECTION) { SCF_CONSTRUCT_IBASE (NULL); flat_color.Set (255, 255, 255); // Default state is white, flat-shaded. } csIsoMaterial::~csIsoMaterial () { // delete texture; } iTextureHandle *csIsoMaterial::GetTexture () { return texture; } void csIsoMaterial::GetFlatColor (csRGBpixel &oColor) { oColor = flat_color; if (texture) { iTextureHandle *th = texture; if (th) th->GetMeanColor (oColor.red, oColor.green, oColor.blue); } } void csIsoMaterial::GetReflection (float &oDiffuse, float &oAmbient, float &oReflection) { oDiffuse = diffuse; oAmbient = ambient; oReflection = reflection; } //--------------------------------------------------------------------------- SCF_IMPLEMENT_IBASE_EXT (csIsoMaterialWrapper) SCF_IMPLEMENTS_EMBEDDED_INTERFACE (iMaterialWrapper) SCF_IMPLEMENTS_EMBEDDED_INTERFACE (iIsoMaterialWrapperIndex) SCF_IMPLEMENT_IBASE_EXT_END SCF_IMPLEMENT_EMBEDDED_IBASE (csIsoMaterialWrapper::MaterialWrapper) SCF_IMPLEMENTS_INTERFACE (iMaterialWrapper) SCF_IMPLEMENT_EMBEDDED_IBASE_END SCF_IMPLEMENT_EMBEDDED_IBASE (csIsoMaterialWrapper::IsoMaterialWrapperIndex) SCF_IMPLEMENTS_INTERFACE (iIsoMaterialWrapperIndex) SCF_IMPLEMENT_EMBEDDED_IBASE_END csIsoMaterialWrapper::csIsoMaterialWrapper (iMaterial* material) : csObject (), handle (NULL) { SCF_CONSTRUCT_EMBEDDED_IBASE (scfiMaterialWrapper); SCF_CONSTRUCT_EMBEDDED_IBASE (scfiIsoMaterialWrapperIndex); csIsoMaterialWrapper::material = material; material->IncRef (); index = 0; //csEngine::current_engine->AddToCurrentRegion (this); } csIsoMaterialWrapper::csIsoMaterialWrapper (csIsoMaterialWrapper &th) : csObject (), handle (NULL) { SCF_CONSTRUCT_EMBEDDED_IBASE (scfiMaterialWrapper); SCF_CONSTRUCT_EMBEDDED_IBASE (scfiIsoMaterialWrapperIndex); (material = th.material)->IncRef (); handle = th.GetMaterialHandle (); SetName (th.GetName ()); index = th.index; //csEngine::current_engine->AddToCurrentRegion (this); } csIsoMaterialWrapper::csIsoMaterialWrapper (iMaterialHandle *ith) : csObject (), material (NULL) { SCF_CONSTRUCT_EMBEDDED_IBASE (scfiMaterialWrapper); SCF_CONSTRUCT_EMBEDDED_IBASE (scfiIsoMaterialWrapperIndex); ith->IncRef (); handle = ith; index = 0; //csEngine::current_engine->AddToCurrentRegion (this); } csIsoMaterialWrapper::~csIsoMaterialWrapper () { if (handle) handle->DecRef (); if (material) material->DecRef (); } void csIsoMaterialWrapper::SetMaterialHandle (iMaterialHandle *m) { if (handle) handle->DecRef (); if (material) material->DecRef (); material = NULL; handle = m; handle->IncRef (); } void csIsoMaterialWrapper::SetMaterial (iMaterial *material) { if (csIsoMaterialWrapper::material) csIsoMaterialWrapper::material->DecRef (); csIsoMaterialWrapper::material = material; material->IncRef (); } void csIsoMaterialWrapper::Register (iTextureManager *txtmgr) { handle = txtmgr->RegisterMaterial (material); } void csIsoMaterialWrapper::Visit () { // @@@ This is not very clean! We shouldn't cast from iMaterial to csMaterial. //csMaterial* mat = (csMaterial*)material; //if (mat && mat->GetTextureWrapper ()) //mat->GetTextureWrapper ()->Visit (); } //------------------------------------------------------ csMaterialList -----// SCF_IMPLEMENT_IBASE (csIsoMaterialList) SCF_IMPLEMENTS_EMBEDDED_INTERFACE (iMaterialList) SCF_IMPLEMENT_IBASE_END SCF_IMPLEMENT_EMBEDDED_IBASE (csIsoMaterialList::MaterialList) SCF_IMPLEMENTS_INTERFACE (iMaterialList) SCF_IMPLEMENT_EMBEDDED_IBASE_END csIsoMaterialList::csIsoMaterialList () : csNamedObjVector (16, 16) { SCF_CONSTRUCT_IBASE (NULL); SCF_CONSTRUCT_EMBEDDED_IBASE (scfiMaterialList); lastindex = 0; } csIsoMaterialList::~csIsoMaterialList () { DeleteAll (); } int csIsoMaterialList::GetNewIndex() { int i = lastindex; while(i < Length()) { if(Get(i)==NULL) { lastindex = i+1; return i; } i++; } /// no indices free Push(NULL); lastindex = Length(); return lastindex-1; } void csIsoMaterialList::RemoveIndex(int i) { CS_ASSERT (i >= 0); if(i>=Length()) return; if(i==Length()-1) { (void)Pop(); // pop last element from the list lastindex = Length(); return; } /// remove from middle of list (*this)[i] = NULL; if(i<lastindex) lastindex = i; } csIsoMaterialWrapper* csIsoMaterialList::NewMaterial (iMaterial* material) { csIsoMaterialWrapper *tm = new csIsoMaterialWrapper (material); int i = GetNewIndex(); (*this)[i] = tm; tm->SetIndex(i); return tm; } csIsoMaterialWrapper* csIsoMaterialList::NewMaterial (iMaterialHandle *ith) { csIsoMaterialWrapper *tm = new csIsoMaterialWrapper (ith); int i = GetNewIndex(); (*this)[i] = tm; tm->SetIndex(i); return tm; } <commit_msg>Fixed potential wastefulness of array indices in isomateriallist. Thanks to Jorrit for pointing it out.<commit_after>/* Copyright (C) 2001 by Jorrit Tyberghein Copyright (C) 2000 by W.C.A. Wijngaards This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "cssysdef.h" #include "isomater.h" #include "ivideo/txtmgr.h" #include "ivideo/texture.h" SCF_IMPLEMENT_IBASE (csIsoMaterial) SCF_IMPLEMENTS_INTERFACE (iMaterial) SCF_IMPLEMENT_IBASE_END csIsoMaterial::csIsoMaterial () : texture(0), diffuse(CS_DEFMAT_DIFFUSE), ambient(CS_DEFMAT_AMBIENT), reflection(CS_DEFMAT_REFLECTION) { SCF_CONSTRUCT_IBASE (NULL); flat_color.Set (255, 255, 255); // Default state is white, flat-shaded. } csIsoMaterial::csIsoMaterial (iTextureHandle* w) : texture(w), diffuse(CS_DEFMAT_DIFFUSE), ambient(CS_DEFMAT_AMBIENT), reflection(CS_DEFMAT_REFLECTION) { SCF_CONSTRUCT_IBASE (NULL); flat_color.Set (255, 255, 255); // Default state is white, flat-shaded. } csIsoMaterial::~csIsoMaterial () { // delete texture; } iTextureHandle *csIsoMaterial::GetTexture () { return texture; } void csIsoMaterial::GetFlatColor (csRGBpixel &oColor) { oColor = flat_color; if (texture) { iTextureHandle *th = texture; if (th) th->GetMeanColor (oColor.red, oColor.green, oColor.blue); } } void csIsoMaterial::GetReflection (float &oDiffuse, float &oAmbient, float &oReflection) { oDiffuse = diffuse; oAmbient = ambient; oReflection = reflection; } //--------------------------------------------------------------------------- SCF_IMPLEMENT_IBASE_EXT (csIsoMaterialWrapper) SCF_IMPLEMENTS_EMBEDDED_INTERFACE (iMaterialWrapper) SCF_IMPLEMENTS_EMBEDDED_INTERFACE (iIsoMaterialWrapperIndex) SCF_IMPLEMENT_IBASE_EXT_END SCF_IMPLEMENT_EMBEDDED_IBASE (csIsoMaterialWrapper::MaterialWrapper) SCF_IMPLEMENTS_INTERFACE (iMaterialWrapper) SCF_IMPLEMENT_EMBEDDED_IBASE_END SCF_IMPLEMENT_EMBEDDED_IBASE (csIsoMaterialWrapper::IsoMaterialWrapperIndex) SCF_IMPLEMENTS_INTERFACE (iIsoMaterialWrapperIndex) SCF_IMPLEMENT_EMBEDDED_IBASE_END csIsoMaterialWrapper::csIsoMaterialWrapper (iMaterial* material) : csObject (), handle (NULL) { SCF_CONSTRUCT_EMBEDDED_IBASE (scfiMaterialWrapper); SCF_CONSTRUCT_EMBEDDED_IBASE (scfiIsoMaterialWrapperIndex); csIsoMaterialWrapper::material = material; material->IncRef (); index = 0; //csEngine::current_engine->AddToCurrentRegion (this); } csIsoMaterialWrapper::csIsoMaterialWrapper (csIsoMaterialWrapper &th) : csObject (), handle (NULL) { SCF_CONSTRUCT_EMBEDDED_IBASE (scfiMaterialWrapper); SCF_CONSTRUCT_EMBEDDED_IBASE (scfiIsoMaterialWrapperIndex); (material = th.material)->IncRef (); handle = th.GetMaterialHandle (); SetName (th.GetName ()); index = th.index; //csEngine::current_engine->AddToCurrentRegion (this); } csIsoMaterialWrapper::csIsoMaterialWrapper (iMaterialHandle *ith) : csObject (), material (NULL) { SCF_CONSTRUCT_EMBEDDED_IBASE (scfiMaterialWrapper); SCF_CONSTRUCT_EMBEDDED_IBASE (scfiIsoMaterialWrapperIndex); ith->IncRef (); handle = ith; index = 0; //csEngine::current_engine->AddToCurrentRegion (this); } csIsoMaterialWrapper::~csIsoMaterialWrapper () { if (handle) handle->DecRef (); if (material) material->DecRef (); } void csIsoMaterialWrapper::SetMaterialHandle (iMaterialHandle *m) { if (handle) handle->DecRef (); if (material) material->DecRef (); material = NULL; handle = m; handle->IncRef (); } void csIsoMaterialWrapper::SetMaterial (iMaterial *material) { if (csIsoMaterialWrapper::material) csIsoMaterialWrapper::material->DecRef (); csIsoMaterialWrapper::material = material; material->IncRef (); } void csIsoMaterialWrapper::Register (iTextureManager *txtmgr) { handle = txtmgr->RegisterMaterial (material); } void csIsoMaterialWrapper::Visit () { // @@@ This is not very clean! We shouldn't cast from iMaterial to csMaterial. //csMaterial* mat = (csMaterial*)material; //if (mat && mat->GetTextureWrapper ()) //mat->GetTextureWrapper ()->Visit (); } //------------------------------------------------------ csMaterialList -----// SCF_IMPLEMENT_IBASE (csIsoMaterialList) SCF_IMPLEMENTS_EMBEDDED_INTERFACE (iMaterialList) SCF_IMPLEMENT_IBASE_END SCF_IMPLEMENT_EMBEDDED_IBASE (csIsoMaterialList::MaterialList) SCF_IMPLEMENTS_INTERFACE (iMaterialList) SCF_IMPLEMENT_EMBEDDED_IBASE_END csIsoMaterialList::csIsoMaterialList () : csNamedObjVector (16, 16) { SCF_CONSTRUCT_IBASE (NULL); SCF_CONSTRUCT_EMBEDDED_IBASE (scfiMaterialList); lastindex = 0; } csIsoMaterialList::~csIsoMaterialList () { DeleteAll (); } int csIsoMaterialList::GetNewIndex() { int i = lastindex; while(i < Length()) { if(Get(i)==NULL) { lastindex = i+1; return i; } i++; } /// no indices free Push(NULL); lastindex = Length(); return lastindex-1; } void csIsoMaterialList::RemoveIndex(int i) { CS_ASSERT (i >= 0); if(i>=Length()) return; if(i==Length()-1) { (void)Pop(); // pop last element from the list if(Length()<lastindex) lastindex = Length(); return; } /// remove from middle of list (*this)[i] = NULL; if(i<lastindex) lastindex = i; } csIsoMaterialWrapper* csIsoMaterialList::NewMaterial (iMaterial* material) { csIsoMaterialWrapper *tm = new csIsoMaterialWrapper (material); int i = GetNewIndex(); (*this)[i] = tm; tm->SetIndex(i); return tm; } csIsoMaterialWrapper* csIsoMaterialList::NewMaterial (iMaterialHandle *ith) { csIsoMaterialWrapper *tm = new csIsoMaterialWrapper (ith); int i = GetNewIndex(); (*this)[i] = tm; tm->SetIndex(i); return tm; } <|endoftext|>
<commit_before>#include <vector> #include <algorithm> #include <experimental/random> #include <iostream> #include <iterator> int main(int, char*[]) { const size_t size = 10; const int range_min = 0; const int range_max = 1000; std::vector<int> v(size); std::generate(v.begin(), v.end(), [](){return std::experimental::randint(range_min, range_max);}); std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, "\n")); return 0; } <commit_msg>update no_loop<commit_after>#include <vector> #include <algorithm> #include <experimental/random> #include <iostream> #include <iterator> #include <functional> int main(int, char*[]) { const size_t size = 10; const int range_min = 0; const int range_max = 1000; std::vector<int> v(size); // lamda function std::generate(v.begin(), v.end(), [](){return std::experimental::randint(range_min, range_max);}); // bind std::generate(v.begin(), v.end(), std::bind(std::experimental::randint<int>, range_min, range_max)); std::srand(time(0)); std::generate(v.begin(), v.end(), [](){ return static_cast<int>(range_min + std::rand() * 1.0 / RAND_MAX * (range_max - range_min)); }); std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, "\n")); return 0; } <|endoftext|>
<commit_before>/************************************************************************ filename: CEGuiSample.cpp created: 24/9/2004 author: Paul D Turner *************************************************************************/ /************************************************************************* Crazy Eddie's GUI System (http://www.cegui.org.uk) Copyright (C)2004 - 2005 Paul D Turner (paul@cegui.org.uk) 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *************************************************************************/ #include "CEGuiSample.h" #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "CEGUIConfig.h" // includes for renderer selector classes #if defined( __WIN32__ ) || defined( _WIN32 ) # include "Win32CEGuiRendererSelector.h" #elif defined(__linux__) # ifdef CEGUI_SAMPLES_USE_GTK2 # include "GTK2CEGuiRendererSelector.h" # else # include "CLICEGuiRendererSelector.h" # endif #endif // includes for application types #ifdef CEGUI_SAMPLES_USE_OGRE # include "CEGuiOgreBaseApplication.h" #endif #ifdef CEGUI_SAMPLES_USE_OPENGL # include "CEGuiOpenGLBaseApplication.h" #endif #ifdef CEGUI_SAMPLES_USE_IRRLICHT # include "CEGuiIrrlichtBaseApplication.h" #endif #if defined( __WIN32__ ) || defined( _WIN32 ) # include "CEGuiD3D81BaseApplication.h" # include "CEGuiD3D9BaseApplication.h" #endif // now we include the base CEGuiBaseApplication just in case someone has managed to // get this far without any of the renderers. This ensures the framework will build, // although there will be no renderers available for selection in the samples. #include "CEGuiBaseApplication.h" /************************************************************************* Constructor *************************************************************************/ CEGuiSample::CEGuiSample() : d_rendererSelector(0), d_sampleApp(0) {} /************************************************************************* Destructor *************************************************************************/ CEGuiSample::~CEGuiSample() { if (d_sampleApp) { d_sampleApp->cleanup(); delete d_sampleApp; } if (d_rendererSelector) { delete d_rendererSelector; } } /************************************************************************* Application entry point *************************************************************************/ int CEGuiSample::run() { try { if (initialise()) cleanup(); } catch (CEGUI::Exception& exc) { outputExceptionMessage(exc.getMessage().c_str()); } catch (std::exception& exc) { outputExceptionMessage(exc.what()); } catch(...) { outputExceptionMessage("Unknown exception was caught!"); } return 0; } /************************************************************************* Initialise the sample application *************************************************************************/ bool CEGuiSample::initialise() { // Setup renderer selection dialog for Win32 #if defined( __WIN32__ ) || defined( _WIN32 ) d_rendererSelector = new Win32CEGuiRendererSelector; // enable renderer types supported for Win32 d_rendererSelector->setRendererAvailability(Direct3D81GuiRendererType); d_rendererSelector->setRendererAvailability(Direct3D9GuiRendererType); #elif defined(__linux__) // decide which method to use for renderer selection # ifdef CEGUI_SAMPLES_USE_GTK2 d_rendererSelector = new GTK2CEGuiRendererSelector(); # else d_rendererSelector = new CLICEGuiRendererSelector(); # endif #endif // enable available renderer types #ifdef CEGUI_SAMPLES_USE_OGRE d_rendererSelector->setRendererAvailability(OgreGuiRendererType); #endif #ifdef CEGUI_SAMPLES_USE_OPENGL d_rendererSelector->setRendererAvailability(OpenGLGuiRendererType); #endif #ifdef CEGUI_SAMPLES_USE_IRRLICHT d_rendererSelector->setRendererAvailability(IrrlichtGuiRendererType); #endif // get selection from user if (d_rendererSelector->inkokeDialog()) { // create appropriate application type based upon users selection switch(d_rendererSelector->getSelectedRendererType()) { #ifdef CEGUI_SAMPLES_USE_OGRE case OgreGuiRendererType: d_sampleApp = new CEGuiOgreBaseApplication(); break; #endif #if defined( __WIN32__ ) || defined( _WIN32 ) case Direct3D81GuiRendererType: d_sampleApp = new CEGuiD3D81BaseApplication(); break; case Direct3D9GuiRendererType: d_sampleApp = new CEGuiD3D9BaseApplication(); break; #endif #ifdef CEGUI_SAMPLES_USE_OPENGL case OpenGLGuiRendererType: d_sampleApp = new CEGuiOpenGLBaseApplication(); break; #endif #ifdef CEGUI_SAMPLES_USE_IRRLICHT case IrrlichtGuiRendererType: d_sampleApp = new CEGuiIrrlichtBaseApplication(); break; #endif default: // TODO: Throw exception or something! break; } // execute the base application (which sets up the demo via 'this' and runs it. if (d_sampleApp->execute(this)) { // signal that app initialised and ran return true; } // sample app did not initialise, delete the object. delete d_sampleApp; d_sampleApp = 0; } // delete renderer selector object delete d_rendererSelector; d_rendererSelector = 0; // signal app did not initialise and run. return false; } /************************************************************************* Cleanup the sample application. *************************************************************************/ void CEGuiSample::cleanup() { if (d_sampleApp) { d_sampleApp->cleanup(); delete d_sampleApp; d_sampleApp = 0; } if (d_rendererSelector) { delete d_rendererSelector; d_rendererSelector = 0; } } /************************************************************************* Output a message to the user in some OS independant way. *************************************************************************/ void CEGuiSample::outputExceptionMessage(const char* message) const { #if defined(__WIN32__) || defined(_WIN32) MessageBox(0, message, "CEGUI - Exception", MB_OK|MB_ICONERROR); #else std::cout << "An exception was thrown within the sample framework:" << std::endl; std::cout << message << std::endl; #endif } <commit_msg>Bug Fix: Missing iostream include in CEGuiSample.cpp for non MS-WIndows systems (Patch #1264079 from Mangetsu)<commit_after>/************************************************************************ filename: CEGuiSample.cpp created: 24/9/2004 author: Paul D Turner *************************************************************************/ /************************************************************************* Crazy Eddie's GUI System (http://www.cegui.org.uk) Copyright (C)2004 - 2005 Paul D Turner (paul@cegui.org.uk) 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *************************************************************************/ #include "CEGuiSample.h" #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "CEGUIConfig.h" // includes for renderer selector classes #if defined( __WIN32__ ) || defined( _WIN32 ) # include "Win32CEGuiRendererSelector.h" #elif defined(__linux__) # ifdef CEGUI_SAMPLES_USE_GTK2 # include "GTK2CEGuiRendererSelector.h" # else # include "CLICEGuiRendererSelector.h" # endif #endif // includes for application types #ifdef CEGUI_SAMPLES_USE_OGRE # include "CEGuiOgreBaseApplication.h" #endif #ifdef CEGUI_SAMPLES_USE_OPENGL # include "CEGuiOpenGLBaseApplication.h" #endif #ifdef CEGUI_SAMPLES_USE_IRRLICHT # include "CEGuiIrrlichtBaseApplication.h" #endif #if defined( __WIN32__ ) || defined( _WIN32 ) # include "CEGuiD3D81BaseApplication.h" # include "CEGuiD3D9BaseApplication.h" #endif // now we include the base CEGuiBaseApplication just in case someone has managed to // get this far without any of the renderers. This ensures the framework will build, // although there will be no renderers available for selection in the samples. #include "CEGuiBaseApplication.h" // Include iostream if not on windows. #if defined( __WIN32__ ) || defined( _WIN32 ) #else # include <iostream> #endif /************************************************************************* Constructor *************************************************************************/ CEGuiSample::CEGuiSample() : d_rendererSelector(0), d_sampleApp(0) {} /************************************************************************* Destructor *************************************************************************/ CEGuiSample::~CEGuiSample() { if (d_sampleApp) { d_sampleApp->cleanup(); delete d_sampleApp; } if (d_rendererSelector) { delete d_rendererSelector; } } /************************************************************************* Application entry point *************************************************************************/ int CEGuiSample::run() { try { if (initialise()) cleanup(); } catch (CEGUI::Exception& exc) { outputExceptionMessage(exc.getMessage().c_str()); } catch (std::exception& exc) { outputExceptionMessage(exc.what()); } catch(...) { outputExceptionMessage("Unknown exception was caught!"); } return 0; } /************************************************************************* Initialise the sample application *************************************************************************/ bool CEGuiSample::initialise() { // Setup renderer selection dialog for Win32 #if defined( __WIN32__ ) || defined( _WIN32 ) d_rendererSelector = new Win32CEGuiRendererSelector; // enable renderer types supported for Win32 d_rendererSelector->setRendererAvailability(Direct3D81GuiRendererType); d_rendererSelector->setRendererAvailability(Direct3D9GuiRendererType); #elif defined(__linux__) // decide which method to use for renderer selection # ifdef CEGUI_SAMPLES_USE_GTK2 d_rendererSelector = new GTK2CEGuiRendererSelector(); # else d_rendererSelector = new CLICEGuiRendererSelector(); # endif #endif // enable available renderer types #ifdef CEGUI_SAMPLES_USE_OGRE d_rendererSelector->setRendererAvailability(OgreGuiRendererType); #endif #ifdef CEGUI_SAMPLES_USE_OPENGL d_rendererSelector->setRendererAvailability(OpenGLGuiRendererType); #endif #ifdef CEGUI_SAMPLES_USE_IRRLICHT d_rendererSelector->setRendererAvailability(IrrlichtGuiRendererType); #endif // get selection from user if (d_rendererSelector->inkokeDialog()) { // create appropriate application type based upon users selection switch(d_rendererSelector->getSelectedRendererType()) { #ifdef CEGUI_SAMPLES_USE_OGRE case OgreGuiRendererType: d_sampleApp = new CEGuiOgreBaseApplication(); break; #endif #if defined( __WIN32__ ) || defined( _WIN32 ) case Direct3D81GuiRendererType: d_sampleApp = new CEGuiD3D81BaseApplication(); break; case Direct3D9GuiRendererType: d_sampleApp = new CEGuiD3D9BaseApplication(); break; #endif #ifdef CEGUI_SAMPLES_USE_OPENGL case OpenGLGuiRendererType: d_sampleApp = new CEGuiOpenGLBaseApplication(); break; #endif #ifdef CEGUI_SAMPLES_USE_IRRLICHT case IrrlichtGuiRendererType: d_sampleApp = new CEGuiIrrlichtBaseApplication(); break; #endif default: // TODO: Throw exception or something! break; } // execute the base application (which sets up the demo via 'this' and runs it. if (d_sampleApp->execute(this)) { // signal that app initialised and ran return true; } // sample app did not initialise, delete the object. delete d_sampleApp; d_sampleApp = 0; } // delete renderer selector object delete d_rendererSelector; d_rendererSelector = 0; // signal app did not initialise and run. return false; } /************************************************************************* Cleanup the sample application. *************************************************************************/ void CEGuiSample::cleanup() { if (d_sampleApp) { d_sampleApp->cleanup(); delete d_sampleApp; d_sampleApp = 0; } if (d_rendererSelector) { delete d_rendererSelector; d_rendererSelector = 0; } } /************************************************************************* Output a message to the user in some OS independant way. *************************************************************************/ void CEGuiSample::outputExceptionMessage(const char* message) const { #if defined(__WIN32__) || defined(_WIN32) MessageBox(0, message, "CEGUI - Exception", MB_OK|MB_ICONERROR); #else std::cout << "An exception was thrown within the sample framework:" << std::endl; std::cout << message << std::endl; #endif } <|endoftext|>
<commit_before>/* bzflag * Copyright (c) 1993-2011 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ // logDetail.cpp : Plugin module for logging server events to stdout // #include <iostream> #include <sstream> #include <cstring> #include "bzfsAPI.h" enum action { join , auth , part }; class LogDetail : public bz_Plugin { public: virtual const char* Name (){return "Log Detail";} virtual void Init ( const char* config); virtual void Cleanup (); virtual void Event ( bz_EventData *eventData ); private: std::string displayPlayerPrivs( int playerID ); std::string displayCallsign( bz_ApiString callsign ); std::string displayCallsign( int playerID ); std::string displayBZid( int playerID ); std::string displayTeam( bz_eTeamType team ); virtual void listPlayers( action act, bz_PlayerJoinPartEventData_V1 *data ); }; BZ_PLUGIN(LogDetail) void LogDetail::Init ( const char* /*commandLine*/ ) { Register(bz_eSlashCommandEvent); Register(bz_eRawChatMessageEvent); Register(bz_eServerMsgEvent); Register(bz_ePlayerJoinEvent); Register(bz_ePlayerPartEvent); Register(bz_ePlayerAuthEvent); Register(bz_eMessageFilteredEvent); bz_debugMessage(0, "SERVER-STATUS Running"); bz_debugMessagef(0, "SERVER-MAPNAME %s", bz_getPublicDescription().c_str()); listPlayers( join , NULL ); } void LogDetail::Cleanup() { listPlayers( part , NULL ); bz_debugMessage(0, "SERVER-STATUS Stopped"); } void LogDetail::Event( bz_EventData *eventData ) { bz_ChatEventData_V1 *chatData = (bz_ChatEventData_V1 *) eventData; bz_ServerMsgEventData_V1 *serverMsgData = (bz_ServerMsgEventData_V1 *) eventData; bz_SlashCommandEventData_V1 *cmdData = (bz_SlashCommandEventData_V1 *) eventData; bz_PlayerJoinPartEventData_V1 *joinPartData = (bz_PlayerJoinPartEventData_V1 *) eventData; bz_PlayerAuthEventData_V1 *authData = (bz_PlayerAuthEventData_V1 *) eventData; bz_MessageFilteredEventData_V1 *filteredData = (bz_MessageFilteredEventData_V1 *) eventData; char temp[9] = {0}; if (eventData) { switch (eventData->eventType) { case bz_eSlashCommandEvent: // Slash commands are case insensitive // Tokenize the stream and check the first word // /report -> MSG-REPORT // anything -> MSG-COMMAND strncpy(temp, cmdData->message.c_str(), 8); if (strcasecmp( temp, "/REPORT ") == 0) { bz_debugMessagef(0, "MSG-REPORT %s %s", displayCallsign( cmdData->from ).c_str(), cmdData->message.c_str()+8); } else { bz_debugMessagef(0, "MSG-COMMAND %s %s", displayCallsign( cmdData->from ).c_str(), cmdData->message.c_str()+1); } break; case bz_eRawChatMessageEvent: if (chatData->from == BZ_SERVER) break; if ((chatData->to == BZ_ALLUSERS) && (chatData->team == eNoTeam)) { bz_debugMessagef(0, "MSG-BROADCAST %s %s", displayCallsign( chatData->from ).c_str(), chatData->message.c_str()); } else if (chatData->to == BZ_NULLUSER) { if (chatData->team == eAdministrators) { bz_debugMessagef(0, "MSG-ADMIN %s %s", displayCallsign( chatData->from ).c_str(), chatData->message.c_str()); } else { bz_debugMessagef(0, "MSG-TEAM %s %s %s", displayCallsign( chatData->from ).c_str(), displayTeam( chatData->team ).c_str(), chatData->message.c_str()); } } else { bz_debugMessagef(0, "MSG-DIRECT %s %s %s", displayCallsign( chatData->from ).c_str(), displayCallsign( chatData->to ).c_str(), chatData->message.c_str()); } break; case bz_eMessageFilteredEvent: bz_debugMessagef(0, "MSG-FILTERED %s %s", displayCallsign( filteredData->playerID ).c_str(), filteredData->filteredMessage.c_str()); break; case bz_eServerMsgEvent: if ((serverMsgData->to == BZ_ALLUSERS) && (serverMsgData->team == eNoTeam)) { bz_debugMessagef(0, "MSG-BROADCAST 6:SERVER %s", serverMsgData->message.c_str()); } else if (serverMsgData->to == BZ_NULLUSER) { if (serverMsgData->team == eAdministrators) { bz_debugMessagef(0, "MSG-ADMIN 6:SERVER %s", serverMsgData->message.c_str()); } else { bz_debugMessagef(0, "MSG-TEAM 6:SERVER %s %s", displayTeam( serverMsgData->team ).c_str(), serverMsgData->message.c_str()); } } else { bz_debugMessagef(0, "MSG-DIRECT 6:SERVER %s %s", displayCallsign( serverMsgData->to ).c_str(), serverMsgData->message.c_str()); } break; case bz_ePlayerJoinEvent: { if (joinPartData->record) { bz_debugMessagef(0, "PLAYER-JOIN %s #%d%s %s %s", displayCallsign( joinPartData->playerID).c_str(), joinPartData->playerID, displayBZid( joinPartData->playerID ).c_str(), displayTeam( joinPartData->record->team ).c_str(), displayPlayerPrivs( joinPartData->playerID ).c_str()); listPlayers( join, joinPartData); } } break; case bz_ePlayerPartEvent: bz_debugMessagef(0, "PLAYER-PART %s #%d%s %s", displayCallsign( joinPartData->playerID ).c_str(), joinPartData->playerID, displayBZid( joinPartData->playerID ).c_str(), joinPartData->reason.c_str()); listPlayers( part, joinPartData); break; case bz_ePlayerAuthEvent: bz_debugMessagef(0, "PLAYER-AUTH %s %s", displayCallsign( authData->playerID ).c_str(), displayPlayerPrivs( authData->playerID ).c_str()), listPlayers( join, joinPartData); break; default : break; } } } std::string LogDetail::displayBZid( int playerID ) { std::ostringstream bzid; bz_BasePlayerRecord *player = bz_getPlayerByIndex( playerID ); if (player) { if (player->globalUser) bzid << " BZid:" << player->bzID.c_str(); bz_freePlayerRecord( player ); } return bzid.str(); } std::string LogDetail::displayPlayerPrivs( int playerID ) { std::ostringstream playerPrivs; bz_BasePlayerRecord *player = bz_getPlayerByIndex( playerID ); if (player) { playerPrivs << "IP:" << player->ipAddress.c_str(); if (player->verified ) playerPrivs << " VERIFIED"; if (player->globalUser ) playerPrivs << " GLOBALUSER"; if (player->admin ) playerPrivs << " ADMIN"; if (player->op ) playerPrivs << " OPERATOR"; bz_freePlayerRecord( player ); } else { playerPrivs << "IP:0.0.0.0"; } return playerPrivs.str(); } std::string LogDetail::displayCallsign( bz_ApiString callsign ) { std::ostringstream result; result << strlen( callsign.c_str() ) << ":" << callsign.c_str(); return result.str(); } std::string LogDetail::displayCallsign( int playerID ) { std::ostringstream callsign; bz_BasePlayerRecord *player = bz_getPlayerByIndex( playerID ); if (player) { callsign << strlen( player->callsign.c_str() ) << ":"; callsign << player->callsign.c_str(); bz_freePlayerRecord( player ); } else { callsign << "7:UNKNOWN"; } return callsign.str(); } std::string LogDetail::displayTeam( bz_eTeamType team ) { // Display the player team switch ( team ) { case eRogueTeam: return std::string("ROGUE"); case eRedTeam: return std::string("RED"); case eGreenTeam: return std::string("GREEN"); case eBlueTeam: return std::string("BLUE"); case ePurpleTeam: return std::string("PURPLE"); case eRabbitTeam: return std::string("RABBIT"); case eHunterTeam: return std::string("HUNTER"); case eObservers: return std::string("OBSERVER"); default : return std::string("NOTEAM"); } } void LogDetail::listPlayers( action act , bz_PlayerJoinPartEventData_V1 *data ) { bz_APIIntList *playerList = bz_newIntList(); bz_BasePlayerRecord *player = NULL; std::ostringstream msg; char playerStatus; int numPlayers; bz_getPlayerIndexList( playerList ); bz_debugMessage( 4 , "Players:" ); // // Count number of players // numPlayers = 0; for ( unsigned int i = 0; i < playerList->size(); i++ ) { player = bz_getPlayerByIndex( playerList->get(i)); if (player) { if ((player->callsign != "") && (act == join || act == auth || (data && (player->playerID != data->playerID)))) numPlayers++; bz_freePlayerRecord( player ); } } // // Display number of players, callsign, and motto string in the following format: // // PLAYERS (nn) [G]cc:callsign(ee:mottostring) // nn - number of players // G - global auth identifier (+|-| |@) // cc - count of characters in player callsign // callsign - player callsign // ee - count of characters in motto string // mottostring - player motto string // // eg. // PLAYERS (2) [@]7:Thumper(16:me@somewhere.net) [ ]3:xxx() // msg.str(""); msg << "PLAYERS (" << numPlayers << ") "; for ( unsigned int i = 0; i < playerList->size(); i++ ) { player = bz_getPlayerByIndex( playerList->get(i)); if (player) { if ((player->callsign != "") && (act == join || act == auth || (data && (player->playerID != data->playerID)))) { playerStatus = ' '; if (player->globalUser) playerStatus = '+'; if (player->verified) playerStatus = '+'; if (player->admin && !bz_hasPerm(player->playerID, bz_perm_hideAdmin)) playerStatus = '@'; msg << "[" << playerStatus << "]"; msg << player->callsign.size() << ':'; msg << player->callsign.c_str(); } } } bz_debugMessage(0, msg.str().c_str()); bz_deleteIntList(playerList); } // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <commit_msg>Revert r22033<commit_after>/* bzflag * Copyright (c) 1993-2011 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ // logDetail.cpp : Plugin module for logging server events to stdout // #include <iostream> #include <sstream> #include <cstring> #include "bzfsAPI.h" enum action { join , auth , part }; class LogDetail : public bz_Plugin { public: virtual const char* Name (){return "Log Detail";} virtual void Init ( const char* config); virtual void Cleanup (); virtual void Event ( bz_EventData *eventData ); private: std::string displayPlayerPrivs( int playerID ); std::string displayCallsign( bz_ApiString callsign ); std::string displayCallsign( int playerID ); std::string displayBZid( int playerID ); std::string displayTeam( bz_eTeamType team ); virtual void listPlayers( action act, bz_PlayerJoinPartEventData_V1 *data ); }; BZ_PLUGIN(LogDetail) void LogDetail::Init ( const char* /*commandLine*/ ) { Register(bz_eSlashCommandEvent); Register(bz_eRawChatMessageEvent); Register(bz_eServerMsgEvent); Register(bz_ePlayerJoinEvent); Register(bz_ePlayerPartEvent); Register(bz_ePlayerAuthEvent); Register(bz_eMessageFilteredEvent); bz_debugMessage(0, "SERVER-STATUS Running"); bz_debugMessagef(0, "SERVER-MAPNAME %s", bz_getPublicDescription().c_str()); listPlayers( join , NULL ); } void LogDetail::Cleanup() { listPlayers( part , NULL ); bz_debugMessage(0, "SERVER-STATUS Stopped"); } void LogDetail::Event( bz_EventData *eventData ) { bz_ChatEventData_V1 *chatData = (bz_ChatEventData_V1 *) eventData; bz_ServerMsgEventData_V1 *serverMsgData = (bz_ServerMsgEventData_V1 *) eventData; bz_SlashCommandEventData_V1 *cmdData = (bz_SlashCommandEventData_V1 *) eventData; bz_PlayerJoinPartEventData_V1 *joinPartData = (bz_PlayerJoinPartEventData_V1 *) eventData; bz_PlayerAuthEventData_V1 *authData = (bz_PlayerAuthEventData_V1 *) eventData; bz_MessageFilteredEventData_V1 *filteredData = (bz_MessageFilteredEventData_V1 *) eventData; char temp[9] = {0}; if (eventData) { switch (eventData->eventType) { case bz_eSlashCommandEvent: // Slash commands are case insensitive // Tokenize the stream and check the first word // /report -> MSG-REPORT // anything -> MSG-COMMAND strncpy(temp, cmdData->message.c_str(), 8); if (strcasecmp( temp, "/REPORT ") == 0) { bz_debugMessagef(0, "MSG-REPORT %s %s", displayCallsign( cmdData->from ).c_str(), cmdData->message.c_str()+8); } else { bz_debugMessagef(0, "MSG-COMMAND %s %s", displayCallsign( cmdData->from ).c_str(), cmdData->message.c_str()+1); } break; case bz_eRawChatMessageEvent: if ((chatData->to == BZ_ALLUSERS) && (chatData->team == eNoTeam)) { bz_debugMessagef(0, "MSG-BROADCAST %s %s", displayCallsign( chatData->from ).c_str(), chatData->message.c_str()); } else if (chatData->to == BZ_NULLUSER) { if (chatData->team == eAdministrators) { bz_debugMessagef(0, "MSG-ADMIN %s %s", displayCallsign( chatData->from ).c_str(), chatData->message.c_str()); } else { bz_debugMessagef(0, "MSG-TEAM %s %s %s", displayCallsign( chatData->from ).c_str(), displayTeam( chatData->team ).c_str(), chatData->message.c_str()); } } else { bz_debugMessagef(0, "MSG-DIRECT %s %s %s", displayCallsign( chatData->from ).c_str(), displayCallsign( chatData->to ).c_str(), chatData->message.c_str()); } break; case bz_eMessageFilteredEvent: bz_debugMessagef(0, "MSG-FILTERED %s %s", displayCallsign( filteredData->playerID ).c_str(), filteredData->filteredMessage.c_str()); break; case bz_eServerMsgEvent: if ((serverMsgData->to == BZ_ALLUSERS) && (serverMsgData->team == eNoTeam)) { bz_debugMessagef(0, "MSG-BROADCAST 6:SERVER %s", serverMsgData->message.c_str()); } else if (serverMsgData->to == BZ_NULLUSER) { if (serverMsgData->team == eAdministrators) { bz_debugMessagef(0, "MSG-ADMIN 6:SERVER %s", serverMsgData->message.c_str()); } else { bz_debugMessagef(0, "MSG-TEAM 6:SERVER %s %s", displayTeam( serverMsgData->team ).c_str(), serverMsgData->message.c_str()); } } else { bz_debugMessagef(0, "MSG-DIRECT 6:SERVER %s %s", displayCallsign( serverMsgData->to ).c_str(), serverMsgData->message.c_str()); } break; case bz_ePlayerJoinEvent: { if (joinPartData->record) { bz_debugMessagef(0, "PLAYER-JOIN %s #%d%s %s %s", displayCallsign( joinPartData->playerID).c_str(), joinPartData->playerID, displayBZid( joinPartData->playerID ).c_str(), displayTeam( joinPartData->record->team ).c_str(), displayPlayerPrivs( joinPartData->playerID ).c_str()); listPlayers( join, joinPartData); } } break; case bz_ePlayerPartEvent: bz_debugMessagef(0, "PLAYER-PART %s #%d%s %s", displayCallsign( joinPartData->playerID ).c_str(), joinPartData->playerID, displayBZid( joinPartData->playerID ).c_str(), joinPartData->reason.c_str()); listPlayers( part, joinPartData); break; case bz_ePlayerAuthEvent: bz_debugMessagef(0, "PLAYER-AUTH %s %s", displayCallsign( authData->playerID ).c_str(), displayPlayerPrivs( authData->playerID ).c_str()), listPlayers( join, joinPartData); break; default : break; } } } std::string LogDetail::displayBZid( int playerID ) { std::ostringstream bzid; bz_BasePlayerRecord *player = bz_getPlayerByIndex( playerID ); if (player) { if (player->globalUser) bzid << " BZid:" << player->bzID.c_str(); bz_freePlayerRecord( player ); } return bzid.str(); } std::string LogDetail::displayPlayerPrivs( int playerID ) { std::ostringstream playerPrivs; bz_BasePlayerRecord *player = bz_getPlayerByIndex( playerID ); if (player) { playerPrivs << "IP:" << player->ipAddress.c_str(); if (player->verified ) playerPrivs << " VERIFIED"; if (player->globalUser ) playerPrivs << " GLOBALUSER"; if (player->admin ) playerPrivs << " ADMIN"; if (player->op ) playerPrivs << " OPERATOR"; bz_freePlayerRecord( player ); } else { playerPrivs << "IP:0.0.0.0"; } return playerPrivs.str(); } std::string LogDetail::displayCallsign( bz_ApiString callsign ) { std::ostringstream result; result << strlen( callsign.c_str() ) << ":" << callsign.c_str(); return result.str(); } std::string LogDetail::displayCallsign( int playerID ) { std::ostringstream callsign; bz_BasePlayerRecord *player = bz_getPlayerByIndex( playerID ); if (player) { callsign << strlen( player->callsign.c_str() ) << ":"; callsign << player->callsign.c_str(); bz_freePlayerRecord( player ); } else { callsign << "7:UNKNOWN"; } return callsign.str(); } std::string LogDetail::displayTeam( bz_eTeamType team ) { // Display the player team switch ( team ) { case eRogueTeam: return std::string("ROGUE"); case eRedTeam: return std::string("RED"); case eGreenTeam: return std::string("GREEN"); case eBlueTeam: return std::string("BLUE"); case ePurpleTeam: return std::string("PURPLE"); case eRabbitTeam: return std::string("RABBIT"); case eHunterTeam: return std::string("HUNTER"); case eObservers: return std::string("OBSERVER"); default : return std::string("NOTEAM"); } } void LogDetail::listPlayers( action act , bz_PlayerJoinPartEventData_V1 *data ) { bz_APIIntList *playerList = bz_newIntList(); bz_BasePlayerRecord *player = NULL; std::ostringstream msg; char playerStatus; int numPlayers; bz_getPlayerIndexList( playerList ); bz_debugMessage( 4 , "Players:" ); // // Count number of players // numPlayers = 0; for ( unsigned int i = 0; i < playerList->size(); i++ ) { player = bz_getPlayerByIndex( playerList->get(i)); if (player) { if ((player->callsign != "") && (act == join || act == auth || (data && (player->playerID != data->playerID)))) numPlayers++; bz_freePlayerRecord( player ); } } // // Display number of players, callsign, and motto string in the following format: // // PLAYERS (nn) [G]cc:callsign(ee:mottostring) // nn - number of players // G - global auth identifier (+|-| |@) // cc - count of characters in player callsign // callsign - player callsign // ee - count of characters in motto string // mottostring - player motto string // // eg. // PLAYERS (2) [@]7:Thumper(16:me@somewhere.net) [ ]3:xxx() // msg.str(""); msg << "PLAYERS (" << numPlayers << ") "; for ( unsigned int i = 0; i < playerList->size(); i++ ) { player = bz_getPlayerByIndex( playerList->get(i)); if (player) { if ((player->callsign != "") && (act == join || act == auth || (data && (player->playerID != data->playerID)))) { playerStatus = ' '; if (player->globalUser) playerStatus = '+'; if (player->verified) playerStatus = '+'; if (player->admin && !bz_hasPerm(player->playerID, bz_perm_hideAdmin)) playerStatus = '@'; msg << "[" << playerStatus << "]"; msg << player->callsign.size() << ':'; msg << player->callsign.c_str(); } } } bz_debugMessage(0, msg.str().c_str()); bz_deleteIntList(playerList); } // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <|endoftext|>
<commit_before>#include "erl_nif.h" #include "CPool.hpp" #include "stdio.h" extern "C" { static ErlNifResourceType* cpool_node_RESOURCE = NULL; static ErlNifResourceType* cpool_RESOURCE = NULL; typedef struct { CPool *pool; } cpool_handle; typedef struct { CPoolNode *node; } cpool_node_handle; // Prototypes static ERL_NIF_TERM cpool_new(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); static ERL_NIF_TERM cpool_join(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); static ERL_NIF_TERM cpool_depart(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); static ERL_NIF_TERM cpool_next(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); static ErlNifFunc nif_funcs[] = { {"new", 1, cpool_new}, {"join", 2, cpool_join}, {"depart", 2, cpool_depart}, {"next", 2, cpool_next} }; static ERL_NIF_TERM cpool_new(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) { ERL_NIF_TERM result; unsigned long schedulers = 0; if (enif_get_ulong(env, argv[0], &schedulers) == 0) { return enif_make_badarg(env); } cpool_handle* handle = (cpool_handle*)enif_alloc_resource(cpool_RESOURCE, sizeof(cpool_handle)); handle->pool = new CPool(schedulers); result = enif_make_resource(env, handle); enif_release_resource(handle); return enif_make_tuple2(env, enif_make_atom(env, "ok"), result); } static ERL_NIF_TERM cpool_join(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) { cpool_handle* handle = NULL; cpool_node_handle* node; ERL_NIF_TERM result; if (enif_get_resource(env, argv[0], cpool_RESOURCE, (void**)&handle) == 0) { return enif_make_badarg(env); } node = (cpool_node_handle*)enif_alloc_resource(cpool_node_RESOURCE, sizeof(cpool_node_handle)); node->node = handle->pool->Join(argv[1]); result = enif_make_resource(env, (void*)node); enif_release_resource((void*)node); return result; } static ERL_NIF_TERM cpool_depart(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) { ERL_NIF_TERM result; cpool_handle* handle_pool = NULL; cpool_node_handle* handle_node = NULL; if (enif_get_resource(env, argv[0], cpool_RESOURCE, (void**)&handle_pool) == 0) { return enif_make_badarg(env); } if (enif_get_resource(env, argv[1], cpool_node_RESOURCE, (void**)&handle_node) == 0) { return enif_make_badarg(env); } result = handle_pool->pool->Depart(env, handle_node->node); return result; } static ERL_NIF_TERM cpool_next(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) { ERL_NIF_TERM result; cpool_handle* handle = NULL; unsigned long iterator; if (enif_get_resource(env, argv[0], cpool_RESOURCE, (void**)&handle) == 0) { return enif_make_badarg(env); } if (enif_get_ulong(env, argv[1], &iterator) == 0) { return enif_make_badarg(env); } // Reduce iterator to account for zero indice --iterator; result = handle->pool->Next(env, iterator); return result; } static void cpool_resource_cleanup(ErlNifEnv* env, void* arg) { cpool_handle* handle = (cpool_handle*)arg; delete handle->pool; handle->pool = NULL; } static void cpool_node_resource_cleanup(ErlNifEnv* env, void* arg) { ((cpool_node_handle*)arg)->node = NULL; } static int on_load(ErlNifEnv* env, void** priv_data, ERL_NIF_TERM load_info) { ErlNifResourceFlags flags = (ErlNifResourceFlags)(ERL_NIF_RT_CREATE | ERL_NIF_RT_TAKEOVER); ErlNifResourceType* cpool = enif_open_resource_type(env, NULL, "cpool_resource", &cpool_resource_cleanup, flags, NULL); if (cpool == NULL) return -1; ErlNifResourceType* cpool_node = enif_open_resource_type(env, NULL, "cpool_node_resource", &cpool_node_resource_cleanup, flags, NULL); if (cpool_node == NULL) return -1; cpool_RESOURCE = cpool; cpool_node_RESOURCE = cpool_node; return 0; } ERL_NIF_INIT(cpool, nif_funcs, &on_load, NULL, NULL, NULL); } <commit_msg>Support for upgrading the cpool nif<commit_after>#include "erl_nif.h" #include "CPool.hpp" #include "stdio.h" extern "C" { static ErlNifResourceType* cpool_node_RESOURCE = NULL; static ErlNifResourceType* cpool_RESOURCE = NULL; typedef struct { CPool *pool; } cpool_handle; typedef struct { CPoolNode *node; } cpool_node_handle; // Prototypes static ERL_NIF_TERM cpool_new(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); static ERL_NIF_TERM cpool_join(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); static ERL_NIF_TERM cpool_depart(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); static ERL_NIF_TERM cpool_next(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); static ErlNifFunc nif_funcs[] = { {"new", 1, cpool_new}, {"join", 2, cpool_join}, {"depart", 2, cpool_depart}, {"next", 2, cpool_next} }; static ERL_NIF_TERM cpool_new(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) { ERL_NIF_TERM result; unsigned long schedulers = 0; if (enif_get_ulong(env, argv[0], &schedulers) == 0) { return enif_make_badarg(env); } cpool_handle* handle = (cpool_handle*)enif_alloc_resource(cpool_RESOURCE, sizeof(cpool_handle)); handle->pool = new CPool(schedulers); result = enif_make_resource(env, handle); enif_release_resource(handle); return enif_make_tuple2(env, enif_make_atom(env, "ok"), result); } static ERL_NIF_TERM cpool_join(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) { cpool_handle* handle = NULL; cpool_node_handle* node; ERL_NIF_TERM result; if (enif_get_resource(env, argv[0], cpool_RESOURCE, (void**)&handle) == 0) { return enif_make_badarg(env); } node = (cpool_node_handle*)enif_alloc_resource(cpool_node_RESOURCE, sizeof(cpool_node_handle)); node->node = handle->pool->Join(argv[1]); result = enif_make_resource(env, (void*)node); enif_release_resource((void*)node); return result; } static ERL_NIF_TERM cpool_depart(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) { ERL_NIF_TERM result; cpool_handle* handle_pool = NULL; cpool_node_handle* handle_node = NULL; if (enif_get_resource(env, argv[0], cpool_RESOURCE, (void**)&handle_pool) == 0) { return enif_make_badarg(env); } if (enif_get_resource(env, argv[1], cpool_node_RESOURCE, (void**)&handle_node) == 0) { return enif_make_badarg(env); } result = handle_pool->pool->Depart(env, handle_node->node); return result; } static ERL_NIF_TERM cpool_next(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) { ERL_NIF_TERM result; cpool_handle* handle = NULL; unsigned long iterator; if (enif_get_resource(env, argv[0], cpool_RESOURCE, (void**)&handle) == 0) { return enif_make_badarg(env); } if (enif_get_ulong(env, argv[1], &iterator) == 0) { return enif_make_badarg(env); } // Reduce iterator to account for zero indice --iterator; result = handle->pool->Next(env, iterator); return result; } static void cpool_resource_cleanup(ErlNifEnv* env, void* arg) { cpool_handle* handle = (cpool_handle*)arg; delete handle->pool; handle->pool = NULL; } static void cpool_node_resource_cleanup(ErlNifEnv* env, void* arg) { ((cpool_node_handle*)arg)->node = NULL; } static int on_load(ErlNifEnv* env, void** priv_data, ERL_NIF_TERM load_info) { ErlNifResourceFlags flags = (ErlNifResourceFlags)(ERL_NIF_RT_CREATE | ERL_NIF_RT_TAKEOVER); ErlNifResourceType* cpool = enif_open_resource_type(env, NULL, "cpool_resource", &cpool_resource_cleanup, flags, NULL); if (cpool == NULL) return -1; ErlNifResourceType* cpool_node = enif_open_resource_type(env, NULL, "cpool_node_resource", &cpool_node_resource_cleanup, flags, NULL); if (cpool_node == NULL) return -1; cpool_RESOURCE = cpool; cpool_node_RESOURCE = cpool_node; return 0; } static int on_upgrade(ErlNifEnv* env, void** old_priv_data, void** priv_data, ERL_NIF_TERM load_info) { ErlNifResourceFlags flags = (ErlNifResourceFlags)(ERL_NIF_RT_CREATE | ERL_NIF_RT_TAKEOVER); ErlNifResourceType* cpool = enif_open_resource_type(env, NULL, "cpool_resource", &cpool_resource_cleanup, flags, NULL); if (cpool == NULL) return -1; ErlNifResourceType* cpool_node = enif_open_resource_type(env, NULL, "cpool_node_resource", &cpool_node_resource_cleanup, flags, NULL); if (cpool_node == NULL) return -1; cpool_RESOURCE = cpool; cpool_node_RESOURCE = cpool_node; return 0; } ERL_NIF_INIT(cpool, nif_funcs, &on_load, NULL, &on_upgrade, NULL); } <|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // author: Javier López-Gómez <jalopezg@inf.uc3m.es> // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ #include "DefinitionShadower.h" #include "cling/Interpreter/Interpreter.h" #include "cling/Interpreter/InterpreterCallbacks.h" #include "cling/Utils/AST.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclContextInternals.h" #include "clang/AST/Stmt.h" #include "clang/Sema/Lookup.h" #include "clang/Sema/Sema.h" using namespace clang; namespace cling { /// \brief Returns whether the given source location is a Cling input line. If /// it came from the prompt, the file is a virtual file with overriden contents. static bool typedInClingPrompt(FullSourceLoc L) { if (L.isInvalid()) return false; const SourceManager &SM = L.getManager(); const FileID FID = SM.getFileID(L); return SM.isFileOverridden(SM.getFileEntryForID(FID)) && (SM.getFileID(SM.getIncludeLoc(FID)) == SM.getMainFileID()); } /// \brief Returns whether the given {Function,Tag,Var}Decl/TemplateDecl is a definition. static bool isDefinition(const Decl *D) { if (auto FD = dyn_cast<FunctionDecl>(D)) return FD->isThisDeclarationADefinition(); if (auto TD = dyn_cast<TagDecl>(D)) return TD->isThisDeclarationADefinition(); if (auto VD = dyn_cast<VarDecl>(D)) return VD->isThisDeclarationADefinition(); if (auto TD = dyn_cast<TemplateDecl>(D)) return isDefinition(TD->getTemplatedDecl()); return true; } DefinitionShadower::DefinitionShadower(Sema& S, Interpreter& I) : ASTTransformer(&S), m_Interp(I), m_Context(S.getASTContext()), m_TU(S.getASTContext().getTranslationUnitDecl()) {} bool DefinitionShadower::isClingShadowNamespace(const DeclContext *DC) { auto NS = dyn_cast<NamespaceDecl>(DC); return NS && NS->getName().startswith("__cling_N5"); } void DefinitionShadower::hideDecl(clang::NamedDecl *D) const { assert(isClingShadowNamespace(D->getDeclContext()) && "D not in a __cling_N5xxx namespace?"); // FIXME: this hides a decl from SemaLookup (there is no unloading). For // (large) L-values, this might be a memory leak. Should this be fixed? if (Scope* S = m_Sema->getScopeForContext(m_TU)) { S->RemoveDecl(D); if (utils::Analyze::isOnScopeChains(D, *m_Sema)) m_Sema->IdResolver.RemoveDecl(D); } clang::StoredDeclsList &SDL = (*m_TU->getLookupPtr())[D->getDeclName()]; if (SDL.getAsVector() || SDL.getAsDecl() == D) SDL.remove(D); if (InterpreterCallbacks *IC = m_Interp.getCallbacks()) IC->DefinitionShadowed(D); } void DefinitionShadower::invalidatePreviousDefinitions(NamedDecl *D) const { LookupResult Previous(*m_Sema, D->getDeclName(), D->getLocation(), Sema::LookupOrdinaryName, Sema::ForRedeclaration); m_Sema->LookupQualifiedName(Previous, m_TU); for (auto Prev : Previous) { if (Prev == D) continue; if (isDefinition(Prev) && (!isDefinition(D) || !isClingShadowNamespace(Prev->getDeclContext()))) continue; // If the found declaration is a function overload, do not invalidate it. // For templated functions, Sema::IsOverload() does the right thing as per // C++ [temp.over.link]p4. if (isa<FunctionDecl>(Prev) && isa<FunctionDecl>(D) && m_Sema->IsOverload(cast<FunctionDecl>(D), cast<FunctionDecl>(Prev), /*IsForUsingDecl=*/false)) continue; if (isa<FunctionTemplateDecl>(Prev) && isa<FunctionTemplateDecl>(D) && m_Sema->IsOverload(cast<FunctionTemplateDecl>(D)->getTemplatedDecl(), cast<FunctionTemplateDecl>(Prev)->getTemplatedDecl(), /*IsForUsingDecl=*/false)) continue; hideDecl(Prev); // For unscoped enumerations, also invalidate all enumerators. if (EnumDecl *ED = dyn_cast<EnumDecl>(Prev)) { if (!ED->isTransparentContext()) continue; for (auto &J : ED->decls()) if (NamedDecl *ND = dyn_cast<NamedDecl>(J)) hideDecl(ND); } } // Ignore any forward declaration issued after a definition. Fixes "error // : reference to 'xxx' is ambiguous" in `class C {}; class C; C foo;`. if (!Previous.empty() && !isDefinition(D)) D->setInvalidDecl(); } void DefinitionShadower::invalidatePreviousDefinitions(FunctionDecl *D) const { const CompilationOptions &CO = getTransaction()->getCompilationOpts(); if (utils::Analyze::IsWrapper(D)) { if (!CO.DeclarationExtraction) return; // DeclExtractor shall move local declarations to the TU. Invalidate all // previous definitions (that may clash) before it runs. auto CS = dyn_cast<CompoundStmt>(D->getBody()); for (auto &I : CS->body()) { auto DS = dyn_cast<DeclStmt>(I); if (!DS) continue; for (auto &J : DS->decls()) if (auto ND = dyn_cast<NamedDecl>(J)) invalidatePreviousDefinitions(ND); } } else invalidatePreviousDefinitions(cast<NamedDecl>(D)); } void DefinitionShadower::invalidatePreviousDefinitions(Decl *D) const { if (auto FD = dyn_cast<FunctionDecl>(D)) invalidatePreviousDefinitions(FD); else if (auto ND = dyn_cast<NamedDecl>(D)) invalidatePreviousDefinitions(ND); } ASTTransformer::Result DefinitionShadower::Transform(Decl* D) { Transaction *T = getTransaction(); const CompilationOptions &CO = T->getCompilationOpts(); // Global declarations whose origin is the Cling prompt are subject to be // nested in a `__cling_N5' namespace. if (!CO.EnableShadowing || D->getLexicalDeclContext() != m_TU || D->isInvalidDecl() || isa<UsingDirectiveDecl>(D) || isa<UsingDecl>(D) // FIXME: NamespaceDecl requires additional processing (TBD) || isa<NamespaceDecl>(D) || (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isTemplateInstantiation()) || !typedInClingPrompt(FullSourceLoc{D->getLocation(), m_Context.getSourceManager()})) return Result(D, true); // Each transaction gets at most a `__cling_N5xxx' namespace. If `T' already // has one, reuse it. auto NS = T->getDefinitionShadowNS(); if (!NS) { NS = NamespaceDecl::Create(m_Context, m_TU, /*inline=*/true, SourceLocation(), SourceLocation(), &m_Context.Idents.get("__cling_N5" + std::to_string(m_UniqueNameCounter++)), nullptr); //NS->setImplicit(); m_TU->addDecl(NS); T->setDefinitionShadowNS(NS); } m_TU->removeDecl(D); if (isa<CXXRecordDecl>(D->getDeclContext())) D->setLexicalDeclContext(NS); else D->setDeclContext(NS); // An instantiated function template inherits the declaration context of the // templated decl. This is used for name mangling; fix it to avoid clashing. if (auto FTD = dyn_cast<FunctionTemplateDecl>(D)) FTD->getTemplatedDecl()->setDeclContext(NS); NS->addDecl(D); // Invalidate previous definitions so that LookupResult::resolveKind() does not // mark resolution as ambiguous. invalidatePreviousDefinitions(D); return Result(D, true); } } // end namespace cling <commit_msg>Shadow only prompt definitions:<commit_after>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // author: Javier López-Gómez <jalopezg@inf.uc3m.es> // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ #include "DefinitionShadower.h" #include "cling/Interpreter/Interpreter.h" #include "cling/Interpreter/InterpreterCallbacks.h" #include "cling/Utils/AST.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclContextInternals.h" #include "clang/AST/Stmt.h" #include "clang/Sema/Lookup.h" #include "clang/Sema/Sema.h" using namespace clang; namespace cling { /// \brief Returns whether the given source location is a Cling input line. If /// it came from the prompt, the file is a virtual file with overriden contents. static bool typedInClingPrompt(FullSourceLoc L) { if (L.isInvalid()) return false; const SourceManager &SM = L.getManager(); const FileID FID = SM.getFileID(L); return SM.isFileOverridden(SM.getFileEntryForID(FID)) && (SM.getFileID(SM.getIncludeLoc(FID)) == SM.getMainFileID()); } /// \brief Returns whether the given {Function,Tag,Var}Decl/TemplateDecl is a definition. static bool isDefinition(const Decl *D) { if (auto FD = dyn_cast<FunctionDecl>(D)) return FD->isThisDeclarationADefinition(); if (auto TD = dyn_cast<TagDecl>(D)) return TD->isThisDeclarationADefinition(); if (auto VD = dyn_cast<VarDecl>(D)) return VD->isThisDeclarationADefinition(); if (auto TD = dyn_cast<TemplateDecl>(D)) return isDefinition(TD->getTemplatedDecl()); return true; } DefinitionShadower::DefinitionShadower(Sema& S, Interpreter& I) : ASTTransformer(&S), m_Interp(I), m_Context(S.getASTContext()), m_TU(S.getASTContext().getTranslationUnitDecl()) {} bool DefinitionShadower::isClingShadowNamespace(const DeclContext *DC) { auto NS = dyn_cast<NamespaceDecl>(DC); return NS && NS->getName().startswith("__cling_N5"); } void DefinitionShadower::hideDecl(clang::NamedDecl *D) const { assert(isClingShadowNamespace(D->getDeclContext()) && "D not in a __cling_N5xxx namespace?"); // FIXME: this hides a decl from SemaLookup (there is no unloading). For // (large) L-values, this might be a memory leak. Should this be fixed? if (Scope* S = m_Sema->getScopeForContext(m_TU)) { S->RemoveDecl(D); if (utils::Analyze::isOnScopeChains(D, *m_Sema)) m_Sema->IdResolver.RemoveDecl(D); } clang::StoredDeclsList &SDL = (*m_TU->getLookupPtr())[D->getDeclName()]; if (SDL.getAsVector() || SDL.getAsDecl() == D) SDL.remove(D); if (InterpreterCallbacks *IC = m_Interp.getCallbacks()) IC->DefinitionShadowed(D); } void DefinitionShadower::invalidatePreviousDefinitions(NamedDecl *D) const { LookupResult Previous(*m_Sema, D->getDeclName(), D->getLocation(), Sema::LookupOrdinaryName, Sema::ForRedeclaration); m_Sema->LookupQualifiedName(Previous, m_TU); for (auto Prev : Previous) { if (Prev == D) continue; if (!isClingShadowNamespace(Prev->getDeclContext())) continue; if (isDefinition(Prev) && !isDefinition(D)) continue; // If the found declaration is a function overload, do not invalidate it. // For templated functions, Sema::IsOverload() does the right thing as per // C++ [temp.over.link]p4. if (isa<FunctionDecl>(Prev) && isa<FunctionDecl>(D) && m_Sema->IsOverload(cast<FunctionDecl>(D), cast<FunctionDecl>(Prev), /*IsForUsingDecl=*/false)) continue; if (isa<FunctionTemplateDecl>(Prev) && isa<FunctionTemplateDecl>(D) && m_Sema->IsOverload(cast<FunctionTemplateDecl>(D)->getTemplatedDecl(), cast<FunctionTemplateDecl>(Prev)->getTemplatedDecl(), /*IsForUsingDecl=*/false)) continue; hideDecl(Prev); // For unscoped enumerations, also invalidate all enumerators. if (EnumDecl *ED = dyn_cast<EnumDecl>(Prev)) { if (!ED->isTransparentContext()) continue; for (auto &J : ED->decls()) if (NamedDecl *ND = dyn_cast<NamedDecl>(J)) hideDecl(ND); } } // Ignore any forward declaration issued after a definition. Fixes "error // : reference to 'xxx' is ambiguous" in `class C {}; class C; C foo;`. if (!Previous.empty() && !isDefinition(D)) D->setInvalidDecl(); } void DefinitionShadower::invalidatePreviousDefinitions(FunctionDecl *D) const { const CompilationOptions &CO = getTransaction()->getCompilationOpts(); if (utils::Analyze::IsWrapper(D)) { if (!CO.DeclarationExtraction) return; // DeclExtractor shall move local declarations to the TU. Invalidate all // previous definitions (that may clash) before it runs. auto CS = dyn_cast<CompoundStmt>(D->getBody()); for (auto &I : CS->body()) { auto DS = dyn_cast<DeclStmt>(I); if (!DS) continue; for (auto &J : DS->decls()) if (auto ND = dyn_cast<NamedDecl>(J)) invalidatePreviousDefinitions(ND); } } else invalidatePreviousDefinitions(cast<NamedDecl>(D)); } void DefinitionShadower::invalidatePreviousDefinitions(Decl *D) const { if (auto FD = dyn_cast<FunctionDecl>(D)) invalidatePreviousDefinitions(FD); else if (auto ND = dyn_cast<NamedDecl>(D)) invalidatePreviousDefinitions(ND); } ASTTransformer::Result DefinitionShadower::Transform(Decl* D) { Transaction *T = getTransaction(); const CompilationOptions &CO = T->getCompilationOpts(); // Global declarations whose origin is the Cling prompt are subject to be // nested in a `__cling_N5' namespace. if (!CO.EnableShadowing || D->getLexicalDeclContext() != m_TU || D->isInvalidDecl() || isa<UsingDirectiveDecl>(D) || isa<UsingDecl>(D) // FIXME: NamespaceDecl requires additional processing (TBD) || isa<NamespaceDecl>(D) || (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isTemplateInstantiation()) || !typedInClingPrompt(FullSourceLoc{D->getLocation(), m_Context.getSourceManager()})) return Result(D, true); // Each transaction gets at most a `__cling_N5xxx' namespace. If `T' already // has one, reuse it. auto NS = T->getDefinitionShadowNS(); if (!NS) { NS = NamespaceDecl::Create(m_Context, m_TU, /*inline=*/true, SourceLocation(), SourceLocation(), &m_Context.Idents.get("__cling_N5" + std::to_string(m_UniqueNameCounter++)), nullptr); //NS->setImplicit(); m_TU->addDecl(NS); T->setDefinitionShadowNS(NS); } m_TU->removeDecl(D); if (isa<CXXRecordDecl>(D->getDeclContext())) D->setLexicalDeclContext(NS); else D->setDeclContext(NS); // An instantiated function template inherits the declaration context of the // templated decl. This is used for name mangling; fix it to avoid clashing. if (auto FTD = dyn_cast<FunctionTemplateDecl>(D)) FTD->getTemplatedDecl()->setDeclContext(NS); NS->addDecl(D); // Invalidate previous definitions so that LookupResult::resolveKind() does not // mark resolution as ambiguous. invalidatePreviousDefinitions(D); return Result(D, true); } } // end namespace cling <|endoftext|>
<commit_before>// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "athena/content/public/web_contents_view_delegate_creator.h" #include "athena/content/render_view_context_menu_impl.h" #include "components/web_modal/popup_manager.h" #include "components/web_modal/single_web_contents_dialog_manager.h" #include "components/web_modal/web_contents_modal_dialog_host.h" #include "components/web_modal/web_contents_modal_dialog_manager.h" #include "content/public/browser/render_widget_host_view.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_contents_delegate.h" #include "content/public/browser/web_contents_view_delegate.h" #include "ui/aura/client/screen_position_client.h" #include "ui/aura/window.h" #include "ui/views/widget/widget.h" namespace athena { namespace { class WebContentsViewDelegateImpl : public content::WebContentsViewDelegate { public: explicit WebContentsViewDelegateImpl(content::WebContents* web_contents) : web_contents_(web_contents) {} ~WebContentsViewDelegateImpl() override {} content::WebDragDestDelegate* GetDragDestDelegate() override { // TODO(oshima): crbug.com/401610 NOTIMPLEMENTED(); return nullptr; } bool Focus() override { web_modal::PopupManager* popup_manager = web_modal::PopupManager::FromWebContents(web_contents_); if (popup_manager) popup_manager->WasFocused(web_contents_); return false; } void ShowContextMenu(content::RenderFrameHost* render_frame_host, const content::ContextMenuParams& params) override { ShowMenu(BuildMenu( content::WebContents::FromRenderFrameHost(render_frame_host), params)); } void SizeChanged(const gfx::Size& size) override { // TODO(oshima|sadrul): Implement this when sad_tab is componentized. // See c/b/ui/views/tab_contents/chrome_web_contents_view_delegate_views.cc } void ShowDisambiguationPopup( const gfx::Rect& target_rect, const SkBitmap& zoomed_bitmap, const gfx::NativeView content, const base::Callback<void(ui::GestureEvent*)>& gesture_cb, const base::Callback<void(ui::MouseEvent*)>& mouse_cb) override { NOTIMPLEMENTED(); } void HideDisambiguationPopup() override { NOTIMPLEMENTED(); } scoped_ptr<RenderViewContextMenuImpl> BuildMenu( content::WebContents* web_contents, const content::ContextMenuParams& params) { scoped_ptr<RenderViewContextMenuImpl> menu; content::RenderFrameHost* focused_frame = web_contents->GetFocusedFrame(); // If the frame tree does not have a focused frame at this point, do not // bother creating RenderViewContextMenuViews. // This happens if the frame has navigated to a different page before // ContextMenu message was received by the current RenderFrameHost. if (focused_frame) { menu.reset(new RenderViewContextMenuImpl(focused_frame, params)); menu->Init(); } return menu.Pass(); } void ShowMenu(scoped_ptr<RenderViewContextMenuImpl> menu) { context_menu_.reset(menu.release()); if (!context_menu_) return; context_menu_->Show(); } aura::Window* GetActiveNativeView() { return web_contents_->GetFullscreenRenderWidgetHostView() ? web_contents_->GetFullscreenRenderWidgetHostView() ->GetNativeView() : web_contents_->GetNativeView(); } views::Widget* GetTopLevelWidget() { return views::Widget::GetTopLevelWidgetForNativeView(GetActiveNativeView()); } views::FocusManager* GetFocusManager() { views::Widget* toplevel_widget = GetTopLevelWidget(); return toplevel_widget ? toplevel_widget->GetFocusManager() : nullptr; } void SetInitialFocus() { if (web_contents_->FocusLocationBarByDefault()) { if (web_contents_->GetDelegate()) web_contents_->GetDelegate()->SetFocusToLocationBar(false); } else { web_contents_->Focus(); } } scoped_ptr<RenderViewContextMenuImpl> context_menu_; content::WebContents* web_contents_; DISALLOW_COPY_AND_ASSIGN(WebContentsViewDelegateImpl); }; } // namespace content::WebContentsViewDelegate* CreateWebContentsViewDelegate( content::WebContents* web_contents) { return new WebContentsViewDelegateImpl(web_contents); } } // namespace athena <commit_msg>Fix the crash of webview new window sample on Athena.<commit_after>// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "athena/content/public/web_contents_view_delegate_creator.h" #include "athena/content/render_view_context_menu_impl.h" #include "components/renderer_context_menu/context_menu_delegate.h" #include "components/web_modal/popup_manager.h" #include "components/web_modal/single_web_contents_dialog_manager.h" #include "components/web_modal/web_contents_modal_dialog_host.h" #include "components/web_modal/web_contents_modal_dialog_manager.h" #include "content/public/browser/render_widget_host_view.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_contents_delegate.h" #include "content/public/browser/web_contents_view_delegate.h" #include "ui/aura/client/screen_position_client.h" #include "ui/aura/window.h" #include "ui/views/widget/widget.h" namespace athena { namespace { class WebContentsViewDelegateImpl : public content::WebContentsViewDelegate, public ContextMenuDelegate { public: explicit WebContentsViewDelegateImpl(content::WebContents* web_contents) : ContextMenuDelegate(web_contents), web_contents_(web_contents) {} ~WebContentsViewDelegateImpl() override {} content::WebDragDestDelegate* GetDragDestDelegate() override { // TODO(oshima): crbug.com/401610 NOTIMPLEMENTED(); return nullptr; } bool Focus() override { web_modal::PopupManager* popup_manager = web_modal::PopupManager::FromWebContents(web_contents_); if (popup_manager) popup_manager->WasFocused(web_contents_); return false; } void ShowContextMenu(content::RenderFrameHost* render_frame_host, const content::ContextMenuParams& params) override { ShowMenu(BuildMenu( content::WebContents::FromRenderFrameHost(render_frame_host), params)); } void SizeChanged(const gfx::Size& size) override { // TODO(oshima|sadrul): Implement this when sad_tab is componentized. // See c/b/ui/views/tab_contents/chrome_web_contents_view_delegate_views.cc } void ShowDisambiguationPopup( const gfx::Rect& target_rect, const SkBitmap& zoomed_bitmap, const gfx::NativeView content, const base::Callback<void(ui::GestureEvent*)>& gesture_cb, const base::Callback<void(ui::MouseEvent*)>& mouse_cb) override { NOTIMPLEMENTED(); } void HideDisambiguationPopup() override { NOTIMPLEMENTED(); } // ContextMenuDelegate: scoped_ptr<RenderViewContextMenuBase> BuildMenu( content::WebContents* web_contents, const content::ContextMenuParams& params) override { scoped_ptr<RenderViewContextMenuBase> menu; content::RenderFrameHost* focused_frame = web_contents->GetFocusedFrame(); // If the frame tree does not have a focused frame at this point, do not // bother creating RenderViewContextMenuViews. // This happens if the frame has navigated to a different page before // ContextMenu message was received by the current RenderFrameHost. if (focused_frame) { menu.reset(new RenderViewContextMenuImpl(focused_frame, params)); menu->Init(); } return menu.Pass(); } void ShowMenu(scoped_ptr<RenderViewContextMenuBase> menu) override { context_menu_.reset(menu.release()); if (!context_menu_) return; context_menu_->Show(); } aura::Window* GetActiveNativeView() { return web_contents_->GetFullscreenRenderWidgetHostView() ? web_contents_->GetFullscreenRenderWidgetHostView() ->GetNativeView() : web_contents_->GetNativeView(); } views::Widget* GetTopLevelWidget() { return views::Widget::GetTopLevelWidgetForNativeView(GetActiveNativeView()); } views::FocusManager* GetFocusManager() { views::Widget* toplevel_widget = GetTopLevelWidget(); return toplevel_widget ? toplevel_widget->GetFocusManager() : nullptr; } void SetInitialFocus() { if (web_contents_->FocusLocationBarByDefault()) { if (web_contents_->GetDelegate()) web_contents_->GetDelegate()->SetFocusToLocationBar(false); } else { web_contents_->Focus(); } } scoped_ptr<RenderViewContextMenuBase> context_menu_; content::WebContents* web_contents_; DISALLOW_COPY_AND_ASSIGN(WebContentsViewDelegateImpl); }; } // namespace content::WebContentsViewDelegate* CreateWebContentsViewDelegate( content::WebContents* web_contents) { return new WebContentsViewDelegateImpl(web_contents); } } // namespace athena <|endoftext|>
<commit_before>// Copyright 2011, Tokyo Institute of Technology. // All rights reserved. // // This file is distributed under the license described in // LICENSE.txt. // // Author: Naoya Maruyama (naoya@matsulab.is.titech.ac.jp) #include <boost/program_options.hpp> #include "translator/config.h" #include "translator/reference_translator.h" //#if defined(CUDA_ENABLED) #include "translator/cuda_translator.h" //#endif //#if defined(MPI_ENABLED) #include "translator/mpi_translator.h" //#endif //#if defined(MPI_ENABLED) && defined(CUDA_ENABLED) #include "translator/mpi_cuda_translator.h" //#endif #include "translator/translator_common.h" #include "translator/translation_context.h" #include "translator/translator.h" #include "translator/configuration.h" using std::string; namespace bpo = boost::program_options; namespace pt = physis::translator; //namespace pu = physis::util; namespace physis { namespace translator { struct CommandLineOptions { bool ref_trans; bool cuda_trans; bool mpi_trans; bool mpi_cuda_trans; std::pair<bool, string> config_file_path; CommandLineOptions(): ref_trans(false), cuda_trans(false), mpi_trans(false), mpi_cuda_trans(false), config_file_path(std::make_pair(false, "")) {} }; void parseOptions(int argc, char *argv[], CommandLineOptions &opts, vector<string> &rem) { // Declare the supported options. bpo::options_description desc("Allowed options"); desc.add_options()("help", "produce help message"); desc.add_options()("ref", "reference translation"); desc.add_options()("config", bpo::value<string>(), "read configuration file"); //#ifdef CUDA_ENABLED desc.add_options()("cuda", "CUDA translation"); //#endif //#ifdef MPI_ENABLED desc.add_options()("mpi", "MPI translation"); //#endif //#if defined(MPI_ENABLED) && defined(CUDA_ENABLED) desc.add_options()("mpi-cuda", "MPI-CUDA translation"); //#endif bpo::variables_map vm; bpo::parsed_options parsed = bpo::command_line_parser(argc, argv). options(desc).allow_unregistered().run(); vector<string> unrec_opts = bpo::collect_unrecognized (parsed.options, bpo::include_positional); FOREACH (it, unrec_opts.begin(), unrec_opts.end()) { rem.push_back(*it); } bpo::store(parsed, vm); bpo::notify(vm); if (vm.count("help")) { std::cout << desc << "\n"; exit(0); } if (vm.count("config")) { opts.config_file_path = make_pair(true, vm["config"].as<string>()); LOG_DEBUG() << "Configuration file specified: " << opts.config_file_path.second << ".\n"; } if (vm.count("ref")) { LOG_DEBUG() << "Reference translation.\n"; opts.ref_trans = true; return; } //#ifdef CUDA_ENABLED if (vm.count("cuda")) { LOG_DEBUG() << "CUDA translation.\n"; opts.cuda_trans = true; return; } //#endif //#ifdef MPI_ENABLED if (vm.count("mpi")) { LOG_DEBUG() << "MPI translation.\n"; opts.mpi_trans = true; return; } //#endif //#if defined(MPI_ENABLED) && defined(CUDA_ENABLED) if (vm.count("mpi-cuda")) { LOG_DEBUG() << "MPI-CUDA translation.\n"; opts.mpi_cuda_trans = true; return; } //#endif LOG_INFO() << "No translation target given.\n"; std::cout << desc << "\n"; exit(0); return; } string generate_output_filename(string srcname, string suffix) { return srcname.substr(0, srcname.rfind(".")) + "." + suffix; } // Set target-wise output file name void set_output_filename(SgFile *file, string suffix) { string name = generate_output_filename(file->get_sourceFileNameWithoutPath(), suffix); file->set_unparse_output_filename(name); return; } } // namespace translator } // namespace physis int main(int argc, char *argv[]) { pt::Translator *trans = NULL; string filename_suffix; string extra_arg; pt::CommandLineOptions opts; std::vector<std::string> argvec; argvec.push_back(argv[0]); pt::parseOptions(argc, argv, opts, argvec); argvec.push_back("-DPHYSIS_USER"); pt::Configuration config; if (opts.config_file_path.first) { config.LoadFile(opts.config_file_path.second); } if (opts.ref_trans) { trans = new pt::ReferenceTranslator(config); filename_suffix = "ref.c"; argvec.push_back("-DPHYSIS_REF"); } //#ifdef CUDA_ENABLED if (opts.cuda_trans) { trans = new pt::CUDATranslator(config); filename_suffix = "cuda.cu"; argvec.push_back("-DPHYSIS_CUDA"); // argvec.push_back("-I" + string(CUDA_INCLUDE_DIR)); // argvec.push_back("-I" + string(CUDA_CUT_INCLUDE_DIR)); } //#endif //#ifdef MPI_ENABLED if (opts.mpi_trans) { trans = new pt::MPITranslator(config); filename_suffix = "mpi.c"; argvec.push_back("-DPHYSIS_MPI"); //argvec.push_back("-I" + string(MPI_INCLUDE_DIR)); } //#endif //#if defined(MPI_ENABLED) && defined(CUDA_ENABLED) if (opts.mpi_cuda_trans) { trans = new pt::MPICUDATranslator(config); filename_suffix = "mpi-cuda.cu"; argvec.push_back("-DPHYSIS_MPI_CUDA"); //argvec.push_back("-I" + string(MPI_INCLUDE_DIR)); //argvec.push_back("-I" + string(CUDA_INCLUDE_DIR)); //argvec.push_back("-I" + string(CUDA_CUT_INCLUDE_DIR)); } //#endif if (trans == NULL) { LOG_INFO() << "No translation done.\n"; exit(0); } #if defined(PS_VERBOSE_DEBUG) physis::StringJoin sj; FOREACH (it, argvec.begin(), argvec.end()) { sj << *it; } LOG_DEBUG() << "Rose command line: " << sj << "\n"; #endif // Build the AST used by ROSE SgProject* proj = frontend(argvec); proj->skipfinalCompileStep(true); LOG_INFO() << "AST generation done\n"; if (proj->numberOfFiles() == 0) { LOG_INFO() << "No input source\n"; exit(0); } // Run internal consistency tests on AST // AstTests::runAllTests(proj); pt::TranslationContext tx(proj); trans->run(proj, &tx); pt::set_output_filename(proj->get_fileList()[0], filename_suffix); int b = backend(proj); LOG_INFO() << "Code generation complete.\n"; return b; } <commit_msg>list-targets option<commit_after>// Copyright 2011, Tokyo Institute of Technology. // All rights reserved. // // This file is distributed under the license described in // LICENSE.txt. // // Author: Naoya Maruyama (naoya@matsulab.is.titech.ac.jp) #include <boost/program_options.hpp> #include "translator/config.h" #include "translator/reference_translator.h" //#if defined(CUDA_ENABLED) #include "translator/cuda_translator.h" //#endif //#if defined(MPI_ENABLED) #include "translator/mpi_translator.h" //#endif //#if defined(MPI_ENABLED) && defined(CUDA_ENABLED) #include "translator/mpi_cuda_translator.h" //#endif #include "translator/translator_common.h" #include "translator/translation_context.h" #include "translator/translator.h" #include "translator/configuration.h" using std::string; namespace bpo = boost::program_options; namespace pt = physis::translator; //namespace pu = physis::util; namespace physis { namespace translator { struct CommandLineOptions { bool ref_trans; bool cuda_trans; bool mpi_trans; bool mpi_cuda_trans; std::pair<bool, string> config_file_path; CommandLineOptions(): ref_trans(false), cuda_trans(false), mpi_trans(false), mpi_cuda_trans(false), config_file_path(std::make_pair(false, "")) {} }; void parseOptions(int argc, char *argv[], CommandLineOptions &opts, vector<string> &rem) { // Declare the supported options. bpo::options_description desc("Allowed options"); desc.add_options()("help", "produce help message"); desc.add_options()("ref", "reference translation"); desc.add_options()("config", bpo::value<string>(), "read configuration file"); //#ifdef CUDA_ENABLED desc.add_options()("cuda", "CUDA translation"); //#endif //#ifdef MPI_ENABLED desc.add_options()("mpi", "MPI translation"); //#endif //#if defined(MPI_ENABLED) && defined(CUDA_ENABLED) desc.add_options()("mpi-cuda", "MPI-CUDA translation"); //#endif desc.add_options()("list-targets", "List available targets"); bpo::variables_map vm; bpo::parsed_options parsed = bpo::command_line_parser(argc, argv). options(desc).allow_unregistered().run(); vector<string> unrec_opts = bpo::collect_unrecognized (parsed.options, bpo::include_positional); FOREACH (it, unrec_opts.begin(), unrec_opts.end()) { rem.push_back(*it); } bpo::store(parsed, vm); bpo::notify(vm); if (vm.count("help")) { std::cout << desc << "\n"; exit(0); } if (vm.count("config")) { opts.config_file_path = make_pair(true, vm["config"].as<string>()); LOG_DEBUG() << "Configuration file specified: " << opts.config_file_path.second << ".\n"; } if (vm.count("ref")) { LOG_DEBUG() << "Reference translation.\n"; opts.ref_trans = true; return; } //#ifdef CUDA_ENABLED if (vm.count("cuda")) { LOG_DEBUG() << "CUDA translation.\n"; opts.cuda_trans = true; return; } //#endif //#ifdef MPI_ENABLED if (vm.count("mpi")) { LOG_DEBUG() << "MPI translation.\n"; opts.mpi_trans = true; return; } //#endif //#if defined(MPI_ENABLED) && defined(CUDA_ENABLED) if (vm.count("mpi-cuda")) { LOG_DEBUG() << "MPI-CUDA translation.\n"; opts.mpi_cuda_trans = true; return; } //#endif if (vm.count("list-targets")) { StringJoin sj(" "); sj << "ref"; sj << "mpi"; sj << "cuda"; sj << "mpi-cuda"; std::cout << sj << "\n"; exit(0); } LOG_INFO() << "No translation target given.\n"; std::cout << desc << "\n"; exit(0); return; } string generate_output_filename(string srcname, string suffix) { return srcname.substr(0, srcname.rfind(".")) + "." + suffix; } // Set target-wise output file name void set_output_filename(SgFile *file, string suffix) { string name = generate_output_filename(file->get_sourceFileNameWithoutPath(), suffix); file->set_unparse_output_filename(name); return; } } // namespace translator } // namespace physis int main(int argc, char *argv[]) { pt::Translator *trans = NULL; string filename_suffix; string extra_arg; pt::CommandLineOptions opts; std::vector<std::string> argvec; argvec.push_back(argv[0]); pt::parseOptions(argc, argv, opts, argvec); argvec.push_back("-DPHYSIS_USER"); pt::Configuration config; if (opts.config_file_path.first) { config.LoadFile(opts.config_file_path.second); } if (opts.ref_trans) { trans = new pt::ReferenceTranslator(config); filename_suffix = "ref.c"; argvec.push_back("-DPHYSIS_REF"); } //#ifdef CUDA_ENABLED if (opts.cuda_trans) { trans = new pt::CUDATranslator(config); filename_suffix = "cuda.cu"; argvec.push_back("-DPHYSIS_CUDA"); // argvec.push_back("-I" + string(CUDA_INCLUDE_DIR)); // argvec.push_back("-I" + string(CUDA_CUT_INCLUDE_DIR)); } //#endif //#ifdef MPI_ENABLED if (opts.mpi_trans) { trans = new pt::MPITranslator(config); filename_suffix = "mpi.c"; argvec.push_back("-DPHYSIS_MPI"); //argvec.push_back("-I" + string(MPI_INCLUDE_DIR)); } //#endif //#if defined(MPI_ENABLED) && defined(CUDA_ENABLED) if (opts.mpi_cuda_trans) { trans = new pt::MPICUDATranslator(config); filename_suffix = "mpi-cuda.cu"; argvec.push_back("-DPHYSIS_MPI_CUDA"); //argvec.push_back("-I" + string(MPI_INCLUDE_DIR)); //argvec.push_back("-I" + string(CUDA_INCLUDE_DIR)); //argvec.push_back("-I" + string(CUDA_CUT_INCLUDE_DIR)); } //#endif if (trans == NULL) { LOG_INFO() << "No translation done.\n"; exit(0); } #if defined(PS_VERBOSE_DEBUG) physis::StringJoin sj; FOREACH (it, argvec.begin(), argvec.end()) { sj << *it; } LOG_DEBUG() << "Rose command line: " << sj << "\n"; #endif // Build the AST used by ROSE SgProject* proj = frontend(argvec); proj->skipfinalCompileStep(true); LOG_INFO() << "AST generation done\n"; if (proj->numberOfFiles() == 0) { LOG_INFO() << "No input source\n"; exit(0); } // Run internal consistency tests on AST // AstTests::runAllTests(proj); pt::TranslationContext tx(proj); trans->run(proj, &tx); pt::set_output_filename(proj->get_fileList()[0], filename_suffix); int b = backend(proj); LOG_INFO() << "Code generation complete.\n"; return b; } <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/fullscreen.h" #include <windows.h> #include <shellapi.h> static bool IsPlatformFullScreenMode() { #if 0 return false; #else // SHQueryUserNotificationState is only available for Vista and above. QUERY_USER_NOTIFICATION_STATE state; if (FAILED(::SHQueryUserNotificationState(&state))) return false; return state == QUNS_RUNNING_D3D_FULL_SCREEN || state == QUNS_PRESENTATION_MODE; #endif } static bool IsFullScreenWindowMode() { // Get the foreground window which the user is currently working on. HWND wnd = ::GetForegroundWindow(); if (!wnd) return false; // Get the monitor where the window is located. RECT wnd_rect; if (!::GetWindowRect(wnd, &wnd_rect)) return false; HMONITOR monitor = ::MonitorFromRect(&wnd_rect, MONITOR_DEFAULTTONULL); if (!monitor) return false; MONITORINFO monitor_info = { sizeof(monitor_info) }; if (!::GetMonitorInfo(monitor, &monitor_info)) return false; // It should be the main monitor. if (!(monitor_info.dwFlags & MONITORINFOF_PRIMARY)) return false; // The window should be at least as large as the monitor. if (!::IntersectRect(&wnd_rect, &wnd_rect, &monitor_info.rcMonitor)) return false; if (!::EqualRect(&wnd_rect, &monitor_info.rcMonitor)) return false; // At last, the window style should not have WS_DLGFRAME and WS_THICKFRAME and // its extended style should not have WS_EX_WINDOWEDGE and WS_EX_TOOLWINDOW. LONG style = ::GetWindowLong(wnd, GWL_STYLE); LONG ext_style = ::GetWindowLong(wnd, GWL_EXSTYLE); return !((style & (WS_DLGFRAME | WS_THICKFRAME)) || (ext_style & (WS_EX_WINDOWEDGE | WS_EX_TOOLWINDOW))); } static bool IsFullScreenConsoleMode() { // We detect this by attaching the current process to the console of the // foreground window and then checking if it is in full screen mode. DWORD pid = 0; ::GetWindowThreadProcessId(::GetForegroundWindow(), &pid); if (!pid) return false; if (!::AttachConsole(pid)) return false; DWORD modes = 0; ::GetConsoleDisplayMode(&modes); ::FreeConsole(); return (modes & (CONSOLE_FULLSCREEN | CONSOLE_FULLSCREEN_HARDWARE)) != 0; } bool IsFullScreenMode() { return IsPlatformFullScreenMode() || IsFullScreenWindowMode() || IsFullScreenConsoleMode(); } <commit_msg>Remove the bad code.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/fullscreen.h" #include <windows.h> #include <shellapi.h> static bool IsPlatformFullScreenMode() { return false; } static bool IsFullScreenWindowMode() { // Get the foreground window which the user is currently working on. HWND wnd = ::GetForegroundWindow(); if (!wnd) return false; // Get the monitor where the window is located. RECT wnd_rect; if (!::GetWindowRect(wnd, &wnd_rect)) return false; HMONITOR monitor = ::MonitorFromRect(&wnd_rect, MONITOR_DEFAULTTONULL); if (!monitor) return false; MONITORINFO monitor_info = { sizeof(monitor_info) }; if (!::GetMonitorInfo(monitor, &monitor_info)) return false; // It should be the main monitor. if (!(monitor_info.dwFlags & MONITORINFOF_PRIMARY)) return false; // The window should be at least as large as the monitor. if (!::IntersectRect(&wnd_rect, &wnd_rect, &monitor_info.rcMonitor)) return false; if (!::EqualRect(&wnd_rect, &monitor_info.rcMonitor)) return false; // At last, the window style should not have WS_DLGFRAME and WS_THICKFRAME and // its extended style should not have WS_EX_WINDOWEDGE and WS_EX_TOOLWINDOW. LONG style = ::GetWindowLong(wnd, GWL_STYLE); LONG ext_style = ::GetWindowLong(wnd, GWL_EXSTYLE); return !((style & (WS_DLGFRAME | WS_THICKFRAME)) || (ext_style & (WS_EX_WINDOWEDGE | WS_EX_TOOLWINDOW))); } static bool IsFullScreenConsoleMode() { // We detect this by attaching the current process to the console of the // foreground window and then checking if it is in full screen mode. DWORD pid = 0; ::GetWindowThreadProcessId(::GetForegroundWindow(), &pid); if (!pid) return false; if (!::AttachConsole(pid)) return false; DWORD modes = 0; ::GetConsoleDisplayMode(&modes); ::FreeConsole(); return (modes & (CONSOLE_FULLSCREEN | CONSOLE_FULLSCREEN_HARDWARE)) != 0; } bool IsFullScreenMode() { return IsPlatformFullScreenMode() || IsFullScreenWindowMode() || IsFullScreenConsoleMode(); } <|endoftext|>
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/views/dom_view.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "views/focus/focus_manager.h" DOMView::DOMView() : initialized_(false), tab_contents_(NULL) { SetFocusable(true); } DOMView::~DOMView() { if (tab_contents_.get()) Detach(); } bool DOMView::Init(Profile* profile, SiteInstance* instance) { if (initialized_) return true; initialized_ = true; tab_contents_.reset( new TabContents(profile, instance, MSG_ROUTING_NONE, NULL)); views::NativeViewHost::Attach(tab_contents_->GetNativeView()); return true; } void DOMView::LoadURL(const GURL& url) { DCHECK(initialized_); tab_contents_->controller().LoadURL(url, GURL(), PageTransition::START_PAGE); } bool DOMView::SkipDefaultKeyEventProcessing(const views::KeyEvent& e) { // Don't move the focus to the next view when tab is pressed, we want the // key event to be propagated to the render view for doing the tab traversal // there. return views::FocusManager::IsTabTraversalKeyEvent(e); } void DOMView::Focus() { tab_contents_->Focus(); } <commit_msg>DOMView: avoid double-detaching.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/views/dom_view.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "views/focus/focus_manager.h" DOMView::DOMView() : initialized_(false), tab_contents_(NULL) { SetFocusable(true); } DOMView::~DOMView() { if (native_view()) Detach(); } bool DOMView::Init(Profile* profile, SiteInstance* instance) { if (initialized_) return true; initialized_ = true; tab_contents_.reset( new TabContents(profile, instance, MSG_ROUTING_NONE, NULL)); views::NativeViewHost::Attach(tab_contents_->GetNativeView()); return true; } void DOMView::LoadURL(const GURL& url) { DCHECK(initialized_); tab_contents_->controller().LoadURL(url, GURL(), PageTransition::START_PAGE); } bool DOMView::SkipDefaultKeyEventProcessing(const views::KeyEvent& e) { // Don't move the focus to the next view when tab is pressed, we want the // key event to be propagated to the render view for doing the tab traversal // there. return views::FocusManager::IsTabTraversalKeyEvent(e); } void DOMView::Focus() { tab_contents_->Focus(); } <|endoftext|>
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/renderer/render_thread.h" #include <algorithm> #include <vector> #include "base/command_line.h" #include "base/shared_memory.h" #include "base/stats_table.h" #include "chrome/common/app_cache/app_cache_context_impl.h" #include "chrome/common/app_cache/app_cache_dispatcher.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/render_messages.h" #include "chrome/common/notification_service.h" #include "chrome/common/url_constants.h" #include "chrome/plugin/npobject_util.h" // TODO(port) #if defined(OS_WIN) #include "chrome/plugin/plugin_channel.h" #else #include "base/scoped_handle.h" #include "chrome/plugin/plugin_channel_base.h" #include "webkit/glue/weburlrequest.h" #endif #include "chrome/renderer/devtools_agent_filter.h" #include "chrome/renderer/extensions/event_bindings.h" #include "chrome/renderer/extensions/extension_process_bindings.h" #include "chrome/renderer/extensions/renderer_extension_bindings.h" #include "chrome/renderer/external_extension.h" #include "chrome/renderer/js_only_v8_extensions.h" #include "chrome/renderer/loadtimes_extension_bindings.h" #include "chrome/renderer/net/render_dns_master.h" #include "chrome/renderer/render_process.h" #include "chrome/renderer/render_view.h" #include "chrome/renderer/renderer_webkitclient_impl.h" #include "chrome/renderer/user_script_slave.h" #include "chrome/renderer/visitedlink_slave.h" #include "webkit/api/public/WebCache.h" #include "webkit/api/public/WebKit.h" #include "webkit/api/public/WebString.h" #include "webkit/extensions/v8/gears_extension.h" #include "webkit/extensions/v8/interval_extension.h" #include "webkit/extensions/v8/playback_extension.h" #if defined(OS_WIN) #include <windows.h> #include <objbase.h> #endif using WebKit::WebCache; using WebKit::WebString; static const unsigned int kCacheStatsDelayMS = 2000 /* milliseconds */; //----------------------------------------------------------------------------- // Methods below are only called on the owner's thread: // When we run plugins in process, we actually run them on the render thread, // which means that we need to make the render thread pump UI events. RenderThread::RenderThread() : ChildThread( base::Thread::Options(RenderProcess::InProcessPlugins() ? MessageLoop::TYPE_UI : MessageLoop::TYPE_DEFAULT, kV8StackSize)), plugin_refresh_allowed_(true) { } RenderThread::RenderThread(const std::wstring& channel_name) : ChildThread( base::Thread::Options(RenderProcess::InProcessPlugins() ? MessageLoop::TYPE_UI : MessageLoop::TYPE_DEFAULT, kV8StackSize)), plugin_refresh_allowed_(true) { SetChannelName(channel_name); } RenderThread::~RenderThread() { } RenderThread* RenderThread::current() { DCHECK(!IsPluginProcess()); return static_cast<RenderThread*>(ChildThread::current()); } void RenderThread::AddFilter(IPC::ChannelProxy::MessageFilter* filter) { channel()->AddFilter(filter); } void RenderThread::RemoveFilter(IPC::ChannelProxy::MessageFilter* filter) { channel()->RemoveFilter(filter); } void RenderThread::Resolve(const char* name, size_t length) { return dns_master_->Resolve(name, length); } void RenderThread::SendHistograms() { return histogram_snapshots_->SendHistograms(); } static WebAppCacheContext* CreateAppCacheContextForRenderer() { return new AppCacheContextImpl(RenderThread::current()); } #if defined(OS_POSIX) class SuicideOnChannelErrorFilter : public IPC::ChannelProxy::MessageFilter { void OnChannelError() { // On POSIX, at least, one can install an unload handler which loops // forever and leave behind a renderer process which eats 100% CPU forever. // // This is because the terminate signals (ViewMsg_ShouldClose and the error // from the IPC channel) are routed to the main message loop but never // processed (because that message loop is stuck in V8). // // One could make the browser SIGKILL the renderers, but that leaves open a // large window where a browser failure (or a user, manually terminating // the browser because "it's stuck") will leave behind a process eating all // the CPU. // // So, we install a filter on the channel so that we can process this event // here and kill the process. _exit(0); } }; #endif void RenderThread::Init() { #if defined(OS_WIN) // If you are running plugins in this thread you need COM active but in // the normal case you don't. if (RenderProcess::InProcessPlugins()) CoInitialize(0); #endif ChildThread::Init(); notification_service_.reset(new NotificationService); cache_stats_factory_.reset( new ScopedRunnableMethodFactory<RenderThread>(this)); visited_link_slave_.reset(new VisitedLinkSlave()); user_script_slave_.reset(new UserScriptSlave()); dns_master_.reset(new RenderDnsMaster()); histogram_snapshots_.reset(new RendererHistogramSnapshots()); app_cache_dispatcher_.reset(new AppCacheDispatcher()); WebAppCacheContext::SetFactory(CreateAppCacheContextForRenderer); devtools_agent_filter_ = new DevToolsAgentFilter(); AddFilter(devtools_agent_filter_.get()); #if defined(OS_POSIX) suicide_on_channel_error_filter_ = new SuicideOnChannelErrorFilter; AddFilter(suicide_on_channel_error_filter_.get()); #endif } void RenderThread::CleanUp() { // Shutdown in reverse of the initialization order. RemoveFilter(devtools_agent_filter_.get()); devtools_agent_filter_ = NULL; WebAppCacheContext::SetFactory(NULL); app_cache_dispatcher_.reset(); histogram_snapshots_.reset(); dns_master_.reset(); user_script_slave_.reset(); visited_link_slave_.reset(); if (webkit_client_.get()) { WebKit::shutdown(); webkit_client_.reset(); } notification_service_.reset(); ChildThread::CleanUp(); // TODO(port) #if defined(OS_WIN) // Clean up plugin channels before this thread goes away. PluginChannelBase::CleanupChannels(); // Don't call COM if the renderer is in the sandbox. if (RenderProcess::InProcessPlugins()) CoUninitialize(); #endif } void RenderThread::OnUpdateVisitedLinks(base::SharedMemoryHandle table) { DCHECK(base::SharedMemory::IsHandleValid(table)) << "Bad table handle"; visited_link_slave_->Init(table); } void RenderThread::OnUpdateUserScripts( base::SharedMemoryHandle scripts) { DCHECK(base::SharedMemory::IsHandleValid(scripts)) << "Bad scripts handle"; user_script_slave_->UpdateScripts(scripts); } void RenderThread::OnSetExtensionFunctionNames( const std::vector<std::string>& names) { ExtensionProcessBindings::SetFunctionNames(names); } void RenderThread::OnControlMessageReceived(const IPC::Message& msg) { // App cache messages are handled by a delegate. if (app_cache_dispatcher_->OnMessageReceived(msg)) return; IPC_BEGIN_MESSAGE_MAP(RenderThread, msg) IPC_MESSAGE_HANDLER(ViewMsg_VisitedLink_NewTable, OnUpdateVisitedLinks) IPC_MESSAGE_HANDLER(ViewMsg_SetNextPageID, OnSetNextPageID) // TODO(port): removed from render_messages_internal.h; // is there a new non-windows message I should add here? IPC_MESSAGE_HANDLER(ViewMsg_New, OnCreateNewView) IPC_MESSAGE_HANDLER(ViewMsg_SetCacheCapacities, OnSetCacheCapacities) IPC_MESSAGE_HANDLER(ViewMsg_GetRendererHistograms, OnGetRendererHistograms) IPC_MESSAGE_HANDLER(ViewMsg_GetCacheResourceStats, OnGetCacheResourceStats) IPC_MESSAGE_HANDLER(ViewMsg_UserScripts_NewScripts, OnUpdateUserScripts) // TODO(rafaelw): create an ExtensionDispatcher that handles extension // messages seperates their handling from the RenderThread. IPC_MESSAGE_HANDLER(ViewMsg_ExtensionHandleConnect, OnExtensionHandleConnect) IPC_MESSAGE_HANDLER(ViewMsg_ExtensionHandleMessage, OnExtensionHandleMessage) IPC_MESSAGE_HANDLER(ViewMsg_ExtensionHandleEvent, OnExtensionHandleEvent) IPC_MESSAGE_HANDLER(ViewMsg_Extension_SetFunctionNames, OnSetExtensionFunctionNames) IPC_MESSAGE_HANDLER(ViewMsg_PurgePluginListCache, OnPurgePluginListCache) IPC_END_MESSAGE_MAP() } void RenderThread::OnSetNextPageID(int32 next_page_id) { // This should only be called at process initialization time, so we shouldn't // have to worry about thread-safety. RenderView::SetNextPageID(next_page_id); } void RenderThread::OnCreateNewView(gfx::NativeViewId parent_hwnd, ModalDialogEvent modal_dialog_event, const WebPreferences& webkit_prefs, int32 view_id) { EnsureWebKitInitialized(); // When bringing in render_view, also bring in webkit's glue and jsbindings. base::WaitableEvent* waitable_event = new base::WaitableEvent( #if defined(OS_WIN) modal_dialog_event.event); #else true, false); #endif // TODO(darin): once we have a RenderThread per RenderView, this will need to // change to assert that we are not creating more than one view. RenderView::Create( this, parent_hwnd, waitable_event, MSG_ROUTING_NONE, webkit_prefs, new SharedRenderViewCounter(0), view_id); } void RenderThread::OnSetCacheCapacities(size_t min_dead_capacity, size_t max_dead_capacity, size_t capacity) { EnsureWebKitInitialized(); WebCache::setCapacities( min_dead_capacity, max_dead_capacity, capacity); } void RenderThread::OnGetCacheResourceStats() { EnsureWebKitInitialized(); WebCache::ResourceTypeStats stats; WebCache::getResourceTypeStats(&stats); Send(new ViewHostMsg_ResourceTypeStats(stats)); } void RenderThread::OnGetRendererHistograms() { SendHistograms(); } void RenderThread::InformHostOfCacheStats() { EnsureWebKitInitialized(); WebCache::UsageStats stats; WebCache::getUsageStats(&stats); Send(new ViewHostMsg_UpdatedCacheStats(stats)); } void RenderThread::InformHostOfCacheStatsLater() { // Rate limit informing the host of our cache stats. if (!cache_stats_factory_->empty()) return; MessageLoop::current()->PostDelayedTask(FROM_HERE, cache_stats_factory_->NewRunnableMethod( &RenderThread::InformHostOfCacheStats), kCacheStatsDelayMS); } static void* CreateHistogram( const char *name, int min, int max, size_t buckets) { return new Histogram(name, min, max, buckets); } static void AddHistogramSample(void* hist, int sample) { Histogram* histogram = static_cast<Histogram *>(hist); histogram->Add(sample); } void RenderThread::EnsureWebKitInitialized() { if (webkit_client_.get()) return; v8::V8::SetCounterFunction(StatsTable::FindLocation); v8::V8::SetCreateHistogramFunction(CreateHistogram); v8::V8::SetAddHistogramSampleFunction(AddHistogramSample); webkit_client_.reset(new RendererWebKitClientImpl); WebKit::initialize(webkit_client_.get()); // chrome: pages should not be accessible by normal content, and should // also be unable to script anything but themselves (to help limit the damage // that a corrupt chrome: page could cause). WebString chrome_ui_scheme(ASCIIToUTF16(chrome::kChromeUIScheme)); WebKit::registerURLSchemeAsLocal(chrome_ui_scheme); WebKit::registerURLSchemeAsNoAccess(chrome_ui_scheme); WebKit::registerExtension(extensions_v8::GearsExtension::Get()); WebKit::registerExtension(extensions_v8::IntervalExtension::Get()); WebKit::registerExtension(extensions_v8::LoadTimesExtension::Get()); WebKit::registerExtension(extensions_v8::ExternalExtension::Get()); WebKit::registerExtension(ExtensionProcessBindings::Get(), WebKit::WebString::fromUTF8(chrome::kExtensionScheme)); const CommandLine& command_line = *CommandLine::ForCurrentProcess(); // TODO(aa): Add a way to restrict extensions to the content script context // only so that we don't have to gate these on --enable-extensions. if (command_line.HasSwitch(switches::kEnableExtensions)) { WebKit::registerExtension(BaseJsV8Extension::Get()); WebKit::registerExtension(JsonJsV8Extension::Get()); WebKit::registerExtension(JsonSchemaJsV8Extension::Get()); WebKit::registerExtension(EventBindings::Get()); WebKit::registerExtension(RendererExtensionBindings::Get()); } if (command_line.HasSwitch(switches::kPlaybackMode) || command_line.HasSwitch(switches::kRecordMode) || command_line.HasSwitch(switches::kNoJsRandomness)) { WebKit::registerExtension(extensions_v8::PlaybackExtension::Get()); } if (command_line.HasSwitch(switches::kEnableWebWorkers)) WebKit::enableWebWorkers(); if (RenderProcess::current()->initialized_media_library()) WebKit::enableMediaPlayer(); } void RenderThread::OnExtensionHandleConnect(int port_id, const std::string& tab_json) { RendererExtensionBindings::HandleConnect(port_id, tab_json); } void RenderThread::OnExtensionHandleMessage(const std::string& message, int port_id) { RendererExtensionBindings::HandleMessage(message, port_id); } void RenderThread::OnExtensionHandleEvent(const std::string event_name, const std::string event_data) { RendererExtensionBindings::HandleEvent(event_name, event_data); } void RenderThread::OnPurgePluginListCache() { // The call below will cause a GetPlugins call with refresh=true, but at this // point we already know that the browser has refreshed its list, so disable // refresh temporarily to prevent each renderer process causing the list to be // regenerated. plugin_refresh_allowed_ = false; WebKit::resetPluginCache(); plugin_refresh_allowed_ = true; } <commit_msg>Send the V8 histograms to UMA<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/renderer/render_thread.h" #include <algorithm> #include <vector> #include "base/command_line.h" #include "base/shared_memory.h" #include "base/stats_table.h" #include "chrome/common/app_cache/app_cache_context_impl.h" #include "chrome/common/app_cache/app_cache_dispatcher.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/render_messages.h" #include "chrome/common/notification_service.h" #include "chrome/common/url_constants.h" #include "chrome/plugin/npobject_util.h" // TODO(port) #if defined(OS_WIN) #include "chrome/plugin/plugin_channel.h" #else #include "base/scoped_handle.h" #include "chrome/plugin/plugin_channel_base.h" #include "webkit/glue/weburlrequest.h" #endif #include "chrome/renderer/devtools_agent_filter.h" #include "chrome/renderer/extensions/event_bindings.h" #include "chrome/renderer/extensions/extension_process_bindings.h" #include "chrome/renderer/extensions/renderer_extension_bindings.h" #include "chrome/renderer/external_extension.h" #include "chrome/renderer/js_only_v8_extensions.h" #include "chrome/renderer/loadtimes_extension_bindings.h" #include "chrome/renderer/net/render_dns_master.h" #include "chrome/renderer/render_process.h" #include "chrome/renderer/render_view.h" #include "chrome/renderer/renderer_webkitclient_impl.h" #include "chrome/renderer/user_script_slave.h" #include "chrome/renderer/visitedlink_slave.h" #include "webkit/api/public/WebCache.h" #include "webkit/api/public/WebKit.h" #include "webkit/api/public/WebString.h" #include "webkit/extensions/v8/gears_extension.h" #include "webkit/extensions/v8/interval_extension.h" #include "webkit/extensions/v8/playback_extension.h" #if defined(OS_WIN) #include <windows.h> #include <objbase.h> #endif using WebKit::WebCache; using WebKit::WebString; static const unsigned int kCacheStatsDelayMS = 2000 /* milliseconds */; //----------------------------------------------------------------------------- // Methods below are only called on the owner's thread: // When we run plugins in process, we actually run them on the render thread, // which means that we need to make the render thread pump UI events. RenderThread::RenderThread() : ChildThread( base::Thread::Options(RenderProcess::InProcessPlugins() ? MessageLoop::TYPE_UI : MessageLoop::TYPE_DEFAULT, kV8StackSize)), plugin_refresh_allowed_(true) { } RenderThread::RenderThread(const std::wstring& channel_name) : ChildThread( base::Thread::Options(RenderProcess::InProcessPlugins() ? MessageLoop::TYPE_UI : MessageLoop::TYPE_DEFAULT, kV8StackSize)), plugin_refresh_allowed_(true) { SetChannelName(channel_name); } RenderThread::~RenderThread() { } RenderThread* RenderThread::current() { DCHECK(!IsPluginProcess()); return static_cast<RenderThread*>(ChildThread::current()); } void RenderThread::AddFilter(IPC::ChannelProxy::MessageFilter* filter) { channel()->AddFilter(filter); } void RenderThread::RemoveFilter(IPC::ChannelProxy::MessageFilter* filter) { channel()->RemoveFilter(filter); } void RenderThread::Resolve(const char* name, size_t length) { return dns_master_->Resolve(name, length); } void RenderThread::SendHistograms() { return histogram_snapshots_->SendHistograms(); } static WebAppCacheContext* CreateAppCacheContextForRenderer() { return new AppCacheContextImpl(RenderThread::current()); } #if defined(OS_POSIX) class SuicideOnChannelErrorFilter : public IPC::ChannelProxy::MessageFilter { void OnChannelError() { // On POSIX, at least, one can install an unload handler which loops // forever and leave behind a renderer process which eats 100% CPU forever. // // This is because the terminate signals (ViewMsg_ShouldClose and the error // from the IPC channel) are routed to the main message loop but never // processed (because that message loop is stuck in V8). // // One could make the browser SIGKILL the renderers, but that leaves open a // large window where a browser failure (or a user, manually terminating // the browser because "it's stuck") will leave behind a process eating all // the CPU. // // So, we install a filter on the channel so that we can process this event // here and kill the process. _exit(0); } }; #endif void RenderThread::Init() { #if defined(OS_WIN) // If you are running plugins in this thread you need COM active but in // the normal case you don't. if (RenderProcess::InProcessPlugins()) CoInitialize(0); #endif ChildThread::Init(); notification_service_.reset(new NotificationService); cache_stats_factory_.reset( new ScopedRunnableMethodFactory<RenderThread>(this)); visited_link_slave_.reset(new VisitedLinkSlave()); user_script_slave_.reset(new UserScriptSlave()); dns_master_.reset(new RenderDnsMaster()); histogram_snapshots_.reset(new RendererHistogramSnapshots()); app_cache_dispatcher_.reset(new AppCacheDispatcher()); WebAppCacheContext::SetFactory(CreateAppCacheContextForRenderer); devtools_agent_filter_ = new DevToolsAgentFilter(); AddFilter(devtools_agent_filter_.get()); #if defined(OS_POSIX) suicide_on_channel_error_filter_ = new SuicideOnChannelErrorFilter; AddFilter(suicide_on_channel_error_filter_.get()); #endif } void RenderThread::CleanUp() { // Shutdown in reverse of the initialization order. RemoveFilter(devtools_agent_filter_.get()); devtools_agent_filter_ = NULL; WebAppCacheContext::SetFactory(NULL); app_cache_dispatcher_.reset(); histogram_snapshots_.reset(); dns_master_.reset(); user_script_slave_.reset(); visited_link_slave_.reset(); if (webkit_client_.get()) { WebKit::shutdown(); webkit_client_.reset(); } notification_service_.reset(); ChildThread::CleanUp(); // TODO(port) #if defined(OS_WIN) // Clean up plugin channels before this thread goes away. PluginChannelBase::CleanupChannels(); // Don't call COM if the renderer is in the sandbox. if (RenderProcess::InProcessPlugins()) CoUninitialize(); #endif } void RenderThread::OnUpdateVisitedLinks(base::SharedMemoryHandle table) { DCHECK(base::SharedMemory::IsHandleValid(table)) << "Bad table handle"; visited_link_slave_->Init(table); } void RenderThread::OnUpdateUserScripts( base::SharedMemoryHandle scripts) { DCHECK(base::SharedMemory::IsHandleValid(scripts)) << "Bad scripts handle"; user_script_slave_->UpdateScripts(scripts); } void RenderThread::OnSetExtensionFunctionNames( const std::vector<std::string>& names) { ExtensionProcessBindings::SetFunctionNames(names); } void RenderThread::OnControlMessageReceived(const IPC::Message& msg) { // App cache messages are handled by a delegate. if (app_cache_dispatcher_->OnMessageReceived(msg)) return; IPC_BEGIN_MESSAGE_MAP(RenderThread, msg) IPC_MESSAGE_HANDLER(ViewMsg_VisitedLink_NewTable, OnUpdateVisitedLinks) IPC_MESSAGE_HANDLER(ViewMsg_SetNextPageID, OnSetNextPageID) // TODO(port): removed from render_messages_internal.h; // is there a new non-windows message I should add here? IPC_MESSAGE_HANDLER(ViewMsg_New, OnCreateNewView) IPC_MESSAGE_HANDLER(ViewMsg_SetCacheCapacities, OnSetCacheCapacities) IPC_MESSAGE_HANDLER(ViewMsg_GetRendererHistograms, OnGetRendererHistograms) IPC_MESSAGE_HANDLER(ViewMsg_GetCacheResourceStats, OnGetCacheResourceStats) IPC_MESSAGE_HANDLER(ViewMsg_UserScripts_NewScripts, OnUpdateUserScripts) // TODO(rafaelw): create an ExtensionDispatcher that handles extension // messages seperates their handling from the RenderThread. IPC_MESSAGE_HANDLER(ViewMsg_ExtensionHandleConnect, OnExtensionHandleConnect) IPC_MESSAGE_HANDLER(ViewMsg_ExtensionHandleMessage, OnExtensionHandleMessage) IPC_MESSAGE_HANDLER(ViewMsg_ExtensionHandleEvent, OnExtensionHandleEvent) IPC_MESSAGE_HANDLER(ViewMsg_Extension_SetFunctionNames, OnSetExtensionFunctionNames) IPC_MESSAGE_HANDLER(ViewMsg_PurgePluginListCache, OnPurgePluginListCache) IPC_END_MESSAGE_MAP() } void RenderThread::OnSetNextPageID(int32 next_page_id) { // This should only be called at process initialization time, so we shouldn't // have to worry about thread-safety. RenderView::SetNextPageID(next_page_id); } void RenderThread::OnCreateNewView(gfx::NativeViewId parent_hwnd, ModalDialogEvent modal_dialog_event, const WebPreferences& webkit_prefs, int32 view_id) { EnsureWebKitInitialized(); // When bringing in render_view, also bring in webkit's glue and jsbindings. base::WaitableEvent* waitable_event = new base::WaitableEvent( #if defined(OS_WIN) modal_dialog_event.event); #else true, false); #endif // TODO(darin): once we have a RenderThread per RenderView, this will need to // change to assert that we are not creating more than one view. RenderView::Create( this, parent_hwnd, waitable_event, MSG_ROUTING_NONE, webkit_prefs, new SharedRenderViewCounter(0), view_id); } void RenderThread::OnSetCacheCapacities(size_t min_dead_capacity, size_t max_dead_capacity, size_t capacity) { EnsureWebKitInitialized(); WebCache::setCapacities( min_dead_capacity, max_dead_capacity, capacity); } void RenderThread::OnGetCacheResourceStats() { EnsureWebKitInitialized(); WebCache::ResourceTypeStats stats; WebCache::getResourceTypeStats(&stats); Send(new ViewHostMsg_ResourceTypeStats(stats)); } void RenderThread::OnGetRendererHistograms() { SendHistograms(); } void RenderThread::InformHostOfCacheStats() { EnsureWebKitInitialized(); WebCache::UsageStats stats; WebCache::getUsageStats(&stats); Send(new ViewHostMsg_UpdatedCacheStats(stats)); } void RenderThread::InformHostOfCacheStatsLater() { // Rate limit informing the host of our cache stats. if (!cache_stats_factory_->empty()) return; MessageLoop::current()->PostDelayedTask(FROM_HERE, cache_stats_factory_->NewRunnableMethod( &RenderThread::InformHostOfCacheStats), kCacheStatsDelayMS); } static void* CreateHistogram( const char *name, int min, int max, size_t buckets) { Histogram* histogram = new Histogram(name, min, max, buckets); if (histogram) { histogram->SetFlags(kUmaTargetedHistogramFlag); } return histogram; } static void AddHistogramSample(void* hist, int sample) { Histogram* histogram = static_cast<Histogram *>(hist); histogram->Add(sample); } void RenderThread::EnsureWebKitInitialized() { if (webkit_client_.get()) return; v8::V8::SetCounterFunction(StatsTable::FindLocation); v8::V8::SetCreateHistogramFunction(CreateHistogram); v8::V8::SetAddHistogramSampleFunction(AddHistogramSample); webkit_client_.reset(new RendererWebKitClientImpl); WebKit::initialize(webkit_client_.get()); // chrome: pages should not be accessible by normal content, and should // also be unable to script anything but themselves (to help limit the damage // that a corrupt chrome: page could cause). WebString chrome_ui_scheme(ASCIIToUTF16(chrome::kChromeUIScheme)); WebKit::registerURLSchemeAsLocal(chrome_ui_scheme); WebKit::registerURLSchemeAsNoAccess(chrome_ui_scheme); WebKit::registerExtension(extensions_v8::GearsExtension::Get()); WebKit::registerExtension(extensions_v8::IntervalExtension::Get()); WebKit::registerExtension(extensions_v8::LoadTimesExtension::Get()); WebKit::registerExtension(extensions_v8::ExternalExtension::Get()); WebKit::registerExtension(ExtensionProcessBindings::Get(), WebKit::WebString::fromUTF8(chrome::kExtensionScheme)); const CommandLine& command_line = *CommandLine::ForCurrentProcess(); // TODO(aa): Add a way to restrict extensions to the content script context // only so that we don't have to gate these on --enable-extensions. if (command_line.HasSwitch(switches::kEnableExtensions)) { WebKit::registerExtension(BaseJsV8Extension::Get()); WebKit::registerExtension(JsonJsV8Extension::Get()); WebKit::registerExtension(JsonSchemaJsV8Extension::Get()); WebKit::registerExtension(EventBindings::Get()); WebKit::registerExtension(RendererExtensionBindings::Get()); } if (command_line.HasSwitch(switches::kPlaybackMode) || command_line.HasSwitch(switches::kRecordMode) || command_line.HasSwitch(switches::kNoJsRandomness)) { WebKit::registerExtension(extensions_v8::PlaybackExtension::Get()); } if (command_line.HasSwitch(switches::kEnableWebWorkers)) WebKit::enableWebWorkers(); if (RenderProcess::current()->initialized_media_library()) WebKit::enableMediaPlayer(); } void RenderThread::OnExtensionHandleConnect(int port_id, const std::string& tab_json) { RendererExtensionBindings::HandleConnect(port_id, tab_json); } void RenderThread::OnExtensionHandleMessage(const std::string& message, int port_id) { RendererExtensionBindings::HandleMessage(message, port_id); } void RenderThread::OnExtensionHandleEvent(const std::string event_name, const std::string event_data) { RendererExtensionBindings::HandleEvent(event_name, event_data); } void RenderThread::OnPurgePluginListCache() { // The call below will cause a GetPlugins call with refresh=true, but at this // point we already know that the browser has refreshed its list, so disable // refresh temporarily to prevent each renderer process causing the list to be // regenerated. plugin_refresh_allowed_ = false; WebKit::resetPluginCache(); plugin_refresh_allowed_ = true; } <|endoftext|>
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "app/l10n_util.h" #include "app/resource_bundle.h" #include "base/command_line.h" #include "base/field_trial.h" #include "base/histogram.h" #include "base/message_loop.h" #include "base/path_service.h" #include "base/platform_thread.h" #include "base/process_util.h" #include "base/scoped_nsautorelease_pool.h" #include "base/stats_counters.h" #include "base/string_util.h" #include "base/system_monitor.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_counters.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/logging_chrome.h" #include "chrome/common/main_function_params.h" #include "chrome/renderer/renderer_main_platform_delegate.h" #include "chrome/renderer/render_process.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #if defined(OS_LINUX) #include "chrome/app/breakpad_linux.h" #endif // This function provides some ways to test crash and assertion handling // behavior of the renderer. static void HandleRendererErrorTestParameters(const CommandLine& command_line) { // This parameter causes an assertion. if (command_line.HasSwitch(switches::kRendererAssertTest)) { DCHECK(false); } // This parameter causes a null pointer crash (crash reporter trigger). if (command_line.HasSwitch(switches::kRendererCrashTest)) { int* bad_pointer = NULL; *bad_pointer = 0; } if (command_line.HasSwitch(switches::kRendererStartupDialog)) { #if defined(OS_WIN) std::wstring title = l10n_util::GetString(IDS_PRODUCT_NAME); std::wstring message = L"renderer starting with pid: "; message += IntToWString(base::GetCurrentProcId()); title += L" renderer"; // makes attaching to process easier ::MessageBox(NULL, message.c_str(), title.c_str(), MB_OK | MB_SETFOREGROUND); #elif defined(OS_MACOSX) // TODO(playmobil): In the long term, overriding this flag doesn't seem // right, either use our own flag or open a dialog we can use. // This is just to ease debugging in the interim. LOG(WARNING) << "Renderer (" << getpid() << ") paused waiting for debugger to attach @ pid"; pause(); #endif // defined(OS_MACOSX) } } // mainline routine for running as the Renderer process int RendererMain(const MainFunctionParams& parameters) { const CommandLine& parsed_command_line = parameters.command_line_; base::ScopedNSAutoreleasePool* pool = parameters.autorelease_pool_; #if defined(OS_LINUX) // Needs to be called after we have chrome::DIR_USER_DATA. InitCrashReporter(); #endif // This function allows pausing execution using the --renderer-startup-dialog // flag allowing us to attach a debugger. // Do not move this function down since that would mean we can't easily debug // whatever occurs before it. HandleRendererErrorTestParameters(parsed_command_line); RendererMainPlatformDelegate platform(parameters); StatsScope<StatsCounterTimer> startup_timer(chrome::Counters::renderer_main()); // The main thread of the renderer services IO. MessageLoopForIO main_message_loop; std::wstring app_name = chrome::kBrowserAppName; PlatformThread::SetName(WideToASCII(app_name + L"_RendererMain").c_str()); // Initialize the SystemMonitor base::SystemMonitor::Start(); platform.PlatformInitialize(); bool no_sandbox = parsed_command_line.HasSwitch(switches::kNoSandbox); platform.InitSandboxTests(no_sandbox); // Initialize histogram statistics gathering system. // Don't create StatisticsRecorder in the single process mode. scoped_ptr<StatisticsRecorder> statistics; if (!StatisticsRecorder::WasStarted()) { statistics.reset(new StatisticsRecorder()); } // Initialize statistical testing infrastructure. FieldTrialList field_trial; // Ensure any field trials in browser are reflected into renderer. if (parsed_command_line.HasSwitch(switches::kForceFieldTestNameAndValue)) { std::string persistent(WideToASCII(parsed_command_line.GetSwitchValue( switches::kForceFieldTestNameAndValue))); bool ret = field_trial.StringAugmentsState(persistent); DCHECK(ret); } { RenderProcess render_process; bool run_loop = true; if (!no_sandbox) { run_loop = platform.EnableSandbox(); } platform.RunSandboxTests(); startup_timer.Stop(); // End of Startup Time Measurement. if (run_loop) { // Load the accelerator table from the browser executable and tell the // message loop to use it when translating messages. if (pool) pool->Recycle(); MessageLoop::current()->Run(); } } platform.PlatformUninitialize(); return 0; } <commit_msg>Linux: make --renderer-startup-dialog work on Linux.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "app/l10n_util.h" #include "app/resource_bundle.h" #include "base/command_line.h" #include "base/field_trial.h" #include "base/histogram.h" #include "base/message_loop.h" #include "base/path_service.h" #include "base/platform_thread.h" #include "base/process_util.h" #include "base/scoped_nsautorelease_pool.h" #include "base/stats_counters.h" #include "base/string_util.h" #include "base/system_monitor.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_counters.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/logging_chrome.h" #include "chrome/common/main_function_params.h" #include "chrome/renderer/renderer_main_platform_delegate.h" #include "chrome/renderer/render_process.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #if defined(OS_LINUX) #include "chrome/app/breakpad_linux.h" #endif #if defined(OS_POSIX) #include <signal.h> static void SigUSR1Handler(int signal) { } #endif // This function provides some ways to test crash and assertion handling // behavior of the renderer. static void HandleRendererErrorTestParameters(const CommandLine& command_line) { // This parameter causes an assertion. if (command_line.HasSwitch(switches::kRendererAssertTest)) { DCHECK(false); } // This parameter causes a null pointer crash (crash reporter trigger). if (command_line.HasSwitch(switches::kRendererCrashTest)) { int* bad_pointer = NULL; *bad_pointer = 0; } if (command_line.HasSwitch(switches::kRendererStartupDialog)) { #if defined(OS_WIN) std::wstring title = l10n_util::GetString(IDS_PRODUCT_NAME); std::wstring message = L"renderer starting with pid: "; message += IntToWString(base::GetCurrentProcId()); title += L" renderer"; // makes attaching to process easier ::MessageBox(NULL, message.c_str(), title.c_str(), MB_OK | MB_SETFOREGROUND); #elif defined(OS_POSIX) // TODO(playmobil): In the long term, overriding this flag doesn't seem // right, either use our own flag or open a dialog we can use. // This is just to ease debugging in the interim. LOG(WARNING) << "Renderer (" << getpid() << ") paused waiting for debugger to attach @ pid"; // Install a signal handler so that pause can be woken. struct sigaction sa; memset(&sa, 0, sizeof(sa)); sa.sa_handler = SigUSR1Handler; sigaction(SIGUSR1, &sa, NULL); pause(); #endif // defined(OS_POSIX) } } // mainline routine for running as the Renderer process int RendererMain(const MainFunctionParams& parameters) { const CommandLine& parsed_command_line = parameters.command_line_; base::ScopedNSAutoreleasePool* pool = parameters.autorelease_pool_; #if defined(OS_LINUX) // Needs to be called after we have chrome::DIR_USER_DATA. InitCrashReporter(); #endif // This function allows pausing execution using the --renderer-startup-dialog // flag allowing us to attach a debugger. // Do not move this function down since that would mean we can't easily debug // whatever occurs before it. HandleRendererErrorTestParameters(parsed_command_line); RendererMainPlatformDelegate platform(parameters); StatsScope<StatsCounterTimer> startup_timer(chrome::Counters::renderer_main()); // The main thread of the renderer services IO. MessageLoopForIO main_message_loop; std::wstring app_name = chrome::kBrowserAppName; PlatformThread::SetName(WideToASCII(app_name + L"_RendererMain").c_str()); // Initialize the SystemMonitor base::SystemMonitor::Start(); platform.PlatformInitialize(); bool no_sandbox = parsed_command_line.HasSwitch(switches::kNoSandbox); platform.InitSandboxTests(no_sandbox); // Initialize histogram statistics gathering system. // Don't create StatisticsRecorder in the single process mode. scoped_ptr<StatisticsRecorder> statistics; if (!StatisticsRecorder::WasStarted()) { statistics.reset(new StatisticsRecorder()); } // Initialize statistical testing infrastructure. FieldTrialList field_trial; // Ensure any field trials in browser are reflected into renderer. if (parsed_command_line.HasSwitch(switches::kForceFieldTestNameAndValue)) { std::string persistent(WideToASCII(parsed_command_line.GetSwitchValue( switches::kForceFieldTestNameAndValue))); bool ret = field_trial.StringAugmentsState(persistent); DCHECK(ret); } { RenderProcess render_process; bool run_loop = true; if (!no_sandbox) { run_loop = platform.EnableSandbox(); } platform.RunSandboxTests(); startup_timer.Stop(); // End of Startup Time Measurement. if (run_loop) { // Load the accelerator table from the browser executable and tell the // message loop to use it when translating messages. if (pool) pool->Recycle(); MessageLoop::current()->Run(); } } platform.PlatformUninitialize(); return 0; } <|endoftext|>
<commit_before>// Time: O(n + k) // Space: O(k) // Wiki of KMP algorithm: //http://en.wikipedia.org/wiki/Knuth-Morris-Pratt_algorithm class Solution { public: /** * Returns a index to the first occurrence of target in source, * or -1 if target is not part of source. * @param source string to be scanned. * @param target string containing the sequence of characters to match. */ int strStr(const char *source, const char *target) { if (source != nullptr && target != nullptr) { const string src(source), tgt(target); if (tgt.empty()) { return 0; } return KMP(src, tgt); } return -1; } int KMP(const string& text, const string& pattern) { const vector<int> prefix = getPrefix(pattern); int j = -1; for (int i = 0; i < text.length(); ++i) { while (j > -1 && pattern[j + 1] != text[i]) { j = prefix[j]; } if (pattern[j + 1] == text[i]) { ++j; } if (j == pattern.length() - 1) { return i - j; } } return -1; } vector<int> getPrefix(const string& pattern) { vector<int> prefix(pattern.length(), -1); int j = -1; for (int i = 1; i < pattern.length(); ++i) { while (j > -1 && pattern[j + 1] != pattern[i]) { j = prefix[j]; } if (pattern[j + 1] == pattern[i]) { ++j; } prefix[i] = j; } return prefix; } }; // Time: O(n * k) // Space: O(k) class Solution2 { public: /** * Returns a index to the first occurrence of target in source, * or -1 if target is not part of source. * @param source string to be scanned. * @param target string containing the sequence of characters to match. */ int strStr(const char *source, const char *target) { if (source != nullptr && target != nullptr) { const string src(source), tgt(target); for (int i = 0; i < src.length() - tgt.length() + 1; ++i) { if (src.substr(i, tgt.length()) == tgt) { return i; } } } return -1; } }; <commit_msg>Update strstr.cpp<commit_after>// Time: O(n + k) // Space: O(k) // Wiki of KMP algorithm: // http://en.wikipedia.org/wiki/Knuth-Morris-Pratt_algorithm class Solution { public: /** * Returns a index to the first occurrence of target in source, * or -1 if target is not part of source. * @param source string to be scanned. * @param target string containing the sequence of characters to match. */ int strStr(const char *source, const char *target) { if (source != nullptr && target != nullptr) { const string src(source), tgt(target); if (tgt.empty()) { return 0; } return KMP(src, tgt); } return -1; } int KMP(const string& text, const string& pattern) { const vector<int> prefix = getPrefix(pattern); int j = -1; for (int i = 0; i < text.length(); ++i) { while (j > -1 && pattern[j + 1] != text[i]) { j = prefix[j]; } if (pattern[j + 1] == text[i]) { ++j; } if (j == pattern.length() - 1) { return i - j; } } return -1; } vector<int> getPrefix(const string& pattern) { vector<int> prefix(pattern.length(), -1); int j = -1; for (int i = 1; i < pattern.length(); ++i) { while (j > -1 && pattern[j + 1] != pattern[i]) { j = prefix[j]; } if (pattern[j + 1] == pattern[i]) { ++j; } prefix[i] = j; } return prefix; } }; // Time: O(n * k) // Space: O(k) class Solution2 { public: /** * Returns a index to the first occurrence of target in source, * or -1 if target is not part of source. * @param source string to be scanned. * @param target string containing the sequence of characters to match. */ int strStr(const char *source, const char *target) { if (source != nullptr && target != nullptr) { const string src(source), tgt(target); for (int i = 0; i < src.length() - tgt.length() + 1; ++i) { if (src.substr(i, tgt.length()) == tgt) { return i; } } } return -1; } }; <|endoftext|>
<commit_before>#include "config_file.h" #ifdef Q_OS_UNIX #include <qfile.h> #include <qtextstream.h> #include <qdir.h> #define general_section "general" #else #include <qsettings.h> #define winwget_register "winwget" #endif // ------------------------------------------------------- // -------- WGConfigFile // ------------------------------------------------------- #ifdef Q_OS_UNIX WGConfigFile::WGConfigFile(): save_config( false ) #else WGConfigFile::WGConfigFile() #endif { #ifdef Q_OS_UNIX config.clear(); open(); #endif } WGConfigFile::~WGConfigFile() { #ifdef Q_OS_UNIX save(); config.clear(); #endif } #ifdef Q_OS_UNIX // begin for Q_OS_UNIX systems void WGConfigFile::open() { QDir dir( QDir::homeDirPath() ); if ( dir.exists() ) { QFile file( dir.filePath(".winwget") ); if ( file.open(IO_ReadOnly) ) { QTextStream stream( &file ); config.clear(); QString section; section.sprintf( "[%s]", general_section ); QString s; while ( !stream.atEnd() ) { s = stream.readLine().stripWhiteSpace(); if ( s.find( '[' ) == 0 ) { int pos = s.find( ']' ); if ( pos != -1 ) { section = s.left( pos + 1 ); } } else { if ( !s.isEmpty() ) config.push_back( section + s ); } } file.close(); config.sort(); } } } void WGConfigFile::save() { if ( save_config ) { QDir dir( QDir::homeDirPath() ); if ( dir.exists() ) { QFile file( dir.filePath(".winwget") ); if ( file.open(IO_WriteOnly) ) { QTextStream stream( &file ); config.sort(); QString s = ""; QString section = ""; for ( unsigned int i = 0; i < config.size(); i++ ) { s = config[i]; int pos = s.find( ']' ); s = s.left( pos + 1 ); if ( s != section ) { section = s; if ( i != 0 ) stream << endl; stream << section << endl; } stream << config[i].right( config[i].length() - 1 - pos ) << endl; } file.close(); } } } } QString WGConfigFile::getConfigValue( QString& name_value, bool& ok, const char* section ) { QString res = ""; QString str = section ? section : general_section; QString sect; sect.sprintf( "[%s]", str.latin1() ); QString str_section; name_value = name_value.stripWhiteSpace(); for ( unsigned int i = 0; i < config.size(); i++ ) { str = config[i]; int pos = str.find( ']' ); str_section = str.left( pos + 1 ); if ( sect == str_section ) { str = str.right( str.length() - 1 - pos ); if ( str.find( name_value ) == 0 ) { str.remove( 0, name_value.length() + 1 ); // + 1 for removing '=' char after value name if ( str.find('"') == 0 && str.findRev('"') == (int)(str.length()-1) ) { str.remove( str.length()-1, 1 ); str.remove( 0, 1 ); } ok = true; return str; } } } ok = false; return res; } void WGConfigFile::setConfigValue( QString& name_value, QString value, const char* section ) { QString str = section ? section : general_section; QString sect; sect.sprintf( "[%s]", str.latin1() ); QString str_section; name_value = name_value.stripWhiteSpace(); bool found = false; for ( unsigned int i = 0; i < config.size(); i++ ) { str = config[i]; int pos = str.find( ']' ); str_section = str.left( pos + 1 ); if ( sect == str_section ) { str = str.right( str.length() - 1 - pos ); if ( str.find( name_value ) == 0 ) { pos += name_value.length() + 1; // + 1 for adding '=' char after value name str = config[i].left( pos + 1 ); str += value; config[i] = str; found = true; break; } } } if ( !found ) { QString s; s.sprintf( "%s%s=", sect.latin1(), name_value.latin1() ); s += value; config.push_back( s ); } save_config = true; } QString WGConfigFile::read_str( QString& name_value, QString def_value, const char* section ) { bool ok; QString s = getConfigValue( name_value, ok, section ); return ok ? s : def_value; } int WGConfigFile::read_int( QString& name_value, const int def_value, const char* section ) { bool ok; QString s = getConfigValue( name_value, ok, section ); int i = 0; if ( ok ) i = s.toInt( &ok ); return ok ? i : def_value; } bool WGConfigFile::read_bool( QString& name_value, const bool def_value, const char* section ) { bool ok; QString s = getConfigValue( name_value, ok, section ); bool b = true; if ( ok ) b = s.toInt( &ok ) ? true : false; return ok ? b : def_value; } void WGConfigFile::write( QString& name_value, QString value, const char* section ) { QString s = "\""; s += value; s += "\""; setConfigValue( name_value, s, section ); } void WGConfigFile::write( QString& name_value, const int value, const char* section ) { setConfigValue( name_value, QString::number( value ), section ); } void WGConfigFile::write( QString& name_value, const bool value, const char* section ) { QString s; if ( value ) { s = "1"; } else { s = "0"; } setConfigValue( name_value, s, section ); } #else // begin for no Q_OS_UNIX systems QString WGConfigFile::read_str( QString& name_value, QString def_value, const char* section ) { QSettings reg; QString s; if ( section ) { s.sprintf( "/%s/%s/%s", winwget_register, section, name_value.latin1() ); } else { s.sprintf( "/%s/%s", winwget_register, name_value.latin1() ); } return reg.readEntry( s, def_value ); } int WGConfigFile::read_int( QString& name_value, const int def_value, const char* section ) { QSettings reg; QString s; if ( section ) { s.sprintf( "/%s/%s/%s", winwget_register, section, name_value.latin1() ); } else { s.sprintf( "/%s/%s", winwget_register, name_value.latin1() ); } return reg.readNumEntry( s, def_value ); } bool WGConfigFile::read_bool( QString& name_value, const bool def_value, const char* section ) { QSettings reg; QString s; if ( section ) { s.sprintf( "/%s/%s/%s", winwget_register, section, name_value.latin1() ); } else { s.sprintf( "/%s/%s", winwget_register, name_value.latin1() ); } return reg.readBoolEntry( s, def_value ); } void WGConfigFile::write( QString& name_value, QString value, const char* section ) { QSettings reg; QString s; if ( section ) { s.sprintf( "/%s/%s/%s", winwget_register, section, name_value.latin1() ); } else { s.sprintf( "/%s/%s", winwget_register, name_value.latin1() ); } reg.writeEntry( s, value ); } void WGConfigFile::write( QString& name_value, const int value, const char* section ) { QSettings reg; QString s; if ( section ) { s.sprintf( "/%s/%s/%s", winwget_register, section, name_value.latin1() ); } else { s.sprintf( "/%s/%s", winwget_register, name_value.latin1() ); } reg.writeEntry( s, value ); } void WGConfigFile::write( QString& name_value, const bool value, const char* section ) { QSettings reg; QString s; if ( section ) { s.sprintf( "/%s/%s/%s", winwget_register, section, name_value.latin1() ); } else { s.sprintf( "/%s/%s", winwget_register, name_value.latin1() ); } reg.writeEntry( s, value ); } #endif // endif for no Q_OS_UNIX systems QString WGConfigFile::read_str( const char* name_value, QString def_value, const char* section ) { QString n = name_value; QString d = def_value; return read_str( n, d, section ); } int WGConfigFile::read_int( const char* name_value, const int def_value, const char* section ) { QString n = name_value; return read_int( n, def_value, section ); } bool WGConfigFile::read_bool( const char* name_value, const bool def_value, const char* section ) { QString n = name_value; return read_bool( n, def_value, section ); } void WGConfigFile::write( const char* name_value, QString value, const char* section ) { QString n = name_value; write( n, value, section ); } void WGConfigFile::write( const char* name_value, const int value, const char* section ) { QString n = name_value; write( n, value, section ); } void WGConfigFile::write( const char* name_value, const bool value, const char* section ) { QString n = name_value; write( n, value, section ); } <commit_msg>config filename changed<commit_after>#include "config_file.h" #ifdef Q_OS_UNIX #include <qfile.h> #include <qtextstream.h> #include <qdir.h> #define config_file_name ".winwget" #define general_section "general" #else #include <qsettings.h> #define root_register "winwget" #endif // ------------------------------------------------------- // -------- WGConfigFile // ------------------------------------------------------- #ifdef Q_OS_UNIX WGConfigFile::WGConfigFile(): save_config( false ) #else WGConfigFile::WGConfigFile() #endif { #ifdef Q_OS_UNIX config.clear(); open(); #endif } WGConfigFile::~WGConfigFile() { #ifdef Q_OS_UNIX save(); config.clear(); #endif } #ifdef Q_OS_UNIX // begin for Q_OS_UNIX systems void WGConfigFile::open() { QDir dir( QDir::homeDirPath() ); if ( dir.exists() ) { QFile file( dir.filePath( config_file_name ) ); if ( file.open(IO_ReadOnly) ) { QTextStream stream( &file ); config.clear(); QString section; section.sprintf( "[%s]", general_section ); QString s; while ( !stream.atEnd() ) { s = stream.readLine().stripWhiteSpace(); if ( s.find( '[' ) == 0 ) { int pos = s.find( ']' ); if ( pos != -1 ) { section = s.left( pos + 1 ); } } else { if ( !s.isEmpty() ) config.push_back( section + s ); } } file.close(); config.sort(); } } } void WGConfigFile::save() { if ( save_config ) { QDir dir( QDir::homeDirPath() ); if ( dir.exists() ) { QFile file( dir.filePath( config_file_name ) ); if ( file.open(IO_WriteOnly) ) { QTextStream stream( &file ); config.sort(); QString s = ""; QString section = ""; for ( unsigned int i = 0; i < config.size(); i++ ) { s = config[i]; int pos = s.find( ']' ); s = s.left( pos + 1 ); if ( s != section ) { section = s; if ( i != 0 ) stream << endl; stream << section << endl; } stream << config[i].right( config[i].length() - 1 - pos ) << endl; } file.close(); } } } } QString WGConfigFile::getConfigValue( QString& name_value, bool& ok, const char* section ) { QString res = ""; QString str = section ? section : general_section; QString sect; sect.sprintf( "[%s]", str.latin1() ); QString str_section; name_value = name_value.stripWhiteSpace(); for ( unsigned int i = 0; i < config.size(); i++ ) { str = config[i]; int pos = str.find( ']' ); str_section = str.left( pos + 1 ); if ( sect == str_section ) { str = str.right( str.length() - 1 - pos ); if ( str.find( name_value ) == 0 ) { str.remove( 0, name_value.length() + 1 ); // + 1 for removing '=' char after value name if ( str.find('"') == 0 && str.findRev('"') == (int)(str.length()-1) ) { str.remove( str.length()-1, 1 ); str.remove( 0, 1 ); } ok = true; return str; } } } ok = false; return res; } void WGConfigFile::setConfigValue( QString& name_value, QString value, const char* section ) { QString str = section ? section : general_section; QString sect; sect.sprintf( "[%s]", str.latin1() ); QString str_section; name_value = name_value.stripWhiteSpace(); bool found = false; for ( unsigned int i = 0; i < config.size(); i++ ) { str = config[i]; int pos = str.find( ']' ); str_section = str.left( pos + 1 ); if ( sect == str_section ) { str = str.right( str.length() - 1 - pos ); if ( str.find( name_value ) == 0 ) { pos += name_value.length() + 1; // + 1 for adding '=' char after value name str = config[i].left( pos + 1 ); str += value; config[i] = str; found = true; break; } } } if ( !found ) { QString s; s.sprintf( "%s%s=", sect.latin1(), name_value.latin1() ); s += value; config.push_back( s ); } save_config = true; } QString WGConfigFile::read_str( QString& name_value, QString def_value, const char* section ) { bool ok; QString s = getConfigValue( name_value, ok, section ); return ok ? s : def_value; } int WGConfigFile::read_int( QString& name_value, const int def_value, const char* section ) { bool ok; QString s = getConfigValue( name_value, ok, section ); int i = 0; if ( ok ) i = s.toInt( &ok ); return ok ? i : def_value; } bool WGConfigFile::read_bool( QString& name_value, const bool def_value, const char* section ) { bool ok; QString s = getConfigValue( name_value, ok, section ); bool b = true; if ( ok ) b = s.toInt( &ok ) ? true : false; return ok ? b : def_value; } void WGConfigFile::write( QString& name_value, QString value, const char* section ) { QString s = "\""; s += value; s += "\""; setConfigValue( name_value, s, section ); } void WGConfigFile::write( QString& name_value, const int value, const char* section ) { setConfigValue( name_value, QString::number( value ), section ); } void WGConfigFile::write( QString& name_value, const bool value, const char* section ) { QString s; if ( value ) { s = "1"; } else { s = "0"; } setConfigValue( name_value, s, section ); } #else // begin for no Q_OS_UNIX systems QString WGConfigFile::read_str( QString& name_value, QString def_value, const char* section ) { QSettings reg; QString s; if ( section ) { s.sprintf( "/%s/%s/%s", root_register, section, name_value.latin1() ); } else { s.sprintf( "/%s/%s", root_register, name_value.latin1() ); } return reg.readEntry( s, def_value ); } int WGConfigFile::read_int( QString& name_value, const int def_value, const char* section ) { QSettings reg; QString s; if ( section ) { s.sprintf( "/%s/%s/%s", root_register, section, name_value.latin1() ); } else { s.sprintf( "/%s/%s", root_register, name_value.latin1() ); } return reg.readNumEntry( s, def_value ); } bool WGConfigFile::read_bool( QString& name_value, const bool def_value, const char* section ) { QSettings reg; QString s; if ( section ) { s.sprintf( "/%s/%s/%s", root_register, section, name_value.latin1() ); } else { s.sprintf( "/%s/%s", root_register, name_value.latin1() ); } return reg.readBoolEntry( s, def_value ); } void WGConfigFile::write( QString& name_value, QString value, const char* section ) { QSettings reg; QString s; if ( section ) { s.sprintf( "/%s/%s/%s", root_register, section, name_value.latin1() ); } else { s.sprintf( "/%s/%s", root_register, name_value.latin1() ); } reg.writeEntry( s, value ); } void WGConfigFile::write( QString& name_value, const int value, const char* section ) { QSettings reg; QString s; if ( section ) { s.sprintf( "/%s/%s/%s", root_register, section, name_value.latin1() ); } else { s.sprintf( "/%s/%s", root_register, name_value.latin1() ); } reg.writeEntry( s, value ); } void WGConfigFile::write( QString& name_value, const bool value, const char* section ) { QSettings reg; QString s; if ( section ) { s.sprintf( "/%s/%s/%s", root_register, section, name_value.latin1() ); } else { s.sprintf( "/%s/%s", root_register, name_value.latin1() ); } reg.writeEntry( s, value ); } #endif // endif for no Q_OS_UNIX systems QString WGConfigFile::read_str( const char* name_value, QString def_value, const char* section ) { QString n = name_value; QString d = def_value; return read_str( n, d, section ); } int WGConfigFile::read_int( const char* name_value, const int def_value, const char* section ) { QString n = name_value; return read_int( n, def_value, section ); } bool WGConfigFile::read_bool( const char* name_value, const bool def_value, const char* section ) { QString n = name_value; return read_bool( n, def_value, section ); } void WGConfigFile::write( const char* name_value, QString value, const char* section ) { QString n = name_value; write( n, value, section ); } void WGConfigFile::write( const char* name_value, const int value, const char* section ) { QString n = name_value; write( n, value, section ); } void WGConfigFile::write( const char* name_value, const bool value, const char* section ) { QString n = name_value; write( n, value, section ); } <|endoftext|>
<commit_before><commit_msg>WaE: -Wunused-variable<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: except.cxx,v $ * * $Revision: 1.13 $ * * last change: $Author: obo $ $Date: 2006-09-16 15:47:40 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_bridges.hxx" #include <stdio.h> #include <dlfcn.h> #include <cxxabi.h> #include <hash_map> #include <rtl/strbuf.hxx> #include <rtl/ustrbuf.hxx> #include <osl/diagnose.h> #include <osl/mutex.hxx> #include <com/sun/star/uno/genfunc.hxx> #include "com/sun/star/uno/RuntimeException.hpp" #include <typelib/typedescription.hxx> #include <uno/any2.h> #include "share.hxx" using namespace ::std; using namespace ::osl; using namespace ::rtl; using namespace ::com::sun::star::uno; using namespace ::__cxxabiv1; namespace CPPU_CURRENT_NAMESPACE { void dummy_can_throw_anything( char const * ) { } //================================================================================================== static OUString toUNOname( char const * p ) SAL_THROW( () ) { #if OSL_DEBUG_LEVEL > 1 char const * start = p; #endif // example: N3com3sun4star4lang24IllegalArgumentExceptionE OUStringBuffer buf( 64 ); OSL_ASSERT( 'N' == *p ); ++p; // skip N while ('E' != *p) { // read chars count long n = (*p++ - '0'); while ('0' <= *p && '9' >= *p) { n *= 10; n += (*p++ - '0'); } buf.appendAscii( p, n ); p += n; if ('E' != *p) buf.append( (sal_Unicode)'.' ); } #if OSL_DEBUG_LEVEL > 1 OUString ret( buf.makeStringAndClear() ); OString c_ret( OUStringToOString( ret, RTL_TEXTENCODING_ASCII_US ) ); fprintf( stderr, "> toUNOname(): %s => %s\n", start, c_ret.getStr() ); return ret; #else return buf.makeStringAndClear(); #endif } //================================================================================================== class RTTI { typedef hash_map< OUString, type_info *, OUStringHash > t_rtti_map; Mutex m_mutex; t_rtti_map m_rttis; t_rtti_map m_generatedRttis; void * m_hApp; public: RTTI() SAL_THROW( () ); ~RTTI() SAL_THROW( () ); type_info * getRTTI( typelib_CompoundTypeDescription * ) SAL_THROW( () ); }; //__________________________________________________________________________________________________ RTTI::RTTI() SAL_THROW( () ) : m_hApp( dlopen( 0, RTLD_LAZY ) ) { } //__________________________________________________________________________________________________ RTTI::~RTTI() SAL_THROW( () ) { dlclose( m_hApp ); } //__________________________________________________________________________________________________ type_info * RTTI::getRTTI( typelib_CompoundTypeDescription *pTypeDescr ) SAL_THROW( () ) { type_info * rtti; OUString const & unoName = *(OUString const *)&pTypeDescr->aBase.pTypeName; MutexGuard guard( m_mutex ); t_rtti_map::const_iterator iRttiFind( m_rttis.find( unoName ) ); if (iRttiFind == m_rttis.end()) { // RTTI symbol OStringBuffer buf( 64 ); buf.append( RTL_CONSTASCII_STRINGPARAM("_ZTIN") ); sal_Int32 index = 0; do { OUString token( unoName.getToken( 0, '.', index ) ); buf.append( token.getLength() ); OString c_token( OUStringToOString( token, RTL_TEXTENCODING_ASCII_US ) ); buf.append( c_token ); } while (index >= 0); buf.append( 'E' ); OString symName( buf.makeStringAndClear() ); rtti = (type_info *)dlsym( m_hApp, symName.getStr() ); if (rtti) { pair< t_rtti_map::iterator, bool > insertion( m_rttis.insert( t_rtti_map::value_type( unoName, rtti ) ) ); OSL_ENSURE( insertion.second, "### inserting new rtti failed?!" ); } else { // try to lookup the symbol in the generated rtti map t_rtti_map::const_iterator iFind( m_generatedRttis.find( unoName ) ); if (iFind == m_generatedRttis.end()) { // we must generate it ! // symbol and rtti-name is nearly identical, // the symbol is prefixed with _ZTI char const * rttiName = symName.getStr() +4; #if OSL_DEBUG_LEVEL > 1 fprintf( stderr,"generated rtti for %s\n", rttiName ); #endif if (pTypeDescr->pBaseTypeDescription) { // ensure availability of base type_info * base_rtti = getRTTI( (typelib_CompoundTypeDescription *)pTypeDescr->pBaseTypeDescription ); rtti = new __si_class_type_info( strdup( rttiName ), (__class_type_info *)base_rtti ); } else { // this class has no base class rtti = new __class_type_info( strdup( rttiName ) ); } pair< t_rtti_map::iterator, bool > insertion( m_generatedRttis.insert( t_rtti_map::value_type( unoName, rtti ) ) ); OSL_ENSURE( insertion.second, "### inserting new generated rtti failed?!" ); } else // taking already generated rtti { rtti = iFind->second; } } } else { rtti = iRttiFind->second; } return rtti; } //-------------------------------------------------------------------------------------------------- static void deleteException( void * pExc ) { __cxa_exception const * header = ((__cxa_exception const *)pExc - 1); typelib_TypeDescription * pTD = 0; OUString unoName( toUNOname( header->exceptionType->name() ) ); ::typelib_typedescription_getByName( &pTD, unoName.pData ); OSL_ENSURE( pTD, "### unknown exception type! leaving out destruction => leaking!!!" ); if (pTD) { ::uno_destructData( pExc, pTD, cpp_release ); ::typelib_typedescription_release( pTD ); } } //================================================================================================== void raiseException( uno_Any * pUnoExc, uno_Mapping * pUno2Cpp ) { #if OSL_DEBUG_LEVEL > 1 OString cstr( OUStringToOString( *reinterpret_cast< OUString const * >( &pUnoExc->pType->pTypeName ), RTL_TEXTENCODING_ASCII_US ) ); fprintf( stderr, "> uno exception occured: %s\n", cstr.getStr() ); #endif void * pCppExc; type_info * rtti; { // construct cpp exception object typelib_TypeDescription * pTypeDescr = 0; TYPELIB_DANGER_GET( &pTypeDescr, pUnoExc->pType ); OSL_ASSERT( pTypeDescr ); if (! pTypeDescr) { throw RuntimeException( OUString( RTL_CONSTASCII_USTRINGPARAM("cannot get typedescription for type ") ) + *reinterpret_cast< OUString const * >( &pUnoExc->pType->pTypeName ), Reference< XInterface >() ); } pCppExc = __cxa_allocate_exception( pTypeDescr->nSize ); ::uno_copyAndConvertData( pCppExc, pUnoExc->pData, pTypeDescr, pUno2Cpp ); // destruct uno exception ::uno_any_destruct( pUnoExc, 0 ); // avoiding locked counts static RTTI * s_rtti = 0; if (! s_rtti) { MutexGuard guard( Mutex::getGlobalMutex() ); if (! s_rtti) { #ifdef LEAK_STATIC_DATA s_rtti = new RTTI(); #else static RTTI rtti_data; s_rtti = &rtti_data; #endif } } rtti = (type_info *)s_rtti->getRTTI( (typelib_CompoundTypeDescription *) pTypeDescr ); TYPELIB_DANGER_RELEASE( pTypeDescr ); OSL_ENSURE( rtti, "### no rtti for throwing exception!" ); if (! rtti) { throw RuntimeException( OUString( RTL_CONSTASCII_USTRINGPARAM("no rtti for type ") ) + *reinterpret_cast< OUString const * >( &pUnoExc->pType->pTypeName ), Reference< XInterface >() ); } } __cxa_throw( pCppExc, rtti, deleteException ); } //================================================================================================== void fillUnoException( __cxa_exception * header, uno_Any * pUnoExc, uno_Mapping * pCpp2Uno ) { if (! header) { RuntimeException aRE( OUString( RTL_CONSTASCII_USTRINGPARAM("no exception header!") ), Reference< XInterface >() ); Type const & rType = ::getCppuType( &aRE ); uno_type_any_constructAndConvert( pUnoExc, &aRE, rType.getTypeLibType(), pCpp2Uno ); #if OSL_DEBUG_LEVEL > 0 OString cstr( OUStringToOString( aRE.Message, RTL_TEXTENCODING_ASCII_US ) ); OSL_ENSURE( 0, cstr.getStr() ); #endif return; } typelib_TypeDescription * pExcTypeDescr = 0; OUString unoName( toUNOname( header->exceptionType->name() ) ); #if OSL_DEBUG_LEVEL > 1 OString cstr_unoName( OUStringToOString( unoName, RTL_TEXTENCODING_ASCII_US ) ); fprintf( stderr, "> c++ exception occured: %s\n", cstr_unoName.getStr() ); #endif typelib_typedescription_getByName( &pExcTypeDescr, unoName.pData ); if (0 == pExcTypeDescr) { RuntimeException aRE( OUString( RTL_CONSTASCII_USTRINGPARAM("exception type not found: ") ) + unoName, Reference< XInterface >() ); Type const & rType = ::getCppuType( &aRE ); uno_type_any_constructAndConvert( pUnoExc, &aRE, rType.getTypeLibType(), pCpp2Uno ); #if OSL_DEBUG_LEVEL > 0 OString cstr( OUStringToOString( aRE.Message, RTL_TEXTENCODING_ASCII_US ) ); OSL_ENSURE( 0, cstr.getStr() ); #endif } else { // construct uno exception any uno_any_constructAndConvert( pUnoExc, header->adjustedPtr, pExcTypeDescr, pCpp2Uno ); typelib_typedescription_release( pExcTypeDescr ); } } } <commit_msg>INTEGRATION: CWS changefileheader (1.13.100); FILE MERGED 2008/03/28 16:30:08 rt 1.13.100.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: except.cxx,v $ * $Revision: 1.14 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org 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 version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_bridges.hxx" #include <stdio.h> #include <dlfcn.h> #include <cxxabi.h> #include <hash_map> #include <rtl/strbuf.hxx> #include <rtl/ustrbuf.hxx> #include <osl/diagnose.h> #include <osl/mutex.hxx> #include <com/sun/star/uno/genfunc.hxx> #include "com/sun/star/uno/RuntimeException.hpp" #include <typelib/typedescription.hxx> #include <uno/any2.h> #include "share.hxx" using namespace ::std; using namespace ::osl; using namespace ::rtl; using namespace ::com::sun::star::uno; using namespace ::__cxxabiv1; namespace CPPU_CURRENT_NAMESPACE { void dummy_can_throw_anything( char const * ) { } //================================================================================================== static OUString toUNOname( char const * p ) SAL_THROW( () ) { #if OSL_DEBUG_LEVEL > 1 char const * start = p; #endif // example: N3com3sun4star4lang24IllegalArgumentExceptionE OUStringBuffer buf( 64 ); OSL_ASSERT( 'N' == *p ); ++p; // skip N while ('E' != *p) { // read chars count long n = (*p++ - '0'); while ('0' <= *p && '9' >= *p) { n *= 10; n += (*p++ - '0'); } buf.appendAscii( p, n ); p += n; if ('E' != *p) buf.append( (sal_Unicode)'.' ); } #if OSL_DEBUG_LEVEL > 1 OUString ret( buf.makeStringAndClear() ); OString c_ret( OUStringToOString( ret, RTL_TEXTENCODING_ASCII_US ) ); fprintf( stderr, "> toUNOname(): %s => %s\n", start, c_ret.getStr() ); return ret; #else return buf.makeStringAndClear(); #endif } //================================================================================================== class RTTI { typedef hash_map< OUString, type_info *, OUStringHash > t_rtti_map; Mutex m_mutex; t_rtti_map m_rttis; t_rtti_map m_generatedRttis; void * m_hApp; public: RTTI() SAL_THROW( () ); ~RTTI() SAL_THROW( () ); type_info * getRTTI( typelib_CompoundTypeDescription * ) SAL_THROW( () ); }; //__________________________________________________________________________________________________ RTTI::RTTI() SAL_THROW( () ) : m_hApp( dlopen( 0, RTLD_LAZY ) ) { } //__________________________________________________________________________________________________ RTTI::~RTTI() SAL_THROW( () ) { dlclose( m_hApp ); } //__________________________________________________________________________________________________ type_info * RTTI::getRTTI( typelib_CompoundTypeDescription *pTypeDescr ) SAL_THROW( () ) { type_info * rtti; OUString const & unoName = *(OUString const *)&pTypeDescr->aBase.pTypeName; MutexGuard guard( m_mutex ); t_rtti_map::const_iterator iRttiFind( m_rttis.find( unoName ) ); if (iRttiFind == m_rttis.end()) { // RTTI symbol OStringBuffer buf( 64 ); buf.append( RTL_CONSTASCII_STRINGPARAM("_ZTIN") ); sal_Int32 index = 0; do { OUString token( unoName.getToken( 0, '.', index ) ); buf.append( token.getLength() ); OString c_token( OUStringToOString( token, RTL_TEXTENCODING_ASCII_US ) ); buf.append( c_token ); } while (index >= 0); buf.append( 'E' ); OString symName( buf.makeStringAndClear() ); rtti = (type_info *)dlsym( m_hApp, symName.getStr() ); if (rtti) { pair< t_rtti_map::iterator, bool > insertion( m_rttis.insert( t_rtti_map::value_type( unoName, rtti ) ) ); OSL_ENSURE( insertion.second, "### inserting new rtti failed?!" ); } else { // try to lookup the symbol in the generated rtti map t_rtti_map::const_iterator iFind( m_generatedRttis.find( unoName ) ); if (iFind == m_generatedRttis.end()) { // we must generate it ! // symbol and rtti-name is nearly identical, // the symbol is prefixed with _ZTI char const * rttiName = symName.getStr() +4; #if OSL_DEBUG_LEVEL > 1 fprintf( stderr,"generated rtti for %s\n", rttiName ); #endif if (pTypeDescr->pBaseTypeDescription) { // ensure availability of base type_info * base_rtti = getRTTI( (typelib_CompoundTypeDescription *)pTypeDescr->pBaseTypeDescription ); rtti = new __si_class_type_info( strdup( rttiName ), (__class_type_info *)base_rtti ); } else { // this class has no base class rtti = new __class_type_info( strdup( rttiName ) ); } pair< t_rtti_map::iterator, bool > insertion( m_generatedRttis.insert( t_rtti_map::value_type( unoName, rtti ) ) ); OSL_ENSURE( insertion.second, "### inserting new generated rtti failed?!" ); } else // taking already generated rtti { rtti = iFind->second; } } } else { rtti = iRttiFind->second; } return rtti; } //-------------------------------------------------------------------------------------------------- static void deleteException( void * pExc ) { __cxa_exception const * header = ((__cxa_exception const *)pExc - 1); typelib_TypeDescription * pTD = 0; OUString unoName( toUNOname( header->exceptionType->name() ) ); ::typelib_typedescription_getByName( &pTD, unoName.pData ); OSL_ENSURE( pTD, "### unknown exception type! leaving out destruction => leaking!!!" ); if (pTD) { ::uno_destructData( pExc, pTD, cpp_release ); ::typelib_typedescription_release( pTD ); } } //================================================================================================== void raiseException( uno_Any * pUnoExc, uno_Mapping * pUno2Cpp ) { #if OSL_DEBUG_LEVEL > 1 OString cstr( OUStringToOString( *reinterpret_cast< OUString const * >( &pUnoExc->pType->pTypeName ), RTL_TEXTENCODING_ASCII_US ) ); fprintf( stderr, "> uno exception occured: %s\n", cstr.getStr() ); #endif void * pCppExc; type_info * rtti; { // construct cpp exception object typelib_TypeDescription * pTypeDescr = 0; TYPELIB_DANGER_GET( &pTypeDescr, pUnoExc->pType ); OSL_ASSERT( pTypeDescr ); if (! pTypeDescr) { throw RuntimeException( OUString( RTL_CONSTASCII_USTRINGPARAM("cannot get typedescription for type ") ) + *reinterpret_cast< OUString const * >( &pUnoExc->pType->pTypeName ), Reference< XInterface >() ); } pCppExc = __cxa_allocate_exception( pTypeDescr->nSize ); ::uno_copyAndConvertData( pCppExc, pUnoExc->pData, pTypeDescr, pUno2Cpp ); // destruct uno exception ::uno_any_destruct( pUnoExc, 0 ); // avoiding locked counts static RTTI * s_rtti = 0; if (! s_rtti) { MutexGuard guard( Mutex::getGlobalMutex() ); if (! s_rtti) { #ifdef LEAK_STATIC_DATA s_rtti = new RTTI(); #else static RTTI rtti_data; s_rtti = &rtti_data; #endif } } rtti = (type_info *)s_rtti->getRTTI( (typelib_CompoundTypeDescription *) pTypeDescr ); TYPELIB_DANGER_RELEASE( pTypeDescr ); OSL_ENSURE( rtti, "### no rtti for throwing exception!" ); if (! rtti) { throw RuntimeException( OUString( RTL_CONSTASCII_USTRINGPARAM("no rtti for type ") ) + *reinterpret_cast< OUString const * >( &pUnoExc->pType->pTypeName ), Reference< XInterface >() ); } } __cxa_throw( pCppExc, rtti, deleteException ); } //================================================================================================== void fillUnoException( __cxa_exception * header, uno_Any * pUnoExc, uno_Mapping * pCpp2Uno ) { if (! header) { RuntimeException aRE( OUString( RTL_CONSTASCII_USTRINGPARAM("no exception header!") ), Reference< XInterface >() ); Type const & rType = ::getCppuType( &aRE ); uno_type_any_constructAndConvert( pUnoExc, &aRE, rType.getTypeLibType(), pCpp2Uno ); #if OSL_DEBUG_LEVEL > 0 OString cstr( OUStringToOString( aRE.Message, RTL_TEXTENCODING_ASCII_US ) ); OSL_ENSURE( 0, cstr.getStr() ); #endif return; } typelib_TypeDescription * pExcTypeDescr = 0; OUString unoName( toUNOname( header->exceptionType->name() ) ); #if OSL_DEBUG_LEVEL > 1 OString cstr_unoName( OUStringToOString( unoName, RTL_TEXTENCODING_ASCII_US ) ); fprintf( stderr, "> c++ exception occured: %s\n", cstr_unoName.getStr() ); #endif typelib_typedescription_getByName( &pExcTypeDescr, unoName.pData ); if (0 == pExcTypeDescr) { RuntimeException aRE( OUString( RTL_CONSTASCII_USTRINGPARAM("exception type not found: ") ) + unoName, Reference< XInterface >() ); Type const & rType = ::getCppuType( &aRE ); uno_type_any_constructAndConvert( pUnoExc, &aRE, rType.getTypeLibType(), pCpp2Uno ); #if OSL_DEBUG_LEVEL > 0 OString cstr( OUStringToOString( aRE.Message, RTL_TEXTENCODING_ASCII_US ) ); OSL_ENSURE( 0, cstr.getStr() ); #endif } else { // construct uno exception any uno_any_constructAndConvert( pUnoExc, header->adjustedPtr, pExcTypeDescr, pCpp2Uno ); typelib_typedescription_release( pExcTypeDescr ); } } } <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Copyright (c) 2013 Adam Roben <adam@roben.org>. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE-CHROMIUM file. #include "browser/inspectable_web_contents_impl.h" #include "browser/browser_client.h" #include "browser/browser_context.h" #include "browser/browser_main_parts.h" #include "browser/inspectable_web_contents_delegate.h" #include "browser/inspectable_web_contents_view.h" #include "base/json/json_reader.h" #include "base/prefs/pref_registry_simple.h" #include "base/prefs/pref_service.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "base/values.h" #include "content/public/browser/devtools_http_handler.h" #include "content/public/browser/host_zoom_map.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_view_host.h" namespace brightray { namespace { const double kPresetZoomFactors[] = { 0.25, 0.333, 0.5, 0.666, 0.75, 0.9, 1.0, 1.1, 1.25, 1.5, 1.75, 2.0, 2.5, 3.0, 4.0, 5.0 }; const char kChromeUIDevToolsURL[] = "chrome-devtools://devtools/devtools.html?" "can_dock=%s&" "toolbarColor=rgba(223,223,223,1)&" "textColor=rgba(0,0,0,1)&" "experiments=true"; const char kDevToolsBoundsPref[] = "brightray.devtools.bounds"; const char kFrontendHostId[] = "id"; const char kFrontendHostMethod[] = "method"; const char kFrontendHostParams[] = "params"; void RectToDictionary(const gfx::Rect& bounds, base::DictionaryValue* dict) { dict->SetInteger("x", bounds.x()); dict->SetInteger("y", bounds.y()); dict->SetInteger("width", bounds.width()); dict->SetInteger("height", bounds.height()); } void DictionaryToRect(const base::DictionaryValue& dict, gfx::Rect* bounds) { int x = 0, y = 0, width = 800, height = 600; dict.GetInteger("x", &x); dict.GetInteger("y", &y); dict.GetInteger("width", &width); dict.GetInteger("height", &height); *bounds = gfx::Rect(x, y, width, height); } bool ParseMessage(const std::string& message, std::string* method, base::ListValue* params, int* id) { scoped_ptr<base::Value> parsed_message(base::JSONReader::Read(message)); if (!parsed_message) return false; base::DictionaryValue* dict = NULL; if (!parsed_message->GetAsDictionary(&dict)) return false; if (!dict->GetString(kFrontendHostMethod, method)) return false; // "params" is optional. if (dict->HasKey(kFrontendHostParams)) { base::ListValue* internal_params; if (dict->GetList(kFrontendHostParams, &internal_params)) params->Swap(internal_params); else return false; } *id = 0; dict->GetInteger(kFrontendHostId, id); return true; } double GetZoomLevelForWebContents(content::WebContents* web_contents) { return content::HostZoomMap::GetZoomLevel(web_contents); } void SetZoomLevelForWebContents(content::WebContents* web_contents, double level) { content::HostZoomMap::SetZoomLevel(web_contents, level); } double GetNextZoomLevel(double level, bool out) { double factor = content::ZoomLevelToZoomFactor(level); size_t size = arraysize(kPresetZoomFactors); for (size_t i = 0; i < size; ++i) { if (!content::ZoomValuesEqual(kPresetZoomFactors[i], factor)) continue; if (out && i > 0) return content::ZoomFactorToZoomLevel(kPresetZoomFactors[i - 1]); if (!out && i != size - 1) return content::ZoomFactorToZoomLevel(kPresetZoomFactors[i + 1]); } return level; } } // namespace // Implemented separately on each platform. InspectableWebContentsView* CreateInspectableContentsView( InspectableWebContentsImpl* inspectable_web_contents_impl); void InspectableWebContentsImpl::RegisterPrefs(PrefRegistrySimple* registry) { auto bounds_dict = make_scoped_ptr(new base::DictionaryValue); RectToDictionary(gfx::Rect(0, 0, 800, 600), bounds_dict.get()); registry->RegisterDictionaryPref(kDevToolsBoundsPref, bounds_dict.release()); } InspectableWebContentsImpl::InspectableWebContentsImpl( content::WebContents* web_contents) : web_contents_(web_contents), can_dock_(true), delegate_(nullptr) { auto context = static_cast<BrowserContext*>(web_contents_->GetBrowserContext()); auto bounds_dict = context->prefs()->GetDictionary(kDevToolsBoundsPref); if (bounds_dict) DictionaryToRect(*bounds_dict, &devtools_bounds_); view_.reset(CreateInspectableContentsView(this)); } InspectableWebContentsImpl::~InspectableWebContentsImpl() { } InspectableWebContentsView* InspectableWebContentsImpl::GetView() const { return view_.get(); } content::WebContents* InspectableWebContentsImpl::GetWebContents() const { return web_contents_.get(); } void InspectableWebContentsImpl::SetCanDock(bool can_dock) { can_dock_ = can_dock; } void InspectableWebContentsImpl::ShowDevTools() { // Show devtools only after it has done loading, this is to make sure the // SetIsDocked is called *BEFORE* ShowDevTools. if (!devtools_web_contents_) { embedder_message_dispatcher_.reset( new DevToolsEmbedderMessageDispatcher(this)); content::WebContents::CreateParams create_params(web_contents_->GetBrowserContext()); devtools_web_contents_.reset(content::WebContents::Create(create_params)); Observe(devtools_web_contents_.get()); devtools_web_contents_->SetDelegate(this); agent_host_ = content::DevToolsAgentHost::GetOrCreateFor(web_contents_.get()); frontend_host_.reset(content::DevToolsFrontendHost::Create( web_contents_->GetRenderViewHost(), this)); agent_host_->AttachClient(this); GURL devtools_url(base::StringPrintf(kChromeUIDevToolsURL, can_dock_ ? "true" : "")); devtools_web_contents_->GetController().LoadURL( devtools_url, content::Referrer(), ui::PAGE_TRANSITION_AUTO_TOPLEVEL, std::string()); } else { view_->ShowDevTools(); } } void InspectableWebContentsImpl::CloseDevTools() { if (devtools_web_contents_) { view_->CloseDevTools(); devtools_web_contents_.reset(); web_contents_->Focus(); } } bool InspectableWebContentsImpl::IsDevToolsViewShowing() { return devtools_web_contents_ && view_->IsDevToolsViewShowing(); } gfx::Rect InspectableWebContentsImpl::GetDevToolsBounds() const { return devtools_bounds_; } void InspectableWebContentsImpl::SaveDevToolsBounds(const gfx::Rect& bounds) { auto context = static_cast<BrowserContext*>(web_contents_->GetBrowserContext()); base::DictionaryValue bounds_dict; RectToDictionary(bounds, &bounds_dict); context->prefs()->Set(kDevToolsBoundsPref, bounds_dict); devtools_bounds_ = bounds; } void InspectableWebContentsImpl::ActivateWindow() { } void InspectableWebContentsImpl::CloseWindow() { devtools_web_contents()->DispatchBeforeUnload(false); } void InspectableWebContentsImpl::SetInspectedPageBounds(const gfx::Rect& rect) { DevToolsContentsResizingStrategy strategy(rect); if (contents_resizing_strategy_.Equals(strategy)) return; contents_resizing_strategy_.CopyFrom(strategy); view_->SetContentsResizingStrategy(contents_resizing_strategy_); } void InspectableWebContentsImpl::InspectElementCompleted() { } void InspectableWebContentsImpl::MoveWindow(int x, int y) { } void InspectableWebContentsImpl::SetIsDocked(bool docked) { view_->SetIsDocked(docked); } void InspectableWebContentsImpl::OpenInNewTab(const std::string& url) { } void InspectableWebContentsImpl::SaveToFile( const std::string& url, const std::string& content, bool save_as) { if (delegate_) delegate_->DevToolsSaveToFile(url, content, save_as); } void InspectableWebContentsImpl::AppendToFile( const std::string& url, const std::string& content) { if (delegate_) delegate_->DevToolsAppendToFile(url, content); } void InspectableWebContentsImpl::RequestFileSystems() { devtools_web_contents()->GetMainFrame()->ExecuteJavaScript( base::ASCIIToUTF16("InspectorFrontendAPI.fileSystemsLoaded([])")); } void InspectableWebContentsImpl::AddFileSystem() { } void InspectableWebContentsImpl::RemoveFileSystem( const std::string& file_system_path) { } void InspectableWebContentsImpl::UpgradeDraggedFileSystemPermissions( const std::string& file_system_url) { } void InspectableWebContentsImpl::IndexPath( int request_id, const std::string& file_system_path) { } void InspectableWebContentsImpl::StopIndexing(int request_id) { } void InspectableWebContentsImpl::SearchInPath( int request_id, const std::string& file_system_path, const std::string& query) { } void InspectableWebContentsImpl::ZoomIn() { double level = GetZoomLevelForWebContents(devtools_web_contents()); SetZoomLevelForWebContents(devtools_web_contents(), GetNextZoomLevel(level, false)); } void InspectableWebContentsImpl::ZoomOut() { double level = GetZoomLevelForWebContents(devtools_web_contents()); SetZoomLevelForWebContents(devtools_web_contents(), GetNextZoomLevel(level, true)); } void InspectableWebContentsImpl::ResetZoom() { SetZoomLevelForWebContents(devtools_web_contents(), 0.); } void InspectableWebContentsImpl::HandleMessageFromDevToolsFrontend(const std::string& message) { std::string method; base::ListValue params; int id; if (!ParseMessage(message, &method, &params, &id)) { LOG(ERROR) << "Invalid message was sent to embedder: " << message; return; } std::string error = embedder_message_dispatcher_->Dispatch(method, &params); if (id) { std::string ack = base::StringPrintf( "InspectorFrontendAPI.embedderMessageAck(%d, \"%s\");", id, error.c_str()); devtools_web_contents()->GetMainFrame()->ExecuteJavaScript(base::UTF8ToUTF16(ack)); } } void InspectableWebContentsImpl::HandleMessageFromDevToolsFrontendToBackend( const std::string& message) { agent_host_->DispatchProtocolMessage(message); } void InspectableWebContentsImpl::DispatchProtocolMessage( content::DevToolsAgentHost* agent_host, const std::string& message) { std::string code = "InspectorFrontendAPI.dispatchMessage(" + message + ");"; base::string16 javascript = base::UTF8ToUTF16(code); web_contents()->GetMainFrame()->ExecuteJavaScript(javascript); } void InspectableWebContentsImpl::AgentHostClosed( content::DevToolsAgentHost* agent_host, bool replaced) { } void InspectableWebContentsImpl::AboutToNavigateRenderFrame( content::RenderFrameHost* new_host) { if (new_host->GetParent()) return; frontend_host_.reset(content::DevToolsFrontendHost::Create(new_host, this)); } void InspectableWebContentsImpl::DidFinishLoad(content::RenderFrameHost* render_frame_host, const GURL& validated_url) { if (render_frame_host->GetParent()) return; view_->ShowDevTools(); // If the devtools can dock, "SetIsDocked" will be called by devtools itself. if (!can_dock_) SetIsDocked(false); } void InspectableWebContentsImpl::WebContentsDestroyed() { agent_host_->DetachClient(); Observe(nullptr); agent_host_ = nullptr; } bool InspectableWebContentsImpl::AddMessageToConsole( content::WebContents* source, int32 level, const base::string16& message, int32 line_no, const base::string16& source_id) { logging::LogMessage("CONSOLE", line_no, level).stream() << "\"" << message << "\", source: " << source_id << " (" << line_no << ")"; return true; } bool InspectableWebContentsImpl::ShouldCreateWebContents( content::WebContents* web_contents, int route_id, int main_frame_route_id, WindowContainerType window_container_type, const base::string16& frame_name, const GURL& target_url, const std::string& partition_id, content::SessionStorageNamespace* session_storage_namespace) { return false; } void InspectableWebContentsImpl::HandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) { auto delegate = web_contents_->GetDelegate(); if (delegate) delegate->HandleKeyboardEvent(source, event); } void InspectableWebContentsImpl::CloseContents(content::WebContents* source) { CloseDevTools(); } } // namespace brightray <commit_msg>Fix inspectable_web_contents_impl.cc<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Copyright (c) 2013 Adam Roben <adam@roben.org>. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE-CHROMIUM file. #include "browser/inspectable_web_contents_impl.h" #include "browser/browser_client.h" #include "browser/browser_context.h" #include "browser/browser_main_parts.h" #include "browser/inspectable_web_contents_delegate.h" #include "browser/inspectable_web_contents_view.h" #include "base/json/json_reader.h" #include "base/prefs/pref_registry_simple.h" #include "base/prefs/pref_service.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "base/values.h" #include "content/public/browser/devtools_http_handler.h" #include "content/public/browser/host_zoom_map.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_view_host.h" namespace brightray { namespace { const double kPresetZoomFactors[] = { 0.25, 0.333, 0.5, 0.666, 0.75, 0.9, 1.0, 1.1, 1.25, 1.5, 1.75, 2.0, 2.5, 3.0, 4.0, 5.0 }; const char kChromeUIDevToolsURL[] = "chrome-devtools://devtools/devtools.html?" "can_dock=%s&" "toolbarColor=rgba(223,223,223,1)&" "textColor=rgba(0,0,0,1)&" "experiments=true"; const char kDevToolsBoundsPref[] = "brightray.devtools.bounds"; const char kFrontendHostId[] = "id"; const char kFrontendHostMethod[] = "method"; const char kFrontendHostParams[] = "params"; void RectToDictionary(const gfx::Rect& bounds, base::DictionaryValue* dict) { dict->SetInteger("x", bounds.x()); dict->SetInteger("y", bounds.y()); dict->SetInteger("width", bounds.width()); dict->SetInteger("height", bounds.height()); } void DictionaryToRect(const base::DictionaryValue& dict, gfx::Rect* bounds) { int x = 0, y = 0, width = 800, height = 600; dict.GetInteger("x", &x); dict.GetInteger("y", &y); dict.GetInteger("width", &width); dict.GetInteger("height", &height); *bounds = gfx::Rect(x, y, width, height); } bool ParseMessage(const std::string& message, std::string* method, base::ListValue* params, int* id) { scoped_ptr<base::Value> parsed_message(base::JSONReader::Read(message)); if (!parsed_message) return false; base::DictionaryValue* dict = NULL; if (!parsed_message->GetAsDictionary(&dict)) return false; if (!dict->GetString(kFrontendHostMethod, method)) return false; // "params" is optional. if (dict->HasKey(kFrontendHostParams)) { base::ListValue* internal_params; if (dict->GetList(kFrontendHostParams, &internal_params)) params->Swap(internal_params); else return false; } *id = 0; dict->GetInteger(kFrontendHostId, id); return true; } double GetZoomLevelForWebContents(content::WebContents* web_contents) { return content::HostZoomMap::GetZoomLevel(web_contents); } void SetZoomLevelForWebContents(content::WebContents* web_contents, double level) { content::HostZoomMap::SetZoomLevel(web_contents, level); } double GetNextZoomLevel(double level, bool out) { double factor = content::ZoomLevelToZoomFactor(level); size_t size = arraysize(kPresetZoomFactors); for (size_t i = 0; i < size; ++i) { if (!content::ZoomValuesEqual(kPresetZoomFactors[i], factor)) continue; if (out && i > 0) return content::ZoomFactorToZoomLevel(kPresetZoomFactors[i - 1]); if (!out && i != size - 1) return content::ZoomFactorToZoomLevel(kPresetZoomFactors[i + 1]); } return level; } } // namespace // Implemented separately on each platform. InspectableWebContentsView* CreateInspectableContentsView( InspectableWebContentsImpl* inspectable_web_contents_impl); void InspectableWebContentsImpl::RegisterPrefs(PrefRegistrySimple* registry) { auto bounds_dict = make_scoped_ptr(new base::DictionaryValue); RectToDictionary(gfx::Rect(0, 0, 800, 600), bounds_dict.get()); registry->RegisterDictionaryPref(kDevToolsBoundsPref, bounds_dict.release()); } InspectableWebContentsImpl::InspectableWebContentsImpl( content::WebContents* web_contents) : web_contents_(web_contents), can_dock_(true), delegate_(nullptr) { auto context = static_cast<BrowserContext*>(web_contents_->GetBrowserContext()); auto bounds_dict = context->prefs()->GetDictionary(kDevToolsBoundsPref); if (bounds_dict) DictionaryToRect(*bounds_dict, &devtools_bounds_); view_.reset(CreateInspectableContentsView(this)); } InspectableWebContentsImpl::~InspectableWebContentsImpl() { } InspectableWebContentsView* InspectableWebContentsImpl::GetView() const { return view_.get(); } content::WebContents* InspectableWebContentsImpl::GetWebContents() const { return web_contents_.get(); } void InspectableWebContentsImpl::SetCanDock(bool can_dock) { can_dock_ = can_dock; } void InspectableWebContentsImpl::ShowDevTools() { // Show devtools only after it has done loading, this is to make sure the // SetIsDocked is called *BEFORE* ShowDevTools. if (!devtools_web_contents_) { embedder_message_dispatcher_.reset( new DevToolsEmbedderMessageDispatcher(this)); content::WebContents::CreateParams create_params(web_contents_->GetBrowserContext()); devtools_web_contents_.reset(content::WebContents::Create(create_params)); Observe(devtools_web_contents_.get()); devtools_web_contents_->SetDelegate(this); agent_host_ = content::DevToolsAgentHost::GetOrCreateFor(web_contents_.get()); frontend_host_.reset(content::DevToolsFrontendHost::Create( web_contents_->GetMainFrame(), this)); agent_host_->AttachClient(this); GURL devtools_url(base::StringPrintf(kChromeUIDevToolsURL, can_dock_ ? "true" : "")); devtools_web_contents_->GetController().LoadURL( devtools_url, content::Referrer(), ui::PAGE_TRANSITION_AUTO_TOPLEVEL, std::string()); } else { view_->ShowDevTools(); } } void InspectableWebContentsImpl::CloseDevTools() { if (devtools_web_contents_) { view_->CloseDevTools(); devtools_web_contents_.reset(); web_contents_->Focus(); } } bool InspectableWebContentsImpl::IsDevToolsViewShowing() { return devtools_web_contents_ && view_->IsDevToolsViewShowing(); } gfx::Rect InspectableWebContentsImpl::GetDevToolsBounds() const { return devtools_bounds_; } void InspectableWebContentsImpl::SaveDevToolsBounds(const gfx::Rect& bounds) { auto context = static_cast<BrowserContext*>(web_contents_->GetBrowserContext()); base::DictionaryValue bounds_dict; RectToDictionary(bounds, &bounds_dict); context->prefs()->Set(kDevToolsBoundsPref, bounds_dict); devtools_bounds_ = bounds; } void InspectableWebContentsImpl::ActivateWindow() { } void InspectableWebContentsImpl::CloseWindow() { devtools_web_contents()->DispatchBeforeUnload(false); } void InspectableWebContentsImpl::SetInspectedPageBounds(const gfx::Rect& rect) { DevToolsContentsResizingStrategy strategy(rect); if (contents_resizing_strategy_.Equals(strategy)) return; contents_resizing_strategy_.CopyFrom(strategy); view_->SetContentsResizingStrategy(contents_resizing_strategy_); } void InspectableWebContentsImpl::InspectElementCompleted() { } void InspectableWebContentsImpl::MoveWindow(int x, int y) { } void InspectableWebContentsImpl::SetIsDocked(bool docked) { view_->SetIsDocked(docked); } void InspectableWebContentsImpl::OpenInNewTab(const std::string& url) { } void InspectableWebContentsImpl::SaveToFile( const std::string& url, const std::string& content, bool save_as) { if (delegate_) delegate_->DevToolsSaveToFile(url, content, save_as); } void InspectableWebContentsImpl::AppendToFile( const std::string& url, const std::string& content) { if (delegate_) delegate_->DevToolsAppendToFile(url, content); } void InspectableWebContentsImpl::RequestFileSystems() { devtools_web_contents()->GetMainFrame()->ExecuteJavaScript( base::ASCIIToUTF16("InspectorFrontendAPI.fileSystemsLoaded([])")); } void InspectableWebContentsImpl::AddFileSystem() { } void InspectableWebContentsImpl::RemoveFileSystem( const std::string& file_system_path) { } void InspectableWebContentsImpl::UpgradeDraggedFileSystemPermissions( const std::string& file_system_url) { } void InspectableWebContentsImpl::IndexPath( int request_id, const std::string& file_system_path) { } void InspectableWebContentsImpl::StopIndexing(int request_id) { } void InspectableWebContentsImpl::SearchInPath( int request_id, const std::string& file_system_path, const std::string& query) { } void InspectableWebContentsImpl::ZoomIn() { double level = GetZoomLevelForWebContents(devtools_web_contents()); SetZoomLevelForWebContents(devtools_web_contents(), GetNextZoomLevel(level, false)); } void InspectableWebContentsImpl::ZoomOut() { double level = GetZoomLevelForWebContents(devtools_web_contents()); SetZoomLevelForWebContents(devtools_web_contents(), GetNextZoomLevel(level, true)); } void InspectableWebContentsImpl::ResetZoom() { SetZoomLevelForWebContents(devtools_web_contents(), 0.); } void InspectableWebContentsImpl::HandleMessageFromDevToolsFrontend(const std::string& message) { std::string method; base::ListValue params; int id; if (!ParseMessage(message, &method, &params, &id)) { LOG(ERROR) << "Invalid message was sent to embedder: " << message; return; } std::string error = embedder_message_dispatcher_->Dispatch(method, &params); if (id) { std::string ack = base::StringPrintf( "InspectorFrontendAPI.embedderMessageAck(%d, \"%s\");", id, error.c_str()); devtools_web_contents()->GetMainFrame()->ExecuteJavaScript(base::UTF8ToUTF16(ack)); } } void InspectableWebContentsImpl::HandleMessageFromDevToolsFrontendToBackend( const std::string& message) { agent_host_->DispatchProtocolMessage(message); } void InspectableWebContentsImpl::DispatchProtocolMessage( content::DevToolsAgentHost* agent_host, const std::string& message) { std::string code = "InspectorFrontendAPI.dispatchMessage(" + message + ");"; base::string16 javascript = base::UTF8ToUTF16(code); web_contents()->GetMainFrame()->ExecuteJavaScript(javascript); } void InspectableWebContentsImpl::AgentHostClosed( content::DevToolsAgentHost* agent_host, bool replaced) { } void InspectableWebContentsImpl::AboutToNavigateRenderFrame( content::RenderFrameHost* new_host) { if (new_host->GetParent()) return; frontend_host_.reset(content::DevToolsFrontendHost::Create(new_host, this)); } void InspectableWebContentsImpl::DidFinishLoad(content::RenderFrameHost* render_frame_host, const GURL& validated_url) { if (render_frame_host->GetParent()) return; view_->ShowDevTools(); // If the devtools can dock, "SetIsDocked" will be called by devtools itself. if (!can_dock_) SetIsDocked(false); } void InspectableWebContentsImpl::WebContentsDestroyed() { agent_host_->DetachClient(); Observe(nullptr); agent_host_ = nullptr; } bool InspectableWebContentsImpl::AddMessageToConsole( content::WebContents* source, int32 level, const base::string16& message, int32 line_no, const base::string16& source_id) { logging::LogMessage("CONSOLE", line_no, level).stream() << "\"" << message << "\", source: " << source_id << " (" << line_no << ")"; return true; } bool InspectableWebContentsImpl::ShouldCreateWebContents( content::WebContents* web_contents, int route_id, int main_frame_route_id, WindowContainerType window_container_type, const base::string16& frame_name, const GURL& target_url, const std::string& partition_id, content::SessionStorageNamespace* session_storage_namespace) { return false; } void InspectableWebContentsImpl::HandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) { auto delegate = web_contents_->GetDelegate(); if (delegate) delegate->HandleKeyboardEvent(source, event); } void InspectableWebContentsImpl::CloseContents(content::WebContents* source) { CloseDevTools(); } } // namespace brightray <|endoftext|>
<commit_before>// Author: Danilo Piparo CERN 08/2018 /************************************************************************* * Copyright (C) 1995-2018, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ /** Set of helper functions that are invoked from the C++ implementation of pythonizations. */ #include "PyzCppHelpers.hxx" #include "CPyCppyy.h" #include "CPPInstance.h" #include "TClass.h" PyObject *CallPyObjMethod(PyObject *obj, const char *meth) { // Helper; call method with signature: obj->meth() Py_INCREF(obj); PyObject* result = PyObject_CallMethod(obj, const_cast<char*>(meth), const_cast<char*>("")); Py_DECREF(obj); return result; } TClass *GetTClass(const CPyCppyy::CPPInstance *pyobj) { return TClass::GetClass(Cppyy::GetFinalName(pyobj->ObjectIsA()).c_str()); } <commit_msg>[Exp PyROOT] Remove unnecessary incref and decref<commit_after>// Author: Danilo Piparo CERN 08/2018 /************************************************************************* * Copyright (C) 1995-2018, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ /** Set of helper functions that are invoked from the C++ implementation of pythonizations. */ #include "PyzCppHelpers.hxx" #include "CPyCppyy.h" #include "CPPInstance.h" #include "TClass.h" PyObject *CallPyObjMethod(PyObject *obj, const char *meth) { // Helper; call method with signature: obj->meth() return PyObject_CallMethod(obj, const_cast<char*>(meth), const_cast<char*>("")); } TClass *GetTClass(const CPyCppyy::CPPInstance *pyobj) { return TClass::GetClass(Cppyy::GetFinalName(pyobj->ObjectIsA()).c_str()); } <|endoftext|>
<commit_before>/* This file is part of the KDE project. Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). 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 or 3 of the License. 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, see <http://www.gnu.org/licenses/>. */ #include "x11renderer.h" #include "videowidget.h" #ifndef Q_WS_QWS #include "backend.h" #include "debug.h" #include "mediaobject.h" #include <QtGui/QPalette> #include <QApplication> #include <QtGui/QPainter> #include <X11/Xlib.h> #include <gst/gst.h> #if GST_VERSION < GST_VERSION_CHECK (1,0,0,0) #include <gst/interfaces/xoverlay.h> #include <gst/interfaces/propertyprobe.h> #else #include <gst/video/videooverlay.h> #endif namespace Phonon { namespace Gstreamer { class OverlayWidget : public QWidget { public: OverlayWidget(VideoWidget *videoWidget, X11Renderer *renderer) : QWidget(videoWidget), m_videoWidget(videoWidget), m_renderer(renderer) { } void paintEvent(QPaintEvent *) { Phonon::State state = m_videoWidget->root() ? m_videoWidget->root()->state() : Phonon::LoadingState; if (state == Phonon::PlayingState || state == Phonon::PausedState) { m_renderer->windowExposed(); } else { QPainter painter(this); painter.fillRect(m_videoWidget->rect(), m_videoWidget->palette().background()); } } private: VideoWidget *m_videoWidget; X11Renderer *m_renderer; }; X11Renderer::X11Renderer(VideoWidget *videoWidget) : AbstractRenderer(videoWidget) { m_renderWidget = new OverlayWidget(videoWidget, this); debug() << "Creating X11 overlay renderer"; QPalette palette; palette.setColor(QPalette::Background, Qt::black); m_videoWidget->setPalette(palette); m_videoWidget->setAutoFillBackground(true); m_renderWidget->setMouseTracking(true); m_videoSink = createVideoSink(); aspectRatioChanged(videoWidget->aspectRatio()); setOverlay(); } X11Renderer::~X11Renderer() { m_renderWidget->setAttribute(Qt::WA_PaintOnScreen, false); m_renderWidget->setAttribute(Qt::WA_NoSystemBackground, false); delete m_renderWidget; } GstElement* X11Renderer::createVideoSink() { GstElement *videoSink = gst_element_factory_make ("xvimagesink", NULL); if (videoSink) { // Check if the xv sink is usable if (gst_element_set_state(videoSink, GST_STATE_READY) != GST_STATE_CHANGE_SUCCESS) { gst_object_unref(GST_OBJECT(videoSink)); videoSink = 0; } else { // Note that this should not really be necessary as these are // default values, though under certain conditions values are retained // even between application instances. (reproducible on 0.10.16/Gutsy) g_object_set(G_OBJECT(videoSink), "brightness", 0, NULL); g_object_set(G_OBJECT(videoSink), "contrast", 0, NULL); g_object_set(G_OBJECT(videoSink), "hue", 0, NULL); g_object_set(G_OBJECT(videoSink), "saturation", 0, NULL); } } QByteArray tegraEnv = qgetenv("TEGRA_GST_OPENMAX"); if (!tegraEnv.isEmpty()) { videoSink = gst_element_factory_make ("nv_gl_videosink", NULL); } if (!videoSink) { videoSink = gst_element_factory_make ("ximagesink", NULL); } gst_object_ref (GST_OBJECT (videoSink)); //Take ownership #if GST_VERSION < GST_VERSION_CHECK (1,0,0,0) gst_object_sink (GST_OBJECT (videoSink)); #else gst_object_ref_sink (GST_OBJECT (videoSink)); #endif return videoSink; } void X11Renderer::aspectRatioChanged(Phonon::VideoWidget::AspectRatio) { if (m_renderWidget) { m_renderWidget->setGeometry(m_videoWidget->calculateDrawFrameRect()); } } void X11Renderer::scaleModeChanged(Phonon::VideoWidget::ScaleMode) { if (m_renderWidget) { m_renderWidget->setGeometry(m_videoWidget->calculateDrawFrameRect()); } } void X11Renderer::movieSizeChanged(const QSize &movieSize) { Q_UNUSED(movieSize); if (m_renderWidget) { m_renderWidget->setGeometry(m_videoWidget->calculateDrawFrameRect()); } } bool X11Renderer::eventFilter(QEvent *e) { if (e->type() == QEvent::Show) { // Setting these values ensures smooth resizing since it // will prevent the system from clearing the background m_renderWidget->setAttribute(Qt::WA_NoSystemBackground, true); m_renderWidget->setAttribute(Qt::WA_PaintOnScreen, true); setOverlay(); } else if (e->type() == QEvent::Resize) { // This is a workaround for missing background repaints // when reducing window size m_renderWidget->setGeometry(m_videoWidget->calculateDrawFrameRect()); windowExposed(); } return false; } void X11Renderer::handlePaint(QPaintEvent *) { QPainter painter(m_videoWidget); painter.fillRect(m_videoWidget->rect(), m_videoWidget->palette().background()); } void X11Renderer::setOverlay() { if (m_videoSink && #if GST_VERSION < GST_VERSION_CHECK (1,0,0,0) GST_IS_X_OVERLAY(m_videoSink) #else GST_IS_VIDEO_OVERLAY(m_videoSink) #endif ) { WId windowId = m_renderWidget->winId(); // Even if we have created a winId at this point, other X applications // need to be aware of it. #if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) #warning syncx // QApplication::syncX(); #else QApplication::syncX(); #endif // QT_VERSION #if GST_VERSION >= GST_VERSION_CHECK (1,0,0,0) gst_video_overlay_set_window_handle(GST_VIDEO_OVERLAY(m_videoSink), windowId); #elif GST_VERSION >= GST_VERSION_CHECK(0,10,31,0) gst_x_overlay_set_window_handle(GST_X_OVERLAY(m_videoSink), windowId); #elif GST_VERSION <= GST_VERSION_CHECK(0,10,31,0) gst_x_overlay_set_xwindow_id(GST_X_OVERLAY(m_videoSink), windowId); #endif // GST_VERSION } windowExposed(); m_overlaySet = true; } void X11Renderer::windowExposed() { #if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) #warning syncx // QApplication::syncX(); #else QApplication::syncX(); if (m_videoSink && #if GST_VERSION < GST_VERSION_CHECK (1,0,0,0) GST_IS_X_OVERLAY(m_videoSink) #else GST_IS_VIDEO_OVERLAY(m_videoSink) #endif ) #if GST_VERSION < GST_VERSION_CHECK (1,0,0,0) gst_x_overlay_expose(GST_X_OVERLAY(m_videoSink)); #else gst_video_overlay_expose(GST_VIDEO_OVERLAY(m_videoSink)); #endif #endif //QT_VERSION } } } //namespace Phonon::Gstreamer #endif // Q_WS_QWS <commit_msg>Fix merge ifdef properly<commit_after>/* This file is part of the KDE project. Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). 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 or 3 of the License. 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, see <http://www.gnu.org/licenses/>. */ #include "x11renderer.h" #include "videowidget.h" #ifndef Q_WS_QWS #include "backend.h" #include "debug.h" #include "mediaobject.h" #include <QtGui/QPalette> #include <QApplication> #include <QtGui/QPainter> #include <X11/Xlib.h> #include <gst/gst.h> #if GST_VERSION < GST_VERSION_CHECK (1,0,0,0) #include <gst/interfaces/xoverlay.h> #include <gst/interfaces/propertyprobe.h> #else #include <gst/video/videooverlay.h> #endif namespace Phonon { namespace Gstreamer { class OverlayWidget : public QWidget { public: OverlayWidget(VideoWidget *videoWidget, X11Renderer *renderer) : QWidget(videoWidget), m_videoWidget(videoWidget), m_renderer(renderer) { } void paintEvent(QPaintEvent *) { Phonon::State state = m_videoWidget->root() ? m_videoWidget->root()->state() : Phonon::LoadingState; if (state == Phonon::PlayingState || state == Phonon::PausedState) { m_renderer->windowExposed(); } else { QPainter painter(this); painter.fillRect(m_videoWidget->rect(), m_videoWidget->palette().background()); } } private: VideoWidget *m_videoWidget; X11Renderer *m_renderer; }; X11Renderer::X11Renderer(VideoWidget *videoWidget) : AbstractRenderer(videoWidget) { m_renderWidget = new OverlayWidget(videoWidget, this); debug() << "Creating X11 overlay renderer"; QPalette palette; palette.setColor(QPalette::Background, Qt::black); m_videoWidget->setPalette(palette); m_videoWidget->setAutoFillBackground(true); m_renderWidget->setMouseTracking(true); m_videoSink = createVideoSink(); aspectRatioChanged(videoWidget->aspectRatio()); setOverlay(); } X11Renderer::~X11Renderer() { m_renderWidget->setAttribute(Qt::WA_PaintOnScreen, false); m_renderWidget->setAttribute(Qt::WA_NoSystemBackground, false); delete m_renderWidget; } GstElement* X11Renderer::createVideoSink() { GstElement *videoSink = gst_element_factory_make ("xvimagesink", NULL); if (videoSink) { // Check if the xv sink is usable if (gst_element_set_state(videoSink, GST_STATE_READY) != GST_STATE_CHANGE_SUCCESS) { gst_object_unref(GST_OBJECT(videoSink)); videoSink = 0; } else { // Note that this should not really be necessary as these are // default values, though under certain conditions values are retained // even between application instances. (reproducible on 0.10.16/Gutsy) g_object_set(G_OBJECT(videoSink), "brightness", 0, NULL); g_object_set(G_OBJECT(videoSink), "contrast", 0, NULL); g_object_set(G_OBJECT(videoSink), "hue", 0, NULL); g_object_set(G_OBJECT(videoSink), "saturation", 0, NULL); } } QByteArray tegraEnv = qgetenv("TEGRA_GST_OPENMAX"); if (!tegraEnv.isEmpty()) { videoSink = gst_element_factory_make ("nv_gl_videosink", NULL); } if (!videoSink) { videoSink = gst_element_factory_make ("ximagesink", NULL); } gst_object_ref (GST_OBJECT (videoSink)); //Take ownership #if GST_VERSION < GST_VERSION_CHECK (1,0,0,0) gst_object_sink (GST_OBJECT (videoSink)); #else gst_object_ref_sink (GST_OBJECT (videoSink)); #endif return videoSink; } void X11Renderer::aspectRatioChanged(Phonon::VideoWidget::AspectRatio) { if (m_renderWidget) { m_renderWidget->setGeometry(m_videoWidget->calculateDrawFrameRect()); } } void X11Renderer::scaleModeChanged(Phonon::VideoWidget::ScaleMode) { if (m_renderWidget) { m_renderWidget->setGeometry(m_videoWidget->calculateDrawFrameRect()); } } void X11Renderer::movieSizeChanged(const QSize &movieSize) { Q_UNUSED(movieSize); if (m_renderWidget) { m_renderWidget->setGeometry(m_videoWidget->calculateDrawFrameRect()); } } bool X11Renderer::eventFilter(QEvent *e) { if (e->type() == QEvent::Show) { // Setting these values ensures smooth resizing since it // will prevent the system from clearing the background m_renderWidget->setAttribute(Qt::WA_NoSystemBackground, true); m_renderWidget->setAttribute(Qt::WA_PaintOnScreen, true); setOverlay(); } else if (e->type() == QEvent::Resize) { // This is a workaround for missing background repaints // when reducing window size m_renderWidget->setGeometry(m_videoWidget->calculateDrawFrameRect()); windowExposed(); } return false; } void X11Renderer::handlePaint(QPaintEvent *) { QPainter painter(m_videoWidget); painter.fillRect(m_videoWidget->rect(), m_videoWidget->palette().background()); } void X11Renderer::setOverlay() { if (m_videoSink && #if GST_VERSION < GST_VERSION_CHECK (1,0,0,0) GST_IS_X_OVERLAY(m_videoSink) #else GST_IS_VIDEO_OVERLAY(m_videoSink) #endif ) { WId windowId = m_renderWidget->winId(); // Even if we have created a winId at this point, other X applications // need to be aware of it. #if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) #warning syncx // QApplication::syncX(); #else QApplication::syncX(); #endif // QT_VERSION #if GST_VERSION >= GST_VERSION_CHECK (1,0,0,0) gst_video_overlay_set_window_handle(GST_VIDEO_OVERLAY(m_videoSink), windowId); #elif GST_VERSION >= GST_VERSION_CHECK(0,10,31,0) gst_x_overlay_set_window_handle(GST_X_OVERLAY(m_videoSink), windowId); #elif GST_VERSION <= GST_VERSION_CHECK(0,10,31,0) gst_x_overlay_set_xwindow_id(GST_X_OVERLAY(m_videoSink), windowId); #endif // GST_VERSION } windowExposed(); m_overlaySet = true; } void X11Renderer::windowExposed() { #if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) #warning syncx // QApplication::syncX(); #else QApplication::syncX(); #endif //QT_VERSION if (m_videoSink && #if GST_VERSION < GST_VERSION_CHECK (1,0,0,0) GST_IS_X_OVERLAY(m_videoSink) #else GST_IS_VIDEO_OVERLAY(m_videoSink) #endif ) #if GST_VERSION < GST_VERSION_CHECK (1,0,0,0) gst_x_overlay_expose(GST_X_OVERLAY(m_videoSink)); #else gst_video_overlay_expose(GST_VIDEO_OVERLAY(m_videoSink)); #endif } } } //namespace Phonon::Gstreamer #endif // Q_WS_QWS <|endoftext|>
<commit_before>/*************************************************************** * * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI. * * Licensed under the Apache License, Version 2.0 (the "License"); you * may not use this file except in compliance with the License. You may * obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************/ #include "condor_common.h" #include "my_hostname.h" void usage( char* me ) { fprintf( stderr, "Usage: %s -ip | -fullhost | -sin\n", me ); exit( 1 ); } int main( int argc, char* argv[] ) { if( argc != 2 ) { usage( argv[0] ); } switch( argv[1][1] ) { case 'i': printf( "ip: %ul\n", my_ip_addr() ); break; case 'f': printf( "fullhost: %s\n", get_local_fqdn().Value() ); break; case 's': printf( "sin_addr: %ul\n", (my_sin_addr())->s_addr ); printf( "ntohl sin_addr: %ul\n", ntohl((my_sin_addr())->s_addr) ); printf( "ntoa sin_addr: %s\n", inet_ntoa(*(my_sin_addr())) ); break; default: usage( argv[0] ); break; } return 0; } <commit_msg>Restore my_hostname test using get_local_hostname. #4718<commit_after>/*************************************************************** * * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI. * * Licensed under the Apache License, Version 2.0 (the "License"); you * may not use this file except in compliance with the License. You may * obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************/ #include "condor_common.h" #include "my_hostname.h" void usage( char* me ) { fprintf( stderr, "Usage: %s -ip | -host | -fullhost | -sin\n", me ); exit( 1 ); } int main( int argc, char* argv[] ) { if( argc != 2 ) { usage( argv[0] ); } switch( argv[1][1] ) { case 'i': printf( "ip: %ul\n", my_ip_addr() ); break; case 'h': printf( "host: %s\n", get_local_hostname().Value() ); break; case 'f': printf( "fullhost: %s\n", get_local_fqdn().Value() ); break; case 's': printf( "sin_addr: %ul\n", (my_sin_addr())->s_addr ); printf( "ntohl sin_addr: %ul\n", ntohl((my_sin_addr())->s_addr) ); printf( "ntoa sin_addr: %s\n", inet_ntoa(*(my_sin_addr())) ); break; default: usage( argv[0] ); break; } return 0; } <|endoftext|>
<commit_before> #ifndef __TWO_LEVEL_ARRAY_HPP__ #define __TWO_LEVEL_ARRAY_HPP__ #include "utils.hpp" /* two_level_array_t is a tree that always has exactly two levels. Its computational complexity is similar to that of an array, but it neither allocates all of its memory at once nor needs to realloc() as it grows. It is parameterized on a value type, 'value_t'. It makes the following assumptions about value_t: 1. value_t has a default constructor value_t() that has no side effects, and its destructor has no side effects. 2. value_t supports conversion to bool 3. bool(value_t()) == false 4. bool(any other instance of value_t) == true Pointer types work well for value_t. If a get() is called on an index in the array that set() has never been called for, the result will be value_t(). It is also parameterized at compile-time on the maximum number of elements in the array and on the size of the chunks to use. */ #define DEFAULT_TWO_LEVEL_ARRAY_CHUNK_SIZE (1 << 16) template <class value_t, int max_size, int chunk_size = DEFAULT_TWO_LEVEL_ARRAY_CHUNK_SIZE> class two_level_array_t { public: typedef unsigned int key_t; private: static const unsigned int num_chunks = max_size / chunk_size + 1; unsigned int count; struct chunk_t { chunk_t() : count(0), values() // default-initialize each value in values { } unsigned int count; value_t values[chunk_size]; }; chunk_t *chunks[num_chunks]; static unsigned int chunk_for_key(key_t key) { unsigned int chunk_id = key / chunk_size; rassert(chunk_id < num_chunks); return chunk_id; } static unsigned int index_for_key(key_t key) { return key % chunk_size; } public: two_level_array_t() : count(0), chunks() { } ~two_level_array_t() { for (unsigned int i = 0; i < num_chunks; i++) { if (chunks[i]) delete chunks[i]; } } value_t get(key_t key) const { unsigned int chunk_id = chunk_for_key(key); if (chunks[chunk_id]) { return chunks[chunk_id]->values[index_for_key(key)]; } else { return value_t(); } } void set(key_t key, value_t value) { unsigned int chunk_id = chunk_for_key(key); chunk_t *chunk = chunks[chunk_id]; if (!bool(value) && !chunk) { /* If the user is inserting a zero value into an already-empty chunk, exit early so we don't create a new empty chunk */ return; } if (!chunk) chunk = chunks[chunk_id] = new chunk_t; if (bool(chunk->values[index_for_key(key)])) { chunk->count--; count--; } chunk->values[index_for_key(key)] = value; if (bool(value)) { chunk->count++; count++; } if (chunk->count == 0) { chunks[chunk_id] = NULL; delete chunk; } } unsigned int size() { return count; } }; #endif // __TWO_LEVEL_ARRAY_HPP__ <commit_msg>Made two-level-array allocate its top level from the heap.<commit_after> #ifndef __TWO_LEVEL_ARRAY_HPP__ #define __TWO_LEVEL_ARRAY_HPP__ #include "utils.hpp" #include <boost/scoped_array.hpp> /* two_level_array_t is a tree that always has exactly two levels. Its computational complexity is similar to that of an array, but it neither allocates all of its memory at once nor needs to realloc() as it grows. It is parameterized on a value type, 'value_t'. It makes the following assumptions about value_t: 1. value_t has a default constructor value_t() that has no side effects, and its destructor has no side effects. 2. value_t supports conversion to bool 3. bool(value_t()) == false 4. bool(any other instance of value_t) == true Pointer types work well for value_t. If a get() is called on an index in the array that set() has never been called for, the result will be value_t(). It is also parameterized at compile-time on the maximum number of elements in the array and on the size of the chunks to use. */ #define DEFAULT_TWO_LEVEL_ARRAY_CHUNK_SIZE (1 << 16) template <class value_t, int max_size, int chunk_size = DEFAULT_TWO_LEVEL_ARRAY_CHUNK_SIZE> class two_level_array_t { public: typedef unsigned int key_t; private: static const unsigned int num_chunks = max_size / chunk_size + 1; unsigned int count; struct chunk_t { chunk_t() : count(0), values() // default-initialize each value in values { } unsigned int count; value_t values[chunk_size]; }; boost::scoped_array<chunk_t*> chunks; static unsigned int chunk_for_key(key_t key) { unsigned int chunk_id = key / chunk_size; rassert(chunk_id < num_chunks); return chunk_id; } static unsigned int index_for_key(key_t key) { return key % chunk_size; } public: two_level_array_t() : count(0), chunks(new chunk_t*[num_chunks]) { for (unsigned int i = 0; i < num_chunks; i++) { chunks[i] = NULL; } } ~two_level_array_t() { for (unsigned int i = 0; i < num_chunks; i++) { if (chunks[i]) delete chunks[i]; } } value_t get(key_t key) const { unsigned int chunk_id = chunk_for_key(key); if (chunks[chunk_id]) { return chunks[chunk_id]->values[index_for_key(key)]; } else { return value_t(); } } void set(key_t key, value_t value) { unsigned int chunk_id = chunk_for_key(key); chunk_t *chunk = chunks[chunk_id]; if (!bool(value) && !chunk) { /* If the user is inserting a zero value into an already-empty chunk, exit early so we don't create a new empty chunk */ return; } if (!chunk) chunk = chunks[chunk_id] = new chunk_t; if (bool(chunk->values[index_for_key(key)])) { chunk->count--; count--; } chunk->values[index_for_key(key)] = value; if (bool(value)) { chunk->count++; count++; } if (chunk->count == 0) { chunks[chunk_id] = NULL; delete chunk; } } unsigned int size() { return count; } }; #endif // __TWO_LEVEL_ARRAY_HPP__ <|endoftext|>
<commit_before>// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon // We are making my contributions/submissions to this project solely in our // personal capacity and are not conveying any rights to any intellectual // property of any third parties. #include <hspp/Games/GameManager.hpp> namespace Hearthstonepp { void GameManager::ProcessNextStep(Game& game, Step step) { // Do nothing } } // namespace Hearthstonepp<commit_msg>[ci skip] feat(game-state): Add code to process BEGIN_FIRST step<commit_after>// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon // We are making my contributions/submissions to this project solely in our // personal capacity and are not conveying any rights to any intellectual // property of any third parties. #include <hspp/Games/GameManager.hpp> namespace Hearthstonepp { void GameManager::ProcessNextStep(Game& game, Step step) { switch (step) { case Step::BEGIN_FIRST: game.step = step; game.BeginFirst(); break; default: break; } } } // namespace Hearthstonepp<|endoftext|>
<commit_before>#include <QTimer> #include <QLabel> #include <QPainter> #include "CommentLib.h" #include "AssassinWar.h" #include "MapLoader.h" #include "UnderGrid.h" #include "PixelCoordinateTransfer.h" const int GRID_NUMBER_IS_ZERO = -1; AssassinWar::AssassinWar(QWidget *parent, Qt::WFlags flags) : QMainWindow(parent, flags), m_pRepaintTimer(NULL), m_pMapLoader(NULL), m_pUnderGrid(NULL) { } AssassinWar::~AssassinWar() { m_pRepaintTimer->stop(); if(NULL != m_pMapLoader) { delete m_pMapLoader; m_pMapLoader = NULL; } if(NULL != m_pUnderGrid) { delete m_pUnderGrid; m_pUnderGrid = NULL; } } void AssassinWar::paintEvent(QPaintEvent *PaintEvent) { static float a = 0.0f; if(60 < a) { a = 0.0f; } QPainter painter(this); painter.drawLine(++a, 0.0, 15.0, 25.0);// drawing code } bool AssassinWar::initAW() { bool bInitSuccessed = true; m_pRepaintTimer = new QTimer(this); connect(m_pRepaintTimer, SIGNAL(timeout()), this, SLOT(repaint())); m_pRepaintTimer->start(250); m_pMapLoader = new MapLoader(); m_pMapLoader->InitMapLoader(); m_pUnderGrid = new UnderGrid(); QString strMapPath = "./map/map1.ui"; bInitSuccessed = LoadGameMap_(strMapPath); setWindowState(Qt::WindowFullScreen); return bInitSuccessed; } bool AssassinWar::LoadGameMap_(const QString& strMapPath) { bool bLoadGameMapSuccessed = true; QWidget* pMapWidget = m_pMapLoader->LoadMap(strMapPath); if(NULL == pMapWidget) { bLoadGameMapSuccessed = false; } else { setCentralWidget(pMapWidget); QSize mapSize = pMapWidget->size(); float fMapWidth = static_cast<float>(mapSize.width()); float fMapHeight = static_cast<float>(mapSize.height()); int iAllGridTotalWidth = PixelCoordinateTransfer::Instance().ToGridX(fMapWidth); int iAllGridTotalHeight = PixelCoordinateTransfer::Instance().ToGridY(fMapHeight); if(GRID_NUMBER_IS_ZERO != iAllGridTotalWidth && GRID_NUMBER_IS_ZERO != iAllGridTotalHeight) { unsigned int uiAllGridTotalWidth = static_cast<unsigned int>(iAllGridTotalWidth); unsigned int uiAllGridTotalHeight = static_cast<unsigned int>(iAllGridTotalHeight); m_pUnderGrid->SetSize(uiAllGridTotalWidth, uiAllGridTotalHeight); m_ListTerrains = m_pMapLoader->LoadMapTerrain(*pMapWidget); } else { bLoadGameMapSuccessed = false; } } return bLoadGameMapSuccessed; } <commit_msg>fix bug:map is small than it should be<commit_after>#include <QTimer> #include <QLabel> #include <QPainter> #include "CommentLib.h" #include "AssassinWar.h" #include "MapLoader.h" #include "UnderGrid.h" #include "PixelCoordinateTransfer.h" const int GRID_NUMBER_IS_ZERO = -1; AssassinWar::AssassinWar(QWidget *parent, Qt::WFlags flags) : QMainWindow(parent, flags), m_pRepaintTimer(NULL), m_pMapLoader(NULL), m_pUnderGrid(NULL) { } AssassinWar::~AssassinWar() { m_pRepaintTimer->stop(); if(NULL != m_pMapLoader) { delete m_pMapLoader; m_pMapLoader = NULL; } if(NULL != m_pUnderGrid) { delete m_pUnderGrid; m_pUnderGrid = NULL; } } void AssassinWar::paintEvent(QPaintEvent *PaintEvent) { static float a = 0.0f; if(60 < a) { a = 0.0f; } QPainter painter(this); painter.drawLine(++a, 0.0, 15.0, 25.0);// drawing code } bool AssassinWar::initAW() { bool bInitSuccessed = true; m_pRepaintTimer = new QTimer(this); connect(m_pRepaintTimer, SIGNAL(timeout()), this, SLOT(repaint())); m_pRepaintTimer->start(250); m_pMapLoader = new MapLoader(); m_pMapLoader->InitMapLoader(); m_pUnderGrid = new UnderGrid(); QString strMapPath = "./map/map1.ui"; bInitSuccessed = LoadGameMap_(strMapPath); setWindowState(Qt::WindowFullScreen); return bInitSuccessed; } bool AssassinWar::LoadGameMap_(const QString& strMapPath) { bool bLoadGameMapSuccessed = true; QWidget* pMapWidget = m_pMapLoader->LoadMap(strMapPath); if(NULL == pMapWidget) { bLoadGameMapSuccessed = false; } else { setCentralWidget(pMapWidget); QSize mapSize = pMapWidget->size(); float fMapWidth = static_cast<float>(mapSize.width()); float fMapHeight = static_cast<float>(mapSize.height()); int iAllGridTotalRow = PixelCoordinateTransfer::Instance().ToGridX(fMapWidth); int iAllGridTotalColumn = PixelCoordinateTransfer::Instance().ToGridY(fMapHeight); if(GRID_NUMBER_IS_ZERO != iAllGridTotalRow && GRID_NUMBER_IS_ZERO != iAllGridTotalColumn) { unsigned int uiAllGridTotalWidth = static_cast<unsigned int>(iAllGridTotalRow + 1); unsigned int uiAllGridTotalHeight = static_cast<unsigned int>(iAllGridTotalColumn + 1); m_pUnderGrid->SetSize(uiAllGridTotalWidth, uiAllGridTotalHeight); m_ListTerrains = m_pMapLoader->LoadMapTerrain(*pMapWidget); } else { bLoadGameMapSuccessed = false; } } return bLoadGameMapSuccessed; } <|endoftext|>
<commit_before>#include "panel_console.h" #include <glgui/label.h> #include <glgui/textfield.h> #include <glgui/rootpanel.h> #include <tinker/application.h> #include <tinker/profiler.h> #include "monitor_window.h" using namespace glgui; CPanel_Console::CPanel_Console() { m_hOutput = AddControl(new CLabel(0, 0, 100, 100, "")); m_hOutput->SetAlign(CLabel::TA_BOTTOMLEFT); m_hInput = AddControl(new CTextField()); m_hStatus = AddControl(new CLabel(0, 0, 100, 100, "")); m_hStatus->SetAlign(CLabel::TA_TOPLEFT); m_bScissoring = true; } void CPanel_Console::Layout() { m_hInput->SetSize(GetWidth(), 20); m_hInput->SetPos(0, GetHeight() - 20); m_hOutput->SetSize(GetWidth(), GetHeight() - 24); m_hOutput->SetPos(0, 0); m_hStatus->SetPos(GetWidth() * 2 / 3, 10); m_hStatus->SetSize(GetWidth() / 3, GetHeight() * 2 / 3); BaseClass::Layout(); } void CPanel_Console::Think() { BaseClass::Think(); if (MonitorWindow()->GetViewback()->GetStatus().length()) { m_hStatus->SetVisible(true); m_hStatus->SetText(MonitorWindow()->GetViewback()->GetStatus().c_str()); } else m_hStatus->SetVisible(false); // If there's too much shit in the console, throw some out. if (m_hOutput->GetTextHeight() > GetHeight() * 2) { tvector<tstring> asTokens; explode(m_hOutput->GetText(), asTokens, "\n"); // About how many lines can we fit in the space we have? size_t iLinesInSpace = (int)(GetHeight() / m_hOutput->GetTextHeight() * m_hOutput->GetNumLines()); iLinesInSpace = (size_t)((float)iLinesInSpace * 1.5f); if (asTokens.size() > iLinesInSpace) { int iInitialLines = asTokens.size(); asTokens.erase(asTokens.begin(), asTokens.end() - iLinesInSpace); tstring sNewOutput; for (size_t i = 0; i < asTokens.size(); i++) { if (!asTokens[i].length()) continue; sNewOutput += asTokens[i] + "\n"; } m_hOutput->SetText(sNewOutput); } } } void CPanel_Console::Paint(float x, float y, float w, float h) { TPROF("CPanel_Console::Paint()"); BaseClass::Paint(x, y, w, h); } void CPanel_Console::PrintConsole(const tstring& sText) { m_hOutput->AppendText(sText); if (m_hOutput->GetText().length() > 2500) m_hOutput->SetText(m_hOutput->GetText().substr(500)); if (!Application()->IsOpen()) return; if (IsVisible()) Layout(); } bool CPanel_Console::KeyPressed(int code, bool bCtrlDown) { if (!IsVisible()) return false; if (m_asHistory.size()) { if (code == TINKER_KEY_DOWN) { if (m_iHistory >= 0 && m_iHistory < (int)m_asHistory.size() - 1) { m_iHistory++; m_hInput->SetText(m_asHistory[m_iHistory]); m_hInput->SetCursorPosition(-1); } else if (m_iHistory == (int)m_asHistory.size() - 1) { m_iHistory = -1; m_hInput->SetText(""); } } else if (code == TINKER_KEY_UP) { if (m_iHistory == -1) m_iHistory = m_asHistory.size() - 1; else if (m_iHistory > 0) m_iHistory--; m_hInput->SetText(m_asHistory[m_iHistory]); m_hInput->SetCursorPosition(-1); } else m_iHistory = -1; } if (code == TINKER_KEY_ENTER || code == TINKER_KEY_KP_ENTER) { tstring sText = m_hInput->GetText(); m_hInput->SetText(""); PrintConsole(tstring("--> ") + sText + "\n"); MonitorWindow()->GetViewback()->SendConsoleCommand(sText.c_str()); if (trim(sText).length()) m_asHistory.push_back(trim(sText)); m_iHistory = -1; return true; } bool bReturn = BaseClass::KeyPressed(code, bCtrlDown); if (bReturn && !(code == TINKER_KEY_ENTER || code == TINKER_KEY_KP_ENTER)) return true; return false; } <commit_msg>Throw in a timestamp when printing out log messages. They should be separated into their own column, but that's not terribly important for now.<commit_after>#include "panel_console.h" #include <glgui/label.h> #include <glgui/textfield.h> #include <glgui/rootpanel.h> #include <tinker/application.h> #include <tinker/profiler.h> #include "monitor_window.h" using namespace glgui; CPanel_Console::CPanel_Console() { m_hOutput = AddControl(new CLabel(0, 0, 100, 100, "")); m_hOutput->SetAlign(CLabel::TA_BOTTOMLEFT); m_hInput = AddControl(new CTextField()); m_hStatus = AddControl(new CLabel(0, 0, 100, 100, "")); m_hStatus->SetAlign(CLabel::TA_TOPLEFT); m_bScissoring = true; } void CPanel_Console::Layout() { m_hInput->SetSize(GetWidth(), 20); m_hInput->SetPos(0, GetHeight() - 20); m_hOutput->SetSize(GetWidth(), GetHeight() - 24); m_hOutput->SetPos(0, 0); m_hStatus->SetPos(GetWidth() * 2 / 3, 10); m_hStatus->SetSize(GetWidth() / 3, GetHeight() * 2 / 3); BaseClass::Layout(); } void CPanel_Console::Think() { BaseClass::Think(); if (MonitorWindow()->GetViewback()->GetStatus().length()) { m_hStatus->SetVisible(true); m_hStatus->SetText(MonitorWindow()->GetViewback()->GetStatus().c_str()); } else m_hStatus->SetVisible(false); // If there's too much shit in the console, throw some out. if (m_hOutput->GetTextHeight() > GetHeight() * 2) { tvector<tstring> asTokens; explode(m_hOutput->GetText(), asTokens, "\n"); // About how many lines can we fit in the space we have? size_t iLinesInSpace = (int)(GetHeight() / m_hOutput->GetTextHeight() * m_hOutput->GetNumLines()); iLinesInSpace = (size_t)((float)iLinesInSpace * 1.5f); if (asTokens.size() > iLinesInSpace) { int iInitialLines = asTokens.size(); asTokens.erase(asTokens.begin(), asTokens.end() - iLinesInSpace); tstring sNewOutput; for (size_t i = 0; i < asTokens.size(); i++) { if (!asTokens[i].length()) continue; sNewOutput += asTokens[i] + "\n"; } m_hOutput->SetText(sNewOutput); } } } void CPanel_Console::Paint(float x, float y, float w, float h) { TPROF("CPanel_Console::Paint()"); BaseClass::Paint(x, y, w, h); } void CPanel_Console::PrintConsole(const tstring& sText) { if (!m_hOutput->GetText().length() || m_hOutput->GetText().back() == '\n') { float the_time = (float)Viewback()->PredictCurrentTime(); m_hOutput->AppendText("[color=aaaaaa]" + pretty_float(the_time, 3) + "[/color] "); } m_hOutput->AppendText(sText); if (m_hOutput->GetText().length() > 2500) m_hOutput->SetText(m_hOutput->GetText().substr(500)); if (!Application()->IsOpen()) return; if (IsVisible()) Layout(); } bool CPanel_Console::KeyPressed(int code, bool bCtrlDown) { if (!IsVisible()) return false; if (m_asHistory.size()) { if (code == TINKER_KEY_DOWN) { if (m_iHistory >= 0 && m_iHistory < (int)m_asHistory.size() - 1) { m_iHistory++; m_hInput->SetText(m_asHistory[m_iHistory]); m_hInput->SetCursorPosition(-1); } else if (m_iHistory == (int)m_asHistory.size() - 1) { m_iHistory = -1; m_hInput->SetText(""); } } else if (code == TINKER_KEY_UP) { if (m_iHistory == -1) m_iHistory = m_asHistory.size() - 1; else if (m_iHistory > 0) m_iHistory--; m_hInput->SetText(m_asHistory[m_iHistory]); m_hInput->SetCursorPosition(-1); } else m_iHistory = -1; } if (code == TINKER_KEY_ENTER || code == TINKER_KEY_KP_ENTER) { tstring sText = m_hInput->GetText(); m_hInput->SetText(""); PrintConsole(tstring("--> ") + sText + "\n"); MonitorWindow()->GetViewback()->SendConsoleCommand(sText.c_str()); if (trim(sText).length()) m_asHistory.push_back(trim(sText)); m_iHistory = -1; return true; } bool bReturn = BaseClass::KeyPressed(code, bCtrlDown); if (bReturn && !(code == TINKER_KEY_ENTER || code == TINKER_KEY_KP_ENTER)) return true; return false; } <|endoftext|>
<commit_before>/* * * Copyright 2017 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <grpc/support/port_platform.h> #include "src/core/lib/iomgr/port.h" #include <grpc/support/alloc.h> #include <grpc/support/log.h> #include "src/core/lib/debug/trace.h" #include "src/core/lib/iomgr/iomgr_custom.h" #include "src/core/lib/iomgr/timer.h" #include "src/core/lib/iomgr/timer_custom.h" static grpc_custom_timer_vtable* custom_timer_impl; void grpc_custom_timer_callback(grpc_custom_timer* t, grpc_error* error) { GRPC_CUSTOM_IOMGR_ASSERT_SAME_THREAD(); grpc_core::ExecCtx exec_ctx; grpc_timer* timer = t->original; GPR_ASSERT(timer->pending); timer->pending = 0; GRPC_CLOSURE_SCHED(timer->closure, GRPC_ERROR_NONE); custom_timer_impl->stop(t); gpr_free(t); } static void timer_init(grpc_timer* timer, grpc_millis deadline, grpc_closure* closure) { uint64_t timeout; GRPC_CUSTOM_IOMGR_ASSERT_SAME_THREAD(); grpc_millis now = grpc_core::ExecCtx::Get()->Now(); if (deadline <= grpc_core::ExecCtx::Get()->Now()) { GRPC_CLOSURE_SCHED(closure, GRPC_ERROR_NONE); timer->pending = false; return; } else { timeout = deadline - now; } timer->pending = true; timer->closure = closure; grpc_custom_timer* timer_wrapper = (grpc_custom_timer*)gpr_malloc(sizeof(grpc_custom_timer)); timer_wrapper->timeout_ms = timeout; timer->custom_timer = (void*)timer_wrapper; timer_wrapper->original = timer; custom_timer_impl->start(timer_wrapper); } static void timer_cancel(grpc_timer* timer) { GRPC_CUSTOM_IOMGR_ASSERT_SAME_THREAD(); grpc_custom_timer* tw = (grpc_custom_timer*)timer->custom_timer; if (timer->pending) { timer->pending = 0; GRPC_CLOSURE_SCHED(timer->closure, GRPC_ERROR_CANCELLED); custom_timer_impl->stop(tw); gpr_free(tw); } } static grpc_timer_check_result timer_check(grpc_millis* next) { return GRPC_TIMERS_NOT_CHECKED; } static void timer_list_init() {} static void timer_list_shutdown() {} static void timer_consume_kick(void) {} static grpc_timer_vtable custom_timer_vtable = { timer_init, timer_cancel, timer_check, timer_list_init, timer_list_shutdown, timer_consume_kick}; void grpc_custom_timer_init(grpc_custom_timer_vtable* impl) { custom_timer_impl = impl; grpc_set_timer_impl(&custom_timer_vtable); } <commit_msg>Create App context callback for timer custom<commit_after>/* * * Copyright 2017 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <grpc/support/port_platform.h> #include "src/core/lib/iomgr/port.h" #include <grpc/support/alloc.h> #include <grpc/support/log.h> #include "src/core/lib/debug/trace.h" #include "src/core/lib/iomgr/iomgr_custom.h" #include "src/core/lib/iomgr/timer.h" #include "src/core/lib/iomgr/timer_custom.h" static grpc_custom_timer_vtable* custom_timer_impl; void grpc_custom_timer_callback(grpc_custom_timer* t, grpc_error* error) { GRPC_CUSTOM_IOMGR_ASSERT_SAME_THREAD(); grpc_core::ApplicationCallbackExecCtx callback_exec_ctx; grpc_core::ExecCtx exec_ctx; grpc_timer* timer = t->original; GPR_ASSERT(timer->pending); timer->pending = 0; GRPC_CLOSURE_SCHED(timer->closure, GRPC_ERROR_NONE); custom_timer_impl->stop(t); gpr_free(t); } static void timer_init(grpc_timer* timer, grpc_millis deadline, grpc_closure* closure) { uint64_t timeout; GRPC_CUSTOM_IOMGR_ASSERT_SAME_THREAD(); grpc_millis now = grpc_core::ExecCtx::Get()->Now(); if (deadline <= grpc_core::ExecCtx::Get()->Now()) { GRPC_CLOSURE_SCHED(closure, GRPC_ERROR_NONE); timer->pending = false; return; } else { timeout = deadline - now; } timer->pending = true; timer->closure = closure; grpc_custom_timer* timer_wrapper = (grpc_custom_timer*)gpr_malloc(sizeof(grpc_custom_timer)); timer_wrapper->timeout_ms = timeout; timer->custom_timer = (void*)timer_wrapper; timer_wrapper->original = timer; custom_timer_impl->start(timer_wrapper); } static void timer_cancel(grpc_timer* timer) { GRPC_CUSTOM_IOMGR_ASSERT_SAME_THREAD(); grpc_custom_timer* tw = (grpc_custom_timer*)timer->custom_timer; if (timer->pending) { timer->pending = 0; GRPC_CLOSURE_SCHED(timer->closure, GRPC_ERROR_CANCELLED); custom_timer_impl->stop(tw); gpr_free(tw); } } static grpc_timer_check_result timer_check(grpc_millis* next) { return GRPC_TIMERS_NOT_CHECKED; } static void timer_list_init() {} static void timer_list_shutdown() {} static void timer_consume_kick(void) {} static grpc_timer_vtable custom_timer_vtable = { timer_init, timer_cancel, timer_check, timer_list_init, timer_list_shutdown, timer_consume_kick}; void grpc_custom_timer_init(grpc_custom_timer_vtable* impl) { custom_timer_impl = impl; grpc_set_timer_impl(&custom_timer_vtable); } <|endoftext|>
<commit_before>#include "StringTools.h" #include <string> #include <sstream> #include <algorithm> #include <string> #include <vector> #include <iterator> using namespace std; using namespace nspace::stringtools; StringToken::StringToken(std::istream & stream):stream(stream){} bool StringToken::next(){ word=stringtools::nextToken(stream); if(word=="")return false; return true; } StringToken:: operator bool(){ return stream.good(); } string nspace::stringtools::nextToken(std::istream & stream){ static string newline="\n"; static string empty=""; bool stop=false; while(!stop){ char c = stream.peek(); switch(c){ case '\n': case '\r': stream.ignore(); return newline; case '\t': case ' ': stream.ignore(); if(!stream)return empty; break; default: stop = true; break; }; } string tok; stream >> tok; return tok; } std::vector<std::string> nspace::stringtools::split(const std::string & str, const char separator){ std::vector<std::string> result; std::stringstream stream(str); std::string item; while(getline(stream,item,separator)){ result.push_back(item); } return result; } std::vector<std::string> nspace::stringtools::split(istringstream & stream){ vector<string> tokens; copy(istream_iterator<string>(stream), istream_iterator<string>(), back_inserter<vector<string> >(tokens)); return tokens; } std::vector<std::string> nspace::stringtools::split(const std::string & str){ istringstream stream(str); return split(stream); } std::string nspace::stringtools::trim(std::stringstream & stream){ return trim(stream.str()); } std::string nspace::stringtools::trimFront(const std::string & str){ int front=0; bool isWhitespace; bool allWhitespace=true; do{ isWhitespace=false; switch(str[front]){ case ' ': case '\t': case '\n': case '\r': isWhitespace=true; break; default: allWhitespace = false; } front++; } while(isWhitespace && front < str.size()); if(allWhitespace)return ""; return str.substr(front-1); } std::string nspace::stringtools::trimBack(const std::string & str){ int back=str.size()-1; if(back < 0)return ""; bool isWhitespace; bool allWhitespace=true; do{ isWhitespace=false; switch(str[back]){ case ' ': case '\t': case '\n': case '\r': isWhitespace=true; break; default: allWhitespace = false; } back--; }while(isWhitespace && back >=0); if(allWhitespace)return ""; return str.substr(0,back+2); } std::string nspace::stringtools::trim(const std::string & str){ return trimFront(trimBack(str)); } bool nspace::stringtools::startsWith(const std::string & subject,const std::string & what){ if(subject.size()<what.size())return false; int i=0; for(int i=0; i < what.size(); i++){ if(what[i]!=subject[i])return false; }; return true; } bool nspace::stringtools::startWithIgnoreCase(const std::string &subject, const std::string & what){ auto s =toLowerCase(subject); auto w = toLowerCase(what); return startsWith(s,w); } std::string nspace::stringtools::toLowerCase(const std::string & original){ std::string data = original; std::transform(data.begin(), data.end(), data.begin(), ::tolower); return data; } std::string nspace::stringtools::toUpperCase(const std::string & original){ std::string data = original; std::transform(data.begin(), data.end(), data.begin(), ::toupper); return data; } bool nspace::stringtools::contains(const std::string & original, const std::string & search){ if( original.find(search) > original.size())return false; return true; } bool nspace::stringtools:: containsIgnoreCase(const std::string & original, const std::string & search){ string ori = toLowerCase(original); string src = toLowerCase(search); if( ori.find(src) > ori.size())return false; return true; } std::string nspace::stringtools:: operator +(const std::string & a, const std::string & b){ std::string result = ""; result.append(a); result.append(b); return result; } std::string nspace::stringtools:: operator +(const std::string &a, const char * b){ return a+std::string(b); } std::string nspace::stringtools::operator +(const char * a, const std::string &b){ return std::string(a)+b; } std::string nspace::stringtools::repeat(const std::string &str, unsigned int n){ std::stringstream ss; for(unsigned int i=0; i < n; i++){ ss << str; } return ss.str(); } std::string nspace::stringtools::replace(std::string original, const std::string & search, const std::string & replacement){ if( original.find(search) > original.size())return original; return original.replace(original.find(search), replacement.size()-1, replacement); } std::string nspace::stringtools::spaces(unsigned int n){ return repeat(" ",n); }<commit_msg>fixed a gcc warning<commit_after>#include "StringTools.h" #include <string> #include <sstream> #include <algorithm> #include <string> #include <vector> #include <iterator> using namespace std; using namespace nspace::stringtools; StringToken::StringToken(std::istream & stream):stream(stream){} bool StringToken::next(){ word=stringtools::nextToken(stream); if(word=="")return false; return true; } StringToken:: operator bool(){ return stream.good(); } string nspace::stringtools::nextToken(std::istream & stream){ static string newline="\n"; static string empty=""; bool stop=false; while(!stop){ char c = stream.peek(); switch(c){ case '\n': case '\r': stream.ignore(); return newline; case '\t': case ' ': stream.ignore(); if(!stream)return empty; break; default: stop = true; break; }; } string tok; stream >> tok; return tok; } std::vector<std::string> nspace::stringtools::split(const std::string & str, const char separator){ std::vector<std::string> result; std::stringstream stream(str); std::string item; while(getline(stream,item,separator)){ result.push_back(item); } return result; } std::vector<std::string> nspace::stringtools::split(istringstream & stream){ vector<string> tokens; copy(istream_iterator<string>(stream), istream_iterator<string>(), back_inserter<vector<string> >(tokens)); return tokens; } std::vector<std::string> nspace::stringtools::split(const std::string & str){ istringstream stream(str); return split(stream); } std::string nspace::stringtools::trim(std::stringstream & stream){ return trim(stream.str()); } std::string nspace::stringtools::trimFront(const std::string & str){ int front=0; bool isWhitespace; bool allWhitespace=true; do{ isWhitespace=false; switch(str[front]){ case ' ': case '\t': case '\n': case '\r': isWhitespace=true; break; default: allWhitespace = false; } front++; } while(isWhitespace && front < str.size()); if(allWhitespace)return ""; return str.substr(front-1); } std::string nspace::stringtools::trimBack(const std::string & str){ int back=str.size()-1; if(back < 0)return ""; bool isWhitespace; bool allWhitespace=true; do{ isWhitespace=false; switch(str[back]){ case ' ': case '\t': case '\n': case '\r': isWhitespace=true; break; default: allWhitespace = false; } back--; }while(isWhitespace && back >=0); if(allWhitespace)return ""; return str.substr(0,back+2); } std::string nspace::stringtools::trim(const std::string & str){ return trimFront(trimBack(str)); } bool nspace::stringtools::startsWith(const std::string & subject,const std::string & what){ if(subject.size()<what.size())return false; for(int i=0; i < what.size(); i++){ if(what[i]!=subject[i])return false; }; return true; } bool nspace::stringtools::startWithIgnoreCase(const std::string &subject, const std::string & what){ auto s =toLowerCase(subject); auto w = toLowerCase(what); return startsWith(s,w); } std::string nspace::stringtools::toLowerCase(const std::string & original){ std::string data = original; std::transform(data.begin(), data.end(), data.begin(), ::tolower); return data; } std::string nspace::stringtools::toUpperCase(const std::string & original){ std::string data = original; std::transform(data.begin(), data.end(), data.begin(), ::toupper); return data; } bool nspace::stringtools::contains(const std::string & original, const std::string & search){ if( original.find(search) > original.size())return false; return true; } bool nspace::stringtools:: containsIgnoreCase(const std::string & original, const std::string & search){ string ori = toLowerCase(original); string src = toLowerCase(search); if( ori.find(src) > ori.size())return false; return true; } std::string nspace::stringtools:: operator +(const std::string & a, const std::string & b){ std::string result = ""; result.append(a); result.append(b); return result; } std::string nspace::stringtools:: operator +(const std::string &a, const char * b){ return a+std::string(b); } std::string nspace::stringtools::operator +(const char * a, const std::string &b){ return std::string(a)+b; } std::string nspace::stringtools::repeat(const std::string &str, unsigned int n){ std::stringstream ss; for(unsigned int i=0; i < n; i++){ ss << str; } return ss.str(); } std::string nspace::stringtools::replace(std::string original, const std::string & search, const std::string & replacement){ if( original.find(search) > original.size())return original; return original.replace(original.find(search), replacement.size()-1, replacement); } std::string nspace::stringtools::spaces(unsigned int n){ return repeat(" ",n); }<|endoftext|>
<commit_before>/* * Copyright 2014-2021 Real Logic Limited. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "AeronArchive.h" using namespace aeron; using namespace aeron::archive::client; AeronArchive::AsyncConnect::AsyncConnect( Context_t &context, std::shared_ptr<Aeron> aeron, std::int64_t subscriptionId, std::int64_t publicationId, const long long deadlineNs) : m_nanoClock(systemNanoClock), m_ctx(std::unique_ptr<Context_t>(new Context_t(context))), m_aeron(std::move(aeron)), m_subscriptionId(subscriptionId), m_publicationId(publicationId), m_deadlineNs(deadlineNs) { } std::shared_ptr<AeronArchive> AeronArchive::AsyncConnect::poll() { if (m_nanoClock() > m_deadlineNs) { throw TimeoutException( "Archive connect timeout: step=" + std::to_string(m_step) + (m_step < 2 ? " publication.uri=" + (m_publication ? m_publication->channel() : "<undiscovered>") : " subscription.uri=" + (m_subscription ? m_subscription->channel() : "<undiscovered>")), SOURCEINFO); } if (!m_subscription) { m_subscription = m_aeron->findSubscription(m_subscriptionId); } if (!m_controlResponsePoller && m_subscription) { m_controlResponsePoller = std::unique_ptr<ControlResponsePoller>(new ControlResponsePoller(m_subscription)); } if (!m_publication) { m_publication = m_aeron->findExclusivePublication(m_publicationId); } if (!m_archiveProxy && m_publication) { m_archiveProxy = std::unique_ptr<ArchiveProxy>(new ArchiveProxy(m_publication)); } if (0 == m_step && m_archiveProxy) { if (!m_archiveProxy->publication()->isConnected()) { return std::shared_ptr<AeronArchive>(); } m_step = 1; } if (1 == m_step && m_subscription) { std::string controlResponseChannel = m_subscription->tryResolveChannelEndpointPort(); if (controlResponseChannel.empty()) { return std::shared_ptr<AeronArchive>(); } auto encodedCredentials = m_ctx->credentialsSupplier().m_encodedCredentials(); m_correlationId = m_aeron->nextCorrelationId(); if (!m_archiveProxy->tryConnect( controlResponseChannel,m_ctx->controlResponseStreamId(), encodedCredentials, m_correlationId)) { m_ctx->credentialsSupplier().m_onFree(encodedCredentials); return std::shared_ptr<AeronArchive>(); } m_ctx->credentialsSupplier().m_onFree(encodedCredentials); m_step = 2; } if (2 == m_step && m_controlResponsePoller) { if (!m_subscription->isConnected()) { return std::shared_ptr<AeronArchive>(); } m_step = 3; } if (5 == m_step && m_controlResponsePoller) { if (!m_archiveProxy->tryChallengeResponse( m_encodedCredentialsFromChallenge, m_correlationId, m_challengeControlSessionId)) { return std::shared_ptr<AeronArchive>(); } m_ctx->credentialsSupplier().m_onFree(m_encodedCredentialsFromChallenge); m_encodedCredentialsFromChallenge.first = nullptr; m_encodedCredentialsFromChallenge.second = 0; m_step = 6; } if (m_controlResponsePoller) { m_controlResponsePoller->poll(); if (m_controlResponsePoller->isPollComplete() && m_controlResponsePoller->correlationId() == m_correlationId) { const std::int64_t sessionId = m_controlResponsePoller->controlSessionId(); if (m_controlResponsePoller->wasChallenged()) { m_encodedCredentialsFromChallenge = m_ctx->credentialsSupplier().m_onChallenge( m_controlResponsePoller->encodedChallenge()); m_correlationId = m_aeron->nextCorrelationId(); m_challengeControlSessionId = sessionId; m_step = 5; } else { if (!m_controlResponsePoller->isCodeOk()) { if (m_controlResponsePoller->isCodeError()) { m_archiveProxy->closeSession(sessionId); throw ArchiveException( static_cast<std::int32_t>(m_controlResponsePoller->relevantId()), "error: " + m_controlResponsePoller->errorMessage(), SOURCEINFO); } throw ArchiveException( "unexpected response: code=" + std::to_string(m_controlResponsePoller->codeValue()), SOURCEINFO); } m_archiveProxy->keepAlive(aeron::NULL_VALUE, sessionId); std::unique_ptr<RecordingDescriptorPoller> recordingDescriptorPoller( new RecordingDescriptorPoller(m_subscription, m_ctx->errorHandler(), sessionId)); std::unique_ptr<RecordingSubscriptionDescriptorPoller> recordingSubscriptionDescriptorPoller( new RecordingSubscriptionDescriptorPoller(m_subscription, m_ctx->errorHandler(), sessionId)); return std::make_shared<AeronArchive>( std::move(m_ctx), std::move(m_archiveProxy), std::move(m_controlResponsePoller), std::move(recordingDescriptorPoller), std::move(recordingSubscriptionDescriptorPoller), m_aeron, sessionId); } } } return std::shared_ptr<AeronArchive>(); } AeronArchive::AeronArchive( std::unique_ptr<Context_t> ctx, std::unique_ptr<ArchiveProxy> archiveProxy, std::unique_ptr<ControlResponsePoller> controlResponsePoller, std::unique_ptr<RecordingDescriptorPoller> recordingDescriptorPoller, std::unique_ptr<RecordingSubscriptionDescriptorPoller> recordingSubscriptionDescriptorPoller, std::shared_ptr<Aeron> aeron, std::int64_t controlSessionId) : m_ctx(std::move(ctx)), m_archiveProxy(std::move(archiveProxy)), m_controlResponsePoller(std::move(controlResponsePoller)), m_recordingDescriptorPoller(std::move(recordingDescriptorPoller)), m_recordingSubscriptionDescriptorPoller(std::move(recordingSubscriptionDescriptorPoller)), m_aeron(std::move(aeron)), m_nanoClock(systemNanoClock), m_controlSessionId(controlSessionId), m_messageTimeoutNs(m_ctx->messageTimeoutNs()) { } AeronArchive::~AeronArchive() { if (m_archiveProxy->publication()->isConnected()) { m_archiveProxy->closeSession(m_controlSessionId); } } std::shared_ptr<AeronArchive::AsyncConnect> AeronArchive::asyncConnect(AeronArchive::Context_t &ctx) { ctx.conclude(); std::shared_ptr<Aeron> aeron = ctx.aeron(); const std::int64_t subscriptionId = aeron->addSubscription( ctx.controlResponseChannel(), ctx.controlResponseStreamId()); const std::int64_t publicationId = aeron->addExclusivePublication( ctx.controlRequestChannel(), ctx.controlRequestStreamId()); const long long deadlineNs = systemNanoClock() + ctx.messageTimeoutNs(); return std::make_shared<AeronArchive::AsyncConnect>(ctx, aeron, subscriptionId, publicationId, deadlineNs); } std::string AeronArchive::version() { return std::string("aeron version " AERON_VERSION_TXT " built " __DATE__ " " __TIME__); } <commit_msg>[C++] Improve error message when awaiting pub and sub find operations. PR #1196.<commit_after>/* * Copyright 2014-2021 Real Logic Limited. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "AeronArchive.h" using namespace aeron; using namespace aeron::archive::client; AeronArchive::AsyncConnect::AsyncConnect( Context_t &context, std::shared_ptr<Aeron> aeron, std::int64_t subscriptionId, std::int64_t publicationId, const long long deadlineNs) : m_nanoClock(systemNanoClock), m_ctx(std::unique_ptr<Context_t>(new Context_t(context))), m_aeron(std::move(aeron)), m_subscriptionId(subscriptionId), m_publicationId(publicationId), m_deadlineNs(deadlineNs) { } std::shared_ptr<AeronArchive> AeronArchive::AsyncConnect::poll() { if (m_nanoClock() > m_deadlineNs) { throw TimeoutException( "Archive connect timeout: step=" + std::to_string(m_step) + (m_step < 2 ? " publication.uri=" + (m_publication ? m_publication->channel() : "<awaiting find operation>") : " subscription.uri=" + (m_subscription ? m_subscription->channel() : "<awaiting find operation>")), SOURCEINFO); } if (!m_subscription) { m_subscription = m_aeron->findSubscription(m_subscriptionId); } if (!m_controlResponsePoller && m_subscription) { m_controlResponsePoller = std::unique_ptr<ControlResponsePoller>(new ControlResponsePoller(m_subscription)); } if (!m_publication) { m_publication = m_aeron->findExclusivePublication(m_publicationId); } if (!m_archiveProxy && m_publication) { m_archiveProxy = std::unique_ptr<ArchiveProxy>(new ArchiveProxy(m_publication)); } if (0 == m_step && m_archiveProxy) { if (!m_archiveProxy->publication()->isConnected()) { return std::shared_ptr<AeronArchive>(); } m_step = 1; } if (1 == m_step && m_subscription) { std::string controlResponseChannel = m_subscription->tryResolveChannelEndpointPort(); if (controlResponseChannel.empty()) { return std::shared_ptr<AeronArchive>(); } auto encodedCredentials = m_ctx->credentialsSupplier().m_encodedCredentials(); m_correlationId = m_aeron->nextCorrelationId(); if (!m_archiveProxy->tryConnect( controlResponseChannel,m_ctx->controlResponseStreamId(), encodedCredentials, m_correlationId)) { m_ctx->credentialsSupplier().m_onFree(encodedCredentials); return std::shared_ptr<AeronArchive>(); } m_ctx->credentialsSupplier().m_onFree(encodedCredentials); m_step = 2; } if (2 == m_step && m_controlResponsePoller) { if (!m_subscription->isConnected()) { return std::shared_ptr<AeronArchive>(); } m_step = 3; } if (5 == m_step && m_controlResponsePoller) { if (!m_archiveProxy->tryChallengeResponse( m_encodedCredentialsFromChallenge, m_correlationId, m_challengeControlSessionId)) { return std::shared_ptr<AeronArchive>(); } m_ctx->credentialsSupplier().m_onFree(m_encodedCredentialsFromChallenge); m_encodedCredentialsFromChallenge.first = nullptr; m_encodedCredentialsFromChallenge.second = 0; m_step = 6; } if (m_controlResponsePoller) { m_controlResponsePoller->poll(); if (m_controlResponsePoller->isPollComplete() && m_controlResponsePoller->correlationId() == m_correlationId) { const std::int64_t sessionId = m_controlResponsePoller->controlSessionId(); if (m_controlResponsePoller->wasChallenged()) { m_encodedCredentialsFromChallenge = m_ctx->credentialsSupplier().m_onChallenge( m_controlResponsePoller->encodedChallenge()); m_correlationId = m_aeron->nextCorrelationId(); m_challengeControlSessionId = sessionId; m_step = 5; } else { if (!m_controlResponsePoller->isCodeOk()) { if (m_controlResponsePoller->isCodeError()) { m_archiveProxy->closeSession(sessionId); throw ArchiveException( static_cast<std::int32_t>(m_controlResponsePoller->relevantId()), "error: " + m_controlResponsePoller->errorMessage(), SOURCEINFO); } throw ArchiveException( "unexpected response: code=" + std::to_string(m_controlResponsePoller->codeValue()), SOURCEINFO); } m_archiveProxy->keepAlive(aeron::NULL_VALUE, sessionId); std::unique_ptr<RecordingDescriptorPoller> recordingDescriptorPoller( new RecordingDescriptorPoller(m_subscription, m_ctx->errorHandler(), sessionId)); std::unique_ptr<RecordingSubscriptionDescriptorPoller> recordingSubscriptionDescriptorPoller( new RecordingSubscriptionDescriptorPoller(m_subscription, m_ctx->errorHandler(), sessionId)); return std::make_shared<AeronArchive>( std::move(m_ctx), std::move(m_archiveProxy), std::move(m_controlResponsePoller), std::move(recordingDescriptorPoller), std::move(recordingSubscriptionDescriptorPoller), m_aeron, sessionId); } } } return std::shared_ptr<AeronArchive>(); } AeronArchive::AeronArchive( std::unique_ptr<Context_t> ctx, std::unique_ptr<ArchiveProxy> archiveProxy, std::unique_ptr<ControlResponsePoller> controlResponsePoller, std::unique_ptr<RecordingDescriptorPoller> recordingDescriptorPoller, std::unique_ptr<RecordingSubscriptionDescriptorPoller> recordingSubscriptionDescriptorPoller, std::shared_ptr<Aeron> aeron, std::int64_t controlSessionId) : m_ctx(std::move(ctx)), m_archiveProxy(std::move(archiveProxy)), m_controlResponsePoller(std::move(controlResponsePoller)), m_recordingDescriptorPoller(std::move(recordingDescriptorPoller)), m_recordingSubscriptionDescriptorPoller(std::move(recordingSubscriptionDescriptorPoller)), m_aeron(std::move(aeron)), m_nanoClock(systemNanoClock), m_controlSessionId(controlSessionId), m_messageTimeoutNs(m_ctx->messageTimeoutNs()) { } AeronArchive::~AeronArchive() { if (m_archiveProxy->publication()->isConnected()) { m_archiveProxy->closeSession(m_controlSessionId); } } std::shared_ptr<AeronArchive::AsyncConnect> AeronArchive::asyncConnect(AeronArchive::Context_t &ctx) { ctx.conclude(); std::shared_ptr<Aeron> aeron = ctx.aeron(); const std::int64_t subscriptionId = aeron->addSubscription( ctx.controlResponseChannel(), ctx.controlResponseStreamId()); const std::int64_t publicationId = aeron->addExclusivePublication( ctx.controlRequestChannel(), ctx.controlRequestStreamId()); const long long deadlineNs = systemNanoClock() + ctx.messageTimeoutNs(); return std::make_shared<AeronArchive::AsyncConnect>(ctx, aeron, subscriptionId, publicationId, deadlineNs); } std::string AeronArchive::version() { return std::string("aeron version " AERON_VERSION_TXT " built " __DATE__ " " __TIME__); } <|endoftext|>
<commit_before>/* * Copyright (C) 2006, 2007, 2008, 2009, 2010 Stephen F. Booth <me@sbooth.org> * 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. * - 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. * - Neither the name of Stephen F. Booth nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * 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 <taglib/mpcfile.h> #include <taglib/tag.h> #include "AudioEngineDefines.h" #include "MusepackMetadata.h" #include "CreateDisplayNameForURL.h" #pragma mark Static Methods CFArrayRef MusepackMetadata::CreateSupportedFileExtensions() { CFStringRef supportedExtensions [] = { CFSTR("mpc") }; return CFArrayCreate(kCFAllocatorDefault, reinterpret_cast<const void **>(supportedExtensions), 1, &kCFTypeArrayCallBacks); } CFArrayRef MusepackMetadata::CreateSupportedMIMETypes() { CFStringRef supportedMIMETypes [] = { CFSTR("audio/musepack") }; return CFArrayCreate(kCFAllocatorDefault, reinterpret_cast<const void **>(supportedMIMETypes), 1, &kCFTypeArrayCallBacks); } bool MusepackMetadata::HandlesFilesWithExtension(CFStringRef extension) { assert(NULL != extension); if(kCFCompareEqualTo == CFStringCompare(extension, CFSTR("mpc"), kCFCompareCaseInsensitive)) return true; return false; } bool MusepackMetadata::HandlesMIMEType(CFStringRef mimeType) { assert(NULL != mimeType); if(kCFCompareEqualTo == CFStringCompare(mimeType, CFSTR("audio/mpeg"), kCFCompareCaseInsensitive)) return true; return false; } #pragma mark Creation and Destruction MusepackMetadata::MusepackMetadata(CFURLRef url) : AudioMetadata(url) {} MusepackMetadata::~MusepackMetadata() {} #pragma mark Functionality bool MusepackMetadata::ReadMetadata(CFErrorRef *error) { // Start from scratch CFDictionaryRemoveAllValues(mMetadata); UInt8 buf [PATH_MAX]; if(false == CFURLGetFileSystemRepresentation(mURL, false, buf, PATH_MAX)) return false; TagLib::MPC::File file(reinterpret_cast<const char *>(buf), false); if(!file.isValid()) { if(NULL != error) { CFMutableDictionaryRef errorDictionary = CFDictionaryCreateMutable(kCFAllocatorDefault, 32, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); CFStringRef displayName = CreateDisplayNameForURL(mURL); CFStringRef errorString = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFCopyLocalizedString(CFSTR("The file \"%@\" is not a valid Musepack file."), ""), displayName); CFDictionarySetValue(errorDictionary, kCFErrorLocalizedDescriptionKey, errorString); CFDictionarySetValue(errorDictionary, kCFErrorLocalizedFailureReasonKey, CFCopyLocalizedString(CFSTR("Not a Musepack file"), "")); CFDictionarySetValue(errorDictionary, kCFErrorLocalizedRecoverySuggestionKey, CFCopyLocalizedString(CFSTR("The file's extension may not match the file's type."), "")); CFRelease(errorString), errorString = NULL; CFRelease(displayName), displayName = NULL; *error = CFErrorCreate(kCFAllocatorDefault, AudioMetadataErrorDomain, AudioMetadataInputOutputError, errorDictionary); CFRelease(errorDictionary), errorDictionary = NULL; } return false; } // Album title if(!file.tag()->album().isNull()) { CFStringRef str = CFStringCreateWithCString(kCFAllocatorDefault, file.tag()->album().toCString(true), kCFStringEncodingUTF8); SetAlbumTitle(str); CFRelease(str), str = NULL; } // Artist if(!file.tag()->artist().isNull()) { CFStringRef str = CFStringCreateWithCString(kCFAllocatorDefault, file.tag()->artist().toCString(true), kCFStringEncodingUTF8); SetArtist(str); CFRelease(str), str = NULL; } // Genre if(!file.tag()->genre().isNull()) { CFStringRef str = CFStringCreateWithCString(kCFAllocatorDefault, file.tag()->genre().toCString(true), kCFStringEncodingUTF8); SetGenre(str); CFRelease(str), str = NULL; } // Year if(file.tag()->year()) { CFStringRef str = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%d"), file.tag()->year()); SetReleaseDate(str); CFRelease(str), str = NULL; } // Comment if(!file.tag()->comment().isNull()) { CFStringRef str = CFStringCreateWithCString(kCFAllocatorDefault, file.tag()->comment().toCString(true), kCFStringEncodingUTF8); SetComment(str); CFRelease(str), str = NULL; } // Track title if(!file.tag()->title().isNull()) { CFStringRef str = CFStringCreateWithCString(kCFAllocatorDefault, file.tag()->title().toCString(true), kCFStringEncodingUTF8); SetTitle(str); CFRelease(str), str = NULL; } // Track number if(file.tag()->track()) { int trackNum = file.tag()->track(); CFNumberRef num = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &trackNum); SetTrackNumber(num); CFRelease(num), num = NULL; } return true; } bool MusepackMetadata::WriteMetadata(CFErrorRef *error) { UInt8 buf [PATH_MAX]; if(false == CFURLGetFileSystemRepresentation(mURL, false, buf, PATH_MAX)) return false; TagLib::MPC::File file(reinterpret_cast<const char *>(buf), false); if(!file.isValid()) { if(error) { CFMutableDictionaryRef errorDictionary = CFDictionaryCreateMutable(kCFAllocatorDefault, 32, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); CFStringRef displayName = CreateDisplayNameForURL(mURL); CFStringRef errorString = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFCopyLocalizedString(CFSTR("The file \"%@\" is not a valid Musepack file."), ""), displayName); CFDictionarySetValue(errorDictionary, kCFErrorLocalizedDescriptionKey, errorString); CFDictionarySetValue(errorDictionary, kCFErrorLocalizedFailureReasonKey, CFCopyLocalizedString(CFSTR("Not a Musepack file"), "")); CFDictionarySetValue(errorDictionary, kCFErrorLocalizedRecoverySuggestionKey, CFCopyLocalizedString(CFSTR("The file's extension may not match the file's type."), "")); CFRelease(errorString), errorString = NULL; CFRelease(displayName), displayName = NULL; *error = CFErrorCreate(kCFAllocatorDefault, AudioMetadataErrorDomain, AudioMetadataInputOutputError, errorDictionary); CFRelease(errorDictionary), errorDictionary = NULL; } return false; } // Album title CFStringRef str = GetAlbumTitle(); if(str) { CFIndex cStringSize = CFStringGetMaximumSizeForEncoding(CFStringGetLength(str), kCFStringEncodingUTF8); char cString [cStringSize + 1]; if(false == CFStringGetCString(str, cString, cStringSize + 1, kCFStringEncodingUTF8)) { ERR("CFStringGetCString failed"); return false; } file.tag()->setAlbum(TagLib::String(cString, TagLib::String::UTF8)); } else file.tag()->setAlbum(TagLib::String()); // Artist str = GetArtist(); if(str) { CFIndex cStringSize = CFStringGetMaximumSizeForEncoding(CFStringGetLength(str), kCFStringEncodingUTF8); char cString [cStringSize + 1]; if(false == CFStringGetCString(str, cString, cStringSize + 1, kCFStringEncodingUTF8)) { ERR("CFStringGetCString failed"); return false; } file.tag()->setArtist(TagLib::String(cString, TagLib::String::UTF8)); } else file.tag()->setArtist(TagLib::String()); // Genre str = GetGenre(); if(str) { CFIndex cStringSize = CFStringGetMaximumSizeForEncoding(CFStringGetLength(str), kCFStringEncodingUTF8); char cString [cStringSize + 1]; if(false == CFStringGetCString(str, cString, cStringSize + 1, kCFStringEncodingUTF8)) { ERR("CFStringGetCString failed"); return false; } file.tag()->setGenre(TagLib::String(cString, TagLib::String::UTF8)); } else file.tag()->setGenre(TagLib::String()); // Year str = GetReleaseDate(); if(str) { CFIndex cStringSize = CFStringGetMaximumSizeForEncoding(CFStringGetLength(str), kCFStringEncodingUTF8); char cString [cStringSize + 1]; if(false == CFStringGetCString(str, cString, cStringSize + 1, kCFStringEncodingUTF8)) { ERR("CFStringGetCString failed"); return false; } file.tag()->setYear(CFStringGetIntValue(str)); } else file.tag()->setYear(0); // Comment str = GetComment(); if(str) { CFIndex cStringSize = CFStringGetMaximumSizeForEncoding(CFStringGetLength(str), kCFStringEncodingUTF8); char cString [cStringSize + 1]; if(false == CFStringGetCString(str, cString, cStringSize + 1, kCFStringEncodingUTF8)) { ERR("CFStringGetCString failed"); return false; } file.tag()->setComment(TagLib::String(cString, TagLib::String::UTF8)); } else file.tag()->setComment(TagLib::String()); // Track title str = GetTitle(); if(str) { CFIndex cStringSize = CFStringGetMaximumSizeForEncoding(CFStringGetLength(str), kCFStringEncodingUTF8); char cString [cStringSize + 1]; if(false == CFStringGetCString(str, cString, cStringSize + 1, kCFStringEncodingUTF8)) { ERR("CFStringGetCString failed"); return false; } file.tag()->setTitle(TagLib::String(cString, TagLib::String::UTF8)); } else file.tag()->setTitle(TagLib::String()); // Track number int trackNum = 0; if(GetTrackNumber()) CFNumberGetValue(GetTrackNumber(), kCFNumberIntType, &trackNum); file.tag()->setTrack(trackNum); if(!file.save()) { if(error) { CFMutableDictionaryRef errorDictionary = CFDictionaryCreateMutable(kCFAllocatorDefault, 32, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); CFStringRef displayName = CreateDisplayNameForURL(mURL); CFStringRef errorString = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFCopyLocalizedString(CFSTR("The file \"%@\" is not a valid Musepack file."), ""), displayName); CFDictionarySetValue(errorDictionary, kCFErrorLocalizedDescriptionKey, errorString); CFDictionarySetValue(errorDictionary, kCFErrorLocalizedFailureReasonKey, CFCopyLocalizedString(CFSTR("Unable to write metadata"), "")); CFDictionarySetValue(errorDictionary, kCFErrorLocalizedRecoverySuggestionKey, CFCopyLocalizedString(CFSTR("The file's extension may not match the file's type."), "")); CFRelease(errorString), errorString = NULL; CFRelease(displayName), displayName = NULL; *error = CFErrorCreate(kCFAllocatorDefault, AudioMetadataErrorDomain, AudioMetadataInputOutputError, errorDictionary); CFRelease(errorDictionary), errorDictionary = NULL; } return false; } return true; } <commit_msg>Use TagLib::String::null<commit_after>/* * Copyright (C) 2006, 2007, 2008, 2009, 2010 Stephen F. Booth <me@sbooth.org> * 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. * - 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. * - Neither the name of Stephen F. Booth nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * 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 <taglib/mpcfile.h> #include <taglib/tag.h> #include "AudioEngineDefines.h" #include "MusepackMetadata.h" #include "CreateDisplayNameForURL.h" #pragma mark Static Methods CFArrayRef MusepackMetadata::CreateSupportedFileExtensions() { CFStringRef supportedExtensions [] = { CFSTR("mpc") }; return CFArrayCreate(kCFAllocatorDefault, reinterpret_cast<const void **>(supportedExtensions), 1, &kCFTypeArrayCallBacks); } CFArrayRef MusepackMetadata::CreateSupportedMIMETypes() { CFStringRef supportedMIMETypes [] = { CFSTR("audio/musepack") }; return CFArrayCreate(kCFAllocatorDefault, reinterpret_cast<const void **>(supportedMIMETypes), 1, &kCFTypeArrayCallBacks); } bool MusepackMetadata::HandlesFilesWithExtension(CFStringRef extension) { assert(NULL != extension); if(kCFCompareEqualTo == CFStringCompare(extension, CFSTR("mpc"), kCFCompareCaseInsensitive)) return true; return false; } bool MusepackMetadata::HandlesMIMEType(CFStringRef mimeType) { assert(NULL != mimeType); if(kCFCompareEqualTo == CFStringCompare(mimeType, CFSTR("audio/mpeg"), kCFCompareCaseInsensitive)) return true; return false; } #pragma mark Creation and Destruction MusepackMetadata::MusepackMetadata(CFURLRef url) : AudioMetadata(url) {} MusepackMetadata::~MusepackMetadata() {} #pragma mark Functionality bool MusepackMetadata::ReadMetadata(CFErrorRef *error) { // Start from scratch CFDictionaryRemoveAllValues(mMetadata); UInt8 buf [PATH_MAX]; if(false == CFURLGetFileSystemRepresentation(mURL, false, buf, PATH_MAX)) return false; TagLib::MPC::File file(reinterpret_cast<const char *>(buf), false); if(!file.isValid()) { if(NULL != error) { CFMutableDictionaryRef errorDictionary = CFDictionaryCreateMutable(kCFAllocatorDefault, 32, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); CFStringRef displayName = CreateDisplayNameForURL(mURL); CFStringRef errorString = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFCopyLocalizedString(CFSTR("The file \"%@\" is not a valid Musepack file."), ""), displayName); CFDictionarySetValue(errorDictionary, kCFErrorLocalizedDescriptionKey, errorString); CFDictionarySetValue(errorDictionary, kCFErrorLocalizedFailureReasonKey, CFCopyLocalizedString(CFSTR("Not a Musepack file"), "")); CFDictionarySetValue(errorDictionary, kCFErrorLocalizedRecoverySuggestionKey, CFCopyLocalizedString(CFSTR("The file's extension may not match the file's type."), "")); CFRelease(errorString), errorString = NULL; CFRelease(displayName), displayName = NULL; *error = CFErrorCreate(kCFAllocatorDefault, AudioMetadataErrorDomain, AudioMetadataInputOutputError, errorDictionary); CFRelease(errorDictionary), errorDictionary = NULL; } return false; } // Album title if(!file.tag()->album().isNull()) { CFStringRef str = CFStringCreateWithCString(kCFAllocatorDefault, file.tag()->album().toCString(true), kCFStringEncodingUTF8); SetAlbumTitle(str); CFRelease(str), str = NULL; } // Artist if(!file.tag()->artist().isNull()) { CFStringRef str = CFStringCreateWithCString(kCFAllocatorDefault, file.tag()->artist().toCString(true), kCFStringEncodingUTF8); SetArtist(str); CFRelease(str), str = NULL; } // Genre if(!file.tag()->genre().isNull()) { CFStringRef str = CFStringCreateWithCString(kCFAllocatorDefault, file.tag()->genre().toCString(true), kCFStringEncodingUTF8); SetGenre(str); CFRelease(str), str = NULL; } // Year if(file.tag()->year()) { CFStringRef str = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%d"), file.tag()->year()); SetReleaseDate(str); CFRelease(str), str = NULL; } // Comment if(!file.tag()->comment().isNull()) { CFStringRef str = CFStringCreateWithCString(kCFAllocatorDefault, file.tag()->comment().toCString(true), kCFStringEncodingUTF8); SetComment(str); CFRelease(str), str = NULL; } // Track title if(!file.tag()->title().isNull()) { CFStringRef str = CFStringCreateWithCString(kCFAllocatorDefault, file.tag()->title().toCString(true), kCFStringEncodingUTF8); SetTitle(str); CFRelease(str), str = NULL; } // Track number if(file.tag()->track()) { int trackNum = file.tag()->track(); CFNumberRef num = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &trackNum); SetTrackNumber(num); CFRelease(num), num = NULL; } return true; } bool MusepackMetadata::WriteMetadata(CFErrorRef *error) { UInt8 buf [PATH_MAX]; if(false == CFURLGetFileSystemRepresentation(mURL, false, buf, PATH_MAX)) return false; TagLib::MPC::File file(reinterpret_cast<const char *>(buf), false); if(!file.isValid()) { if(error) { CFMutableDictionaryRef errorDictionary = CFDictionaryCreateMutable(kCFAllocatorDefault, 32, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); CFStringRef displayName = CreateDisplayNameForURL(mURL); CFStringRef errorString = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFCopyLocalizedString(CFSTR("The file \"%@\" is not a valid Musepack file."), ""), displayName); CFDictionarySetValue(errorDictionary, kCFErrorLocalizedDescriptionKey, errorString); CFDictionarySetValue(errorDictionary, kCFErrorLocalizedFailureReasonKey, CFCopyLocalizedString(CFSTR("Not a Musepack file"), "")); CFDictionarySetValue(errorDictionary, kCFErrorLocalizedRecoverySuggestionKey, CFCopyLocalizedString(CFSTR("The file's extension may not match the file's type."), "")); CFRelease(errorString), errorString = NULL; CFRelease(displayName), displayName = NULL; *error = CFErrorCreate(kCFAllocatorDefault, AudioMetadataErrorDomain, AudioMetadataInputOutputError, errorDictionary); CFRelease(errorDictionary), errorDictionary = NULL; } return false; } // Album title CFStringRef str = GetAlbumTitle(); if(str) { CFIndex cStringSize = CFStringGetMaximumSizeForEncoding(CFStringGetLength(str), kCFStringEncodingUTF8); char cString [cStringSize + 1]; if(false == CFStringGetCString(str, cString, cStringSize + 1, kCFStringEncodingUTF8)) { ERR("CFStringGetCString failed"); return false; } file.tag()->setAlbum(TagLib::String(cString, TagLib::String::UTF8)); } else file.tag()->setAlbum(TagLib::String::null); // Artist str = GetArtist(); if(str) { CFIndex cStringSize = CFStringGetMaximumSizeForEncoding(CFStringGetLength(str), kCFStringEncodingUTF8); char cString [cStringSize + 1]; if(false == CFStringGetCString(str, cString, cStringSize + 1, kCFStringEncodingUTF8)) { ERR("CFStringGetCString failed"); return false; } file.tag()->setArtist(TagLib::String(cString, TagLib::String::UTF8)); } else file.tag()->setArtist(TagLib::String::null); // Genre str = GetGenre(); if(str) { CFIndex cStringSize = CFStringGetMaximumSizeForEncoding(CFStringGetLength(str), kCFStringEncodingUTF8); char cString [cStringSize + 1]; if(false == CFStringGetCString(str, cString, cStringSize + 1, kCFStringEncodingUTF8)) { ERR("CFStringGetCString failed"); return false; } file.tag()->setGenre(TagLib::String(cString, TagLib::String::UTF8)); } else file.tag()->setGenre(TagLib::String::null); // Year str = GetReleaseDate(); if(str) { CFIndex cStringSize = CFStringGetMaximumSizeForEncoding(CFStringGetLength(str), kCFStringEncodingUTF8); char cString [cStringSize + 1]; if(false == CFStringGetCString(str, cString, cStringSize + 1, kCFStringEncodingUTF8)) { ERR("CFStringGetCString failed"); return false; } file.tag()->setYear(CFStringGetIntValue(str)); } else file.tag()->setYear(0); // Comment str = GetComment(); if(str) { CFIndex cStringSize = CFStringGetMaximumSizeForEncoding(CFStringGetLength(str), kCFStringEncodingUTF8); char cString [cStringSize + 1]; if(false == CFStringGetCString(str, cString, cStringSize + 1, kCFStringEncodingUTF8)) { ERR("CFStringGetCString failed"); return false; } file.tag()->setComment(TagLib::String(cString, TagLib::String::UTF8)); } else file.tag()->setComment(TagLib::String::null); // Track title str = GetTitle(); if(str) { CFIndex cStringSize = CFStringGetMaximumSizeForEncoding(CFStringGetLength(str), kCFStringEncodingUTF8); char cString [cStringSize + 1]; if(false == CFStringGetCString(str, cString, cStringSize + 1, kCFStringEncodingUTF8)) { ERR("CFStringGetCString failed"); return false; } file.tag()->setTitle(TagLib::String(cString, TagLib::String::UTF8)); } else file.tag()->setTitle(TagLib::String::null); // Track number int trackNum = 0; if(GetTrackNumber()) CFNumberGetValue(GetTrackNumber(), kCFNumberIntType, &trackNum); file.tag()->setTrack(trackNum); if(!file.save()) { if(error) { CFMutableDictionaryRef errorDictionary = CFDictionaryCreateMutable(kCFAllocatorDefault, 32, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); CFStringRef displayName = CreateDisplayNameForURL(mURL); CFStringRef errorString = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFCopyLocalizedString(CFSTR("The file \"%@\" is not a valid Musepack file."), ""), displayName); CFDictionarySetValue(errorDictionary, kCFErrorLocalizedDescriptionKey, errorString); CFDictionarySetValue(errorDictionary, kCFErrorLocalizedFailureReasonKey, CFCopyLocalizedString(CFSTR("Unable to write metadata"), "")); CFDictionarySetValue(errorDictionary, kCFErrorLocalizedRecoverySuggestionKey, CFCopyLocalizedString(CFSTR("The file's extension may not match the file's type."), "")); CFRelease(errorString), errorString = NULL; CFRelease(displayName), displayName = NULL; *error = CFErrorCreate(kCFAllocatorDefault, AudioMetadataErrorDomain, AudioMetadataInputOutputError, errorDictionary); CFRelease(errorDictionary), errorDictionary = NULL; } return false; } return true; } <|endoftext|>
<commit_before>/* * RToolsInfo.cpp * * Copyright (C) 2009-19 by RStudio, PBC * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include <core/Version.hpp> #include <core/r_util/RToolsInfo.hpp> #include <boost/format.hpp> #include <boost/algorithm/string.hpp> #include <core/Log.hpp> #include <core/http/URL.hpp> #include <core/StringUtils.hpp> #include <core/system/System.hpp> #include <core/system/RegistryKey.hpp> #ifndef KEY_WOW64_32KEY #define KEY_WOW64_32KEY 0x0200 #endif namespace rstudio { namespace core { namespace r_util { namespace { std::string asRBuildPath(const FilePath& filePath) { std::string path = filePath.getAbsolutePath(); boost::algorithm::replace_all(path, "\\", "/"); if (!boost::algorithm::ends_with(path, "/")) path += "/"; return path; } std::vector<std::string> gcc463ClangArgs(const FilePath& installPath) { std::vector<std::string> clangArgs; clangArgs.push_back("-I" + installPath.completeChildPath( "gcc-4.6.3/i686-w64-mingw32/include").getAbsolutePath()); clangArgs.push_back("-I" + installPath.completeChildPath( "gcc-4.6.3/include/c++/4.6.3").getAbsolutePath()); std::string bits = "-I" + installPath.completeChildPath( "gcc-4.6.3/include/c++/4.6.3/i686-w64-mingw32").getAbsolutePath(); #ifdef _WIN64 bits += "/64"; #endif clangArgs.push_back(bits); return clangArgs; } void gcc463Configuration(const FilePath& installPath, std::vector<std::string>* pRelativePathEntries, std::vector<std::string>* pClangArgs) { pRelativePathEntries->push_back("bin"); pRelativePathEntries->push_back("gcc-4.6.3/bin"); *pClangArgs = gcc463ClangArgs(installPath); } } // anonymous namespace RToolsInfo::RToolsInfo(const std::string& name, const FilePath& installPath, bool usingMingwGcc49) : name_(name), installPath_(installPath) { std::string versionMin, versionMax; std::vector<std::string> relativePathEntries; std::vector<std::string> clangArgs; std::vector<core::system::Option> environmentVars; if (name == "2.11") { versionMin = "2.10.0"; versionMax = "2.11.1"; relativePathEntries.push_back("bin"); relativePathEntries.push_back("perl/bin"); relativePathEntries.push_back("MinGW/bin"); } else if (name == "2.12") { versionMin = "2.12.0"; versionMax = "2.12.2"; relativePathEntries.push_back("bin"); relativePathEntries.push_back("perl/bin"); relativePathEntries.push_back("MinGW/bin"); relativePathEntries.push_back("MinGW64/bin"); } else if (name == "2.13") { versionMin = "2.13.0"; versionMax = "2.13.2"; relativePathEntries.push_back("bin"); relativePathEntries.push_back("MinGW/bin"); relativePathEntries.push_back("MinGW64/bin"); } else if (name == "2.14") { versionMin = "2.13.0"; versionMax = "2.14.2"; relativePathEntries.push_back("bin"); relativePathEntries.push_back("MinGW/bin"); relativePathEntries.push_back("MinGW64/bin"); } else if (name == "2.15") { versionMin = "2.14.2"; versionMax = "2.15.1"; relativePathEntries.push_back("bin"); relativePathEntries.push_back("gcc-4.6.3/bin"); clangArgs = gcc463ClangArgs(installPath); } else if (name == "2.16" || name == "3.0") { versionMin = "2.15.2"; versionMax = "3.0.99"; gcc463Configuration(installPath, &relativePathEntries, &clangArgs); } else if (name == "3.1") { versionMin = "3.0.0"; versionMax = "3.1.99"; gcc463Configuration(installPath, &relativePathEntries, &clangArgs); } else if (name == "3.2") { versionMin = "3.1.0"; versionMax = "3.2.0"; gcc463Configuration(installPath, &relativePathEntries, &clangArgs); } else if (name == "3.3") { versionMin = "3.2.0"; versionMax = "3.2.99"; gcc463Configuration(installPath, &relativePathEntries, &clangArgs); } else if (name == "3.4" || name == "3.5") { versionMin = "3.3.0"; if (name == "3.4") versionMax = "3.5.99"; // Rtools 3.4 else versionMax = "3.6.99"; // Rtools 3.5 relativePathEntries.push_back("bin"); // set environment variables FilePath gccPath = installPath_.completeChildPath("mingw_$(WIN)/bin"); environmentVars.push_back( std::make_pair("BINPREF", asRBuildPath(gccPath))); // set clang args #ifdef _WIN64 std::string baseDir = "mingw_64"; std::string arch = "x86_64"; #else std::string baseDir = "mingw_32"; std::string arch = "i686"; #endif boost::format mgwIncFmt("%1%/%2%-w64-mingw32/include"); std::string mgwInc = boost::str(mgwIncFmt % baseDir % arch); clangArgs.push_back( "-I" + installPath.completeChildPath(mgwInc).getAbsolutePath()); std::string cppInc = mgwInc + "/c++"; clangArgs.push_back( "-I" + installPath.completeChildPath(cppInc).getAbsolutePath()); boost::format bitsIncFmt("%1%/%2%-w64-mingw32"); std::string bitsInc = boost::str(bitsIncFmt % cppInc % arch); clangArgs.push_back( "-I" + installPath.completeChildPath(bitsInc).getAbsolutePath()); } else if (name == "4.0") { versionMin = "4.0.0"; versionMax = "5.0.0"; // PATH for utilities relativePathEntries.push_back("usr/bin"); // set BINPREF environmentVars.push_back({"BINPREF", "/mingw$(WIN)/bin/"}); // set clang args #ifdef _WIN64 std::string baseDir = "mingw64"; std::string arch = "x86_64"; #else std::string baseDir = "mingw32"; std::string arch = "i686"; #endif // path to mingw includes boost::format mgwIncFmt("%1%/%2%-w64-mingw32/include"); std::string mingwIncludeSuffix = boost::str(mgwIncFmt % baseDir % arch); FilePath mingwIncludePath = installPath.completeChildPath(mingwIncludeSuffix); clangArgs.push_back("-I" + mingwIncludePath.getAbsolutePath()); // path to C++ headers std::string cppSuffix = "c++/8.3.0"; FilePath cppIncludePath = installPath.completeChildPath(cppSuffix); clangArgs.push_back("-I" + cppIncludePath.getAbsolutePath()); } else { LOG_DEBUG_MESSAGE("Unrecognized Rtools installation at path '" + installPath.getAbsolutePath() + "'"); } // build version predicate and path list if we can if (!versionMin.empty()) { boost::format fmt("getRversion() >= \"%1%\" && getRversion() <= \"%2%\""); versionPredicate_ = boost::str(fmt % versionMin % versionMax); for (const std::string& relativePath : relativePathEntries) { pathEntries_.push_back(installPath_.completeChildPath(relativePath)); } clangArgs_ = clangArgs; environmentVars_ = environmentVars; } } std::string RToolsInfo::url(const std::string& repos) const { std::string url; if (name() == "4.0") { std::string arch = core::system::isWin64() ? "x86_64" : "i686"; std::string suffix = "bin/windows/Rtools/rtools40-" + arch + ".exe"; url = core::http::URL::complete(repos, suffix); } else { std::string version = boost::algorithm::replace_all_copy(name(), ".", ""); std::string suffix = "bin/windows/Rtools/Rtools" + version + ".exe"; url = core::http::URL::complete(repos, suffix); } return url; } std::ostream& operator<<(std::ostream& os, const RToolsInfo& info) { os << "Rtools " << info.name() << std::endl; os << info.versionPredicate() << std::endl; for (const FilePath& pathEntry : info.pathEntries()) { os << pathEntry << std::endl; } for (const core::system::Option& var : info.environmentVars()) { os << var.first << "=" << var.second << std::endl; } return os; } namespace { Error scanEnvironmentForRTools(bool usingMingwGcc49, const std::string& envvar, std::vector<RToolsInfo>* pRTools) { // nothing to do if we have no envvar if (envvar.empty()) return Success(); // read value std::string envval = core::system::getenv(envvar); if (envval.empty()) return Success(); // build info FilePath installPath(envval); RToolsInfo toolsInfo("4.0", installPath, usingMingwGcc49); // check that recorded path is valid bool ok = toolsInfo.isStillInstalled() && toolsInfo.isRecognized(); // use it if all looks well if (ok) pRTools->push_back(toolsInfo); return Success(); } Error scanRegistryForRTools(HKEY key, bool usingMingwGcc49, std::vector<RToolsInfo>* pRTools) { core::system::RegistryKey regKey; Error error = regKey.open(key, "Software\\R-core\\Rtools", KEY_READ | KEY_WOW64_32KEY); if (error) { if (error != systemError(boost::system::errc::no_such_file_or_directory, ErrorLocation())) return error; else return Success(); } std::vector<std::string> keys = regKey.keyNames(); for (size_t i = 0; i < keys.size(); i++) { std::string name = keys.at(i); core::system::RegistryKey verKey; error = verKey.open(regKey.handle(), name, KEY_READ | KEY_WOW64_32KEY); if (error) { LOG_ERROR(error); continue; } std::string installPath = verKey.getStringValue("InstallPath", ""); if (!installPath.empty()) { std::string utf8InstallPath = string_utils::systemToUtf8(installPath); RToolsInfo toolsInfo(name, FilePath(utf8InstallPath), usingMingwGcc49); if (toolsInfo.isStillInstalled()) { if (toolsInfo.isRecognized()) pRTools->push_back(toolsInfo); else LOG_WARNING_MESSAGE("Unknown Rtools version: " + name); } } } return Success(); } void scanRegistryForRTools(bool usingMingwGcc49, std::vector<RToolsInfo>* pRTools) { // try HKLM first (backwards compatible with previous code) Error error = scanRegistryForRTools( HKEY_LOCAL_MACHINE, usingMingwGcc49, pRTools); if (error) LOG_ERROR(error); // try HKCU as a fallback if (pRTools->empty()) { Error error = scanRegistryForRTools( HKEY_CURRENT_USER, usingMingwGcc49, pRTools); if (error) LOG_ERROR(error); } } void scanFoldersForRTools(bool usingMingwGcc49, std::vector<RToolsInfo>* pRTools) { // look for Rtools as installed by RStudio std::string systemDrive = core::system::getenv("SYSTEMDRIVE"); FilePath buildDirRoot(systemDrive + "/RBuildTools"); // ensure it exists (may not exist if the user has not installed // any copies of Rtools through RStudio yet) if (!buildDirRoot.exists()) return; // find sub-directories std::vector<FilePath> buildDirs; Error error = buildDirRoot.getChildren(buildDirs); if (error) LOG_ERROR(error); // infer Rtools information from each directory for (const FilePath& buildDir : buildDirs) { RToolsInfo toolsInfo(buildDir.getFilename(), buildDir, usingMingwGcc49); if (toolsInfo.isRecognized()) pRTools->push_back(toolsInfo); else LOG_WARNING_MESSAGE("Unknown Rtools version: " + buildDir.getFilename()); } } } // end anonymous namespace void scanForRTools(bool usingMingwGcc49, const std::string& rtoolsHomeEnvVar, std::vector<RToolsInfo>* pRTools) { std::vector<RToolsInfo> rtoolsInfo; // scan for Rtools scanEnvironmentForRTools(usingMingwGcc49, rtoolsHomeEnvVar, &rtoolsInfo); scanRegistryForRTools(usingMingwGcc49, &rtoolsInfo); scanFoldersForRTools(usingMingwGcc49, &rtoolsInfo); // remove duplicates std::set<FilePath> knownPaths; for (const RToolsInfo& info : rtoolsInfo) { if (knownPaths.count(info.installPath())) continue; knownPaths.insert(info.installPath()); pRTools->push_back(info); } // ensure sorted by version std::sort( pRTools->begin(), pRTools->end(), [](const RToolsInfo& lhs, const RToolsInfo& rhs) { return Version(lhs.name()) < Version(rhs.name()); }); } } // namespace r_util } // namespace core } // namespace rstudio <commit_msg>ensure RTOOLS40_HOME is set (#6748)<commit_after>/* * RToolsInfo.cpp * * Copyright (C) 2009-19 by RStudio, PBC * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include <core/Version.hpp> #include <core/r_util/RToolsInfo.hpp> #include <boost/format.hpp> #include <boost/algorithm/string.hpp> #include <core/Log.hpp> #include <core/http/URL.hpp> #include <core/StringUtils.hpp> #include <core/system/System.hpp> #include <core/system/RegistryKey.hpp> #ifndef KEY_WOW64_32KEY #define KEY_WOW64_32KEY 0x0200 #endif namespace rstudio { namespace core { namespace r_util { namespace { std::string asRBuildPath(const FilePath& filePath) { std::string path = filePath.getAbsolutePath(); boost::algorithm::replace_all(path, "\\", "/"); if (!boost::algorithm::ends_with(path, "/")) path += "/"; return path; } std::vector<std::string> gcc463ClangArgs(const FilePath& installPath) { std::vector<std::string> clangArgs; clangArgs.push_back("-I" + installPath.completeChildPath( "gcc-4.6.3/i686-w64-mingw32/include").getAbsolutePath()); clangArgs.push_back("-I" + installPath.completeChildPath( "gcc-4.6.3/include/c++/4.6.3").getAbsolutePath()); std::string bits = "-I" + installPath.completeChildPath( "gcc-4.6.3/include/c++/4.6.3/i686-w64-mingw32").getAbsolutePath(); #ifdef _WIN64 bits += "/64"; #endif clangArgs.push_back(bits); return clangArgs; } void gcc463Configuration(const FilePath& installPath, std::vector<std::string>* pRelativePathEntries, std::vector<std::string>* pClangArgs) { pRelativePathEntries->push_back("bin"); pRelativePathEntries->push_back("gcc-4.6.3/bin"); *pClangArgs = gcc463ClangArgs(installPath); } } // anonymous namespace RToolsInfo::RToolsInfo(const std::string& name, const FilePath& installPath, bool usingMingwGcc49) : name_(name), installPath_(installPath) { std::string versionMin, versionMax; std::vector<std::string> relativePathEntries; std::vector<std::string> clangArgs; std::vector<core::system::Option> environmentVars; if (name == "2.11") { versionMin = "2.10.0"; versionMax = "2.11.1"; relativePathEntries.push_back("bin"); relativePathEntries.push_back("perl/bin"); relativePathEntries.push_back("MinGW/bin"); } else if (name == "2.12") { versionMin = "2.12.0"; versionMax = "2.12.2"; relativePathEntries.push_back("bin"); relativePathEntries.push_back("perl/bin"); relativePathEntries.push_back("MinGW/bin"); relativePathEntries.push_back("MinGW64/bin"); } else if (name == "2.13") { versionMin = "2.13.0"; versionMax = "2.13.2"; relativePathEntries.push_back("bin"); relativePathEntries.push_back("MinGW/bin"); relativePathEntries.push_back("MinGW64/bin"); } else if (name == "2.14") { versionMin = "2.13.0"; versionMax = "2.14.2"; relativePathEntries.push_back("bin"); relativePathEntries.push_back("MinGW/bin"); relativePathEntries.push_back("MinGW64/bin"); } else if (name == "2.15") { versionMin = "2.14.2"; versionMax = "2.15.1"; relativePathEntries.push_back("bin"); relativePathEntries.push_back("gcc-4.6.3/bin"); clangArgs = gcc463ClangArgs(installPath); } else if (name == "2.16" || name == "3.0") { versionMin = "2.15.2"; versionMax = "3.0.99"; gcc463Configuration(installPath, &relativePathEntries, &clangArgs); } else if (name == "3.1") { versionMin = "3.0.0"; versionMax = "3.1.99"; gcc463Configuration(installPath, &relativePathEntries, &clangArgs); } else if (name == "3.2") { versionMin = "3.1.0"; versionMax = "3.2.0"; gcc463Configuration(installPath, &relativePathEntries, &clangArgs); } else if (name == "3.3") { versionMin = "3.2.0"; versionMax = "3.2.99"; gcc463Configuration(installPath, &relativePathEntries, &clangArgs); } else if (name == "3.4" || name == "3.5") { versionMin = "3.3.0"; if (name == "3.4") versionMax = "3.5.99"; // Rtools 3.4 else versionMax = "3.6.99"; // Rtools 3.5 relativePathEntries.push_back("bin"); // set environment variables FilePath gccPath = installPath_.completeChildPath("mingw_$(WIN)/bin"); environmentVars.push_back( std::make_pair("BINPREF", asRBuildPath(gccPath))); // set clang args #ifdef _WIN64 std::string baseDir = "mingw_64"; std::string arch = "x86_64"; #else std::string baseDir = "mingw_32"; std::string arch = "i686"; #endif boost::format mgwIncFmt("%1%/%2%-w64-mingw32/include"); std::string mgwInc = boost::str(mgwIncFmt % baseDir % arch); clangArgs.push_back( "-I" + installPath.completeChildPath(mgwInc).getAbsolutePath()); std::string cppInc = mgwInc + "/c++"; clangArgs.push_back( "-I" + installPath.completeChildPath(cppInc).getAbsolutePath()); boost::format bitsIncFmt("%1%/%2%-w64-mingw32"); std::string bitsInc = boost::str(bitsIncFmt % cppInc % arch); clangArgs.push_back( "-I" + installPath.completeChildPath(bitsInc).getAbsolutePath()); } else if (name == "4.0") { versionMin = "4.0.0"; versionMax = "5.0.0"; // PATH for utilities relativePathEntries.push_back("usr/bin"); // set BINPREF environmentVars.push_back({"BINPREF", "/mingw$(WIN)/bin/"}); // set RTOOLS40_HOME std::string rtoolsPath = installPath.getAbsolutePath(); std::replace(rtoolsPath.begin(), rtoolsPath.end(), '\\', '/'); environmentVars.push_back({"RTOOLS40_HOME", rtoolsPath}); // set clang args #ifdef _WIN64 std::string baseDir = "mingw64"; std::string arch = "x86_64"; #else std::string baseDir = "mingw32"; std::string arch = "i686"; #endif // path to mingw includes boost::format mgwIncFmt("%1%/%2%-w64-mingw32/include"); std::string mingwIncludeSuffix = boost::str(mgwIncFmt % baseDir % arch); FilePath mingwIncludePath = installPath.completeChildPath(mingwIncludeSuffix); clangArgs.push_back("-I" + mingwIncludePath.getAbsolutePath()); // path to C++ headers std::string cppSuffix = "c++/8.3.0"; FilePath cppIncludePath = installPath.completeChildPath(cppSuffix); clangArgs.push_back("-I" + cppIncludePath.getAbsolutePath()); } else { LOG_DEBUG_MESSAGE("Unrecognized Rtools installation at path '" + installPath.getAbsolutePath() + "'"); } // build version predicate and path list if we can if (!versionMin.empty()) { boost::format fmt("getRversion() >= \"%1%\" && getRversion() <= \"%2%\""); versionPredicate_ = boost::str(fmt % versionMin % versionMax); for (const std::string& relativePath : relativePathEntries) { pathEntries_.push_back(installPath_.completeChildPath(relativePath)); } clangArgs_ = clangArgs; environmentVars_ = environmentVars; } } std::string RToolsInfo::url(const std::string& repos) const { std::string url; if (name() == "4.0") { std::string arch = core::system::isWin64() ? "x86_64" : "i686"; std::string suffix = "bin/windows/Rtools/rtools40-" + arch + ".exe"; url = core::http::URL::complete(repos, suffix); } else { std::string version = boost::algorithm::replace_all_copy(name(), ".", ""); std::string suffix = "bin/windows/Rtools/Rtools" + version + ".exe"; url = core::http::URL::complete(repos, suffix); } return url; } std::ostream& operator<<(std::ostream& os, const RToolsInfo& info) { os << "Rtools " << info.name() << std::endl; os << info.versionPredicate() << std::endl; for (const FilePath& pathEntry : info.pathEntries()) { os << pathEntry << std::endl; } for (const core::system::Option& var : info.environmentVars()) { os << var.first << "=" << var.second << std::endl; } return os; } namespace { Error scanEnvironmentForRTools(bool usingMingwGcc49, const std::string& envvar, std::vector<RToolsInfo>* pRTools) { // nothing to do if we have no envvar if (envvar.empty()) return Success(); // read value std::string envval = core::system::getenv(envvar); if (envval.empty()) return Success(); // build info FilePath installPath(envval); RToolsInfo toolsInfo("4.0", installPath, usingMingwGcc49); // check that recorded path is valid bool ok = toolsInfo.isStillInstalled() && toolsInfo.isRecognized(); // use it if all looks well if (ok) pRTools->push_back(toolsInfo); return Success(); } Error scanRegistryForRTools(HKEY key, bool usingMingwGcc49, std::vector<RToolsInfo>* pRTools) { core::system::RegistryKey regKey; Error error = regKey.open(key, "Software\\R-core\\Rtools", KEY_READ | KEY_WOW64_32KEY); if (error) { if (error != systemError(boost::system::errc::no_such_file_or_directory, ErrorLocation())) return error; else return Success(); } std::vector<std::string> keys = regKey.keyNames(); for (size_t i = 0; i < keys.size(); i++) { std::string name = keys.at(i); core::system::RegistryKey verKey; error = verKey.open(regKey.handle(), name, KEY_READ | KEY_WOW64_32KEY); if (error) { LOG_ERROR(error); continue; } std::string installPath = verKey.getStringValue("InstallPath", ""); if (!installPath.empty()) { std::string utf8InstallPath = string_utils::systemToUtf8(installPath); RToolsInfo toolsInfo(name, FilePath(utf8InstallPath), usingMingwGcc49); if (toolsInfo.isStillInstalled()) { if (toolsInfo.isRecognized()) pRTools->push_back(toolsInfo); else LOG_WARNING_MESSAGE("Unknown Rtools version: " + name); } } } return Success(); } void scanRegistryForRTools(bool usingMingwGcc49, std::vector<RToolsInfo>* pRTools) { // try HKLM first (backwards compatible with previous code) Error error = scanRegistryForRTools( HKEY_LOCAL_MACHINE, usingMingwGcc49, pRTools); if (error) LOG_ERROR(error); // try HKCU as a fallback if (pRTools->empty()) { Error error = scanRegistryForRTools( HKEY_CURRENT_USER, usingMingwGcc49, pRTools); if (error) LOG_ERROR(error); } } void scanFoldersForRTools(bool usingMingwGcc49, std::vector<RToolsInfo>* pRTools) { // look for Rtools as installed by RStudio std::string systemDrive = core::system::getenv("SYSTEMDRIVE"); FilePath buildDirRoot(systemDrive + "/RBuildTools"); // ensure it exists (may not exist if the user has not installed // any copies of Rtools through RStudio yet) if (!buildDirRoot.exists()) return; // find sub-directories std::vector<FilePath> buildDirs; Error error = buildDirRoot.getChildren(buildDirs); if (error) LOG_ERROR(error); // infer Rtools information from each directory for (const FilePath& buildDir : buildDirs) { RToolsInfo toolsInfo(buildDir.getFilename(), buildDir, usingMingwGcc49); if (toolsInfo.isRecognized()) pRTools->push_back(toolsInfo); else LOG_WARNING_MESSAGE("Unknown Rtools version: " + buildDir.getFilename()); } } } // end anonymous namespace void scanForRTools(bool usingMingwGcc49, const std::string& rtoolsHomeEnvVar, std::vector<RToolsInfo>* pRTools) { std::vector<RToolsInfo> rtoolsInfo; // scan for Rtools scanEnvironmentForRTools(usingMingwGcc49, rtoolsHomeEnvVar, &rtoolsInfo); scanRegistryForRTools(usingMingwGcc49, &rtoolsInfo); scanFoldersForRTools(usingMingwGcc49, &rtoolsInfo); // remove duplicates std::set<FilePath> knownPaths; for (const RToolsInfo& info : rtoolsInfo) { if (knownPaths.count(info.installPath())) continue; knownPaths.insert(info.installPath()); pRTools->push_back(info); } // ensure sorted by version std::sort( pRTools->begin(), pRTools->end(), [](const RToolsInfo& lhs, const RToolsInfo& rhs) { return Version(lhs.name()) < Version(rhs.name()); }); } } // namespace r_util } // namespace core } // namespace rstudio <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information (qt-info@nokia.com) ** ** This file is part of the QtDeclarative module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the either Technology Preview License Agreement or the ** Beta Release License Agreement. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at qt-sales@nokia.com. ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <limits.h> #include <math.h> #include <QtCore/qdebug.h> #include "private/qobject_p.h" #include "qmlfollow.h" #include "private/qmlanimation_p.h" QT_BEGIN_NAMESPACE QML_DEFINE_TYPE(QmlFollow,Follow) class QmlFollowPrivate : public QObjectPrivate { Q_DECLARE_PUBLIC(QmlFollow) public: QmlFollowPrivate() : sourceValue(0), maxVelocity(0), lastTime(0) , mass(1.0), spring(0.), damping(0.), velocity(0), epsilon(0.01), modulus(0.0), enabled(true), mode(Track), clock(this) {} QmlMetaProperty property; qreal currentValue; qreal sourceValue; qreal maxVelocity; qreal velocityms; int lastTime; qreal mass; qreal spring; qreal damping; qreal velocity; qreal epsilon; qreal modulus; bool enabled; enum Mode { Track, Velocity, Spring }; Mode mode; void tick(int); void updateMode(); void start(); void stop(); QTickAnimationProxy<QmlFollowPrivate, &QmlFollowPrivate::tick> clock; }; void QmlFollowPrivate::tick(int time) { Q_Q(QmlFollow); int elapsed = time - lastTime; if (!elapsed) return; qreal srcVal = sourceValue; if (modulus != 0.0) { currentValue = fmod(currentValue, modulus); srcVal = fmod(srcVal, modulus); } if (mode == Spring) { if (elapsed < 16) // capped at 62fps. return; // Real men solve the spring DEs using RK4. // We'll do something much simpler which gives a result that looks fine. int count = (elapsed+8) / 16; for (int i = 0; i < count; ++i) { qreal diff = srcVal - currentValue; if (modulus != 0.0 && qAbs(diff) > modulus / 2) { if (diff < 0) diff += modulus; else diff -= modulus; } velocity = velocity + spring * diff - damping * velocity; // The following line supports mass. Not sure its worth the extra divisions. // velocity = velocity + spring / mass * diff - damping / mass * velocity; if (maxVelocity > 0.) { // limit velocity if (velocity > maxVelocity) velocity = maxVelocity; else if (velocity < -maxVelocity) velocity = -maxVelocity; } currentValue += velocity * 16.0 / 1000.0; if (modulus != 0.0) { currentValue = fmod(currentValue, modulus); if (currentValue < 0.0) currentValue += modulus; } } if (qAbs(velocity) < epsilon && qAbs(srcVal - currentValue) < epsilon) { velocity = 0.0; currentValue = srcVal; clock.stop(); } lastTime = time - (elapsed - count * 16); } else { qreal moveBy = elapsed * velocityms; qreal diff = srcVal - currentValue; if (modulus != 0.0 && qAbs(diff) > modulus / 2) { if (diff < 0) diff += modulus; else diff -= modulus; } if (diff > 0) { currentValue += moveBy; if (modulus != 0.0) currentValue = fmod(currentValue, modulus); if (currentValue > sourceValue) { currentValue = sourceValue; clock.stop(); } } else { currentValue -= moveBy; if (modulus != 0.0 && currentValue < 0.0) currentValue = fmod(currentValue, modulus) + modulus; if (currentValue < sourceValue) { currentValue = sourceValue; clock.stop(); } } lastTime = time; } property.write(currentValue); emit q->valueChanged(currentValue); if (clock.state() != QAbstractAnimation::Running) emit q->syncChanged(); } void QmlFollowPrivate::updateMode() { if (spring == 0. && maxVelocity == 0.) mode = Track; else if (spring > 0.) mode = Spring; else mode = Velocity; } void QmlFollowPrivate::start() { if (!enabled) return; Q_Q(QmlFollow); if (mode == QmlFollowPrivate::Track) { currentValue = sourceValue; property.write(currentValue); } else if (sourceValue != currentValue && clock.state() != QAbstractAnimation::Running) { lastTime = 0; currentValue = property.read().toDouble(); clock.start(); // infinity?? emit q->syncChanged(); } } void QmlFollowPrivate::stop() { clock.stop(); } /*! \qmlclass Follow QmlFollow \brief The Follow element allows a property to track a value. In example below, Rect2 will follow Rect1 moving with a velocity of up to 200: \code Rect { id: Rect1 width: 20; height: 20 color: "#00ff00" y: 200 //initial value y: SequentialAnimation { running: true repeat: true NumberAnimation { to: 200 easing: "easeOutBounce(amplitude:100)" duration: 2000 } PauseAnimation { duration: 1000 } } } Rect { id: Rect2 x: Rect1.width width: 20; height: 20 color: "#ff0000" y: Follow { source: Rect1.y; velocity: 200 } } \endcode */ QmlFollow::QmlFollow(QObject *parent) : QmlPropertyValueSource(*(new QmlFollowPrivate),parent) { } QmlFollow::~QmlFollow() { } void QmlFollow::setTarget(const QmlMetaProperty &property) { Q_D(QmlFollow); d->property = property; d->currentValue = property.read().toDouble(); } qreal QmlFollow::sourceValue() const { Q_D(const QmlFollow); return d->sourceValue; } /*! \qmlproperty qreal Follow::source This property holds the source value which will be tracked. Bind to a property in order to track its changes. */ void QmlFollow::setSourceValue(qreal value) { Q_D(QmlFollow); if (d->sourceValue != value) { d->sourceValue = value; d->start(); } } /*! \qmlproperty qreal Follow::velocity This property holds the maximum velocity allowed when tracking the source. */ qreal QmlFollow::velocity() const { Q_D(const QmlFollow); return d->maxVelocity; } void QmlFollow::setVelocity(qreal velocity) { Q_D(QmlFollow); d->maxVelocity = velocity; d->velocityms = velocity / 1000.0; d->updateMode(); } /*! \qmlproperty qreal Follow::spring This property holds the spring constant The spring constant describes how strongly the target is pulled towards the source. Setting spring to 0 turns off spring tracking. Useful values 0 - 5.0 When a spring constant is set and the velocity property is greater than 0, velocity limits the maximum speed. */ qreal QmlFollow::spring() const { Q_D(const QmlFollow); return d->spring; } void QmlFollow::setSpring(qreal spring) { Q_D(QmlFollow); d->spring = spring; d->updateMode(); } /*! \qmlproperty qreal Follow::damping This property holds the spring damping constant The damping constant describes how quickly a sprung follower comes to rest. Useful range is 0 - 1.0 */ qreal QmlFollow::damping() const { Q_D(const QmlFollow); return d->damping; } void QmlFollow::setDamping(qreal damping) { Q_D(QmlFollow); if (damping > 1.) damping = 1.; d->damping = damping; } /*! \qmlproperty qreal Follow::epsilon This property holds the spring epsilon The epsilon is the rate and amount of change in the value which is close enough to 0 to be considered equal to zero. This will depend on the usage of the value. For pixel positions, 0.25 would suffice. For scale, 0.005 will suffice. The default is 0.01. Small performance improvements can result in tuning this value. */ qreal QmlFollow::epsilon() const { Q_D(const QmlFollow); return d->epsilon; } void QmlFollow::setEpsilon(qreal epsilon) { Q_D(QmlFollow); d->epsilon = epsilon; } /*! \qmlproperty qreal Follow::modulus This property holds the modulus value. Setting a \a modulus forces the target value to "wrap around" at the modulus. For example, setting the modulus to 360 will cause a value of 370 to wrap around to 10. */ qreal QmlFollow::modulus() const { Q_D(const QmlFollow); return d->modulus; } void QmlFollow::setModulus(qreal modulus) { Q_D(QmlFollow); d->modulus = modulus; } /*! \qmlproperty qreal Follow::followValue The current value. */ /*! \qmlproperty bool Follow::enabled This property holds whether the target will track the source. */ bool QmlFollow::enabled() const { Q_D(const QmlFollow); return d->enabled; } void QmlFollow::setEnabled(bool enabled) { Q_D(QmlFollow); d->enabled = enabled; if (enabled) d->start(); else d->stop(); } /*! \qmlproperty bool Follow::inSync This property is true when target is equal to the source; otherwise false. If inSync is true the target is not being animated. If \l enabled is false then inSync will also be false. */ bool QmlFollow::inSync() const { Q_D(const QmlFollow); return d->enabled && d->clock.state() != QAbstractAnimation::Running; } qreal QmlFollow::value() const { Q_D(const QmlFollow); return d->currentValue; } QT_END_NAMESPACE <commit_msg>Doc clarification.<commit_after>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information (qt-info@nokia.com) ** ** This file is part of the QtDeclarative module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the either Technology Preview License Agreement or the ** Beta Release License Agreement. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at qt-sales@nokia.com. ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <limits.h> #include <math.h> #include <QtCore/qdebug.h> #include "private/qobject_p.h" #include "qmlfollow.h" #include "private/qmlanimation_p.h" QT_BEGIN_NAMESPACE QML_DEFINE_TYPE(QmlFollow,Follow) class QmlFollowPrivate : public QObjectPrivate { Q_DECLARE_PUBLIC(QmlFollow) public: QmlFollowPrivate() : sourceValue(0), maxVelocity(0), lastTime(0) , mass(1.0), spring(0.), damping(0.), velocity(0), epsilon(0.01), modulus(0.0), enabled(true), mode(Track), clock(this) {} QmlMetaProperty property; qreal currentValue; qreal sourceValue; qreal maxVelocity; qreal velocityms; int lastTime; qreal mass; qreal spring; qreal damping; qreal velocity; qreal epsilon; qreal modulus; bool enabled; enum Mode { Track, Velocity, Spring }; Mode mode; void tick(int); void updateMode(); void start(); void stop(); QTickAnimationProxy<QmlFollowPrivate, &QmlFollowPrivate::tick> clock; }; void QmlFollowPrivate::tick(int time) { Q_Q(QmlFollow); int elapsed = time - lastTime; if (!elapsed) return; qreal srcVal = sourceValue; if (modulus != 0.0) { currentValue = fmod(currentValue, modulus); srcVal = fmod(srcVal, modulus); } if (mode == Spring) { if (elapsed < 16) // capped at 62fps. return; // Real men solve the spring DEs using RK4. // We'll do something much simpler which gives a result that looks fine. int count = (elapsed+8) / 16; for (int i = 0; i < count; ++i) { qreal diff = srcVal - currentValue; if (modulus != 0.0 && qAbs(diff) > modulus / 2) { if (diff < 0) diff += modulus; else diff -= modulus; } velocity = velocity + spring * diff - damping * velocity; // The following line supports mass. Not sure its worth the extra divisions. // velocity = velocity + spring / mass * diff - damping / mass * velocity; if (maxVelocity > 0.) { // limit velocity if (velocity > maxVelocity) velocity = maxVelocity; else if (velocity < -maxVelocity) velocity = -maxVelocity; } currentValue += velocity * 16.0 / 1000.0; if (modulus != 0.0) { currentValue = fmod(currentValue, modulus); if (currentValue < 0.0) currentValue += modulus; } } if (qAbs(velocity) < epsilon && qAbs(srcVal - currentValue) < epsilon) { velocity = 0.0; currentValue = srcVal; clock.stop(); } lastTime = time - (elapsed - count * 16); } else { qreal moveBy = elapsed * velocityms; qreal diff = srcVal - currentValue; if (modulus != 0.0 && qAbs(diff) > modulus / 2) { if (diff < 0) diff += modulus; else diff -= modulus; } if (diff > 0) { currentValue += moveBy; if (modulus != 0.0) currentValue = fmod(currentValue, modulus); if (currentValue > sourceValue) { currentValue = sourceValue; clock.stop(); } } else { currentValue -= moveBy; if (modulus != 0.0 && currentValue < 0.0) currentValue = fmod(currentValue, modulus) + modulus; if (currentValue < sourceValue) { currentValue = sourceValue; clock.stop(); } } lastTime = time; } property.write(currentValue); emit q->valueChanged(currentValue); if (clock.state() != QAbstractAnimation::Running) emit q->syncChanged(); } void QmlFollowPrivate::updateMode() { if (spring == 0. && maxVelocity == 0.) mode = Track; else if (spring > 0.) mode = Spring; else mode = Velocity; } void QmlFollowPrivate::start() { if (!enabled) return; Q_Q(QmlFollow); if (mode == QmlFollowPrivate::Track) { currentValue = sourceValue; property.write(currentValue); } else if (sourceValue != currentValue && clock.state() != QAbstractAnimation::Running) { lastTime = 0; currentValue = property.read().toDouble(); clock.start(); // infinity?? emit q->syncChanged(); } } void QmlFollowPrivate::stop() { clock.stop(); } /*! \qmlclass Follow QmlFollow \brief The Follow element allows a property to track a value. In example below, Rect2 will follow Rect1 moving with a velocity of up to 200: \code Rect { id: Rect1 width: 20; height: 20 color: "#00ff00" y: 200 //initial value y: SequentialAnimation { running: true repeat: true NumberAnimation { to: 200 easing: "easeOutBounce(amplitude:100)" duration: 2000 } PauseAnimation { duration: 1000 } } } Rect { id: Rect2 x: Rect1.width width: 20; height: 20 color: "#ff0000" y: Follow { source: Rect1.y; velocity: 200 } } \endcode */ QmlFollow::QmlFollow(QObject *parent) : QmlPropertyValueSource(*(new QmlFollowPrivate),parent) { } QmlFollow::~QmlFollow() { } void QmlFollow::setTarget(const QmlMetaProperty &property) { Q_D(QmlFollow); d->property = property; d->currentValue = property.read().toDouble(); } qreal QmlFollow::sourceValue() const { Q_D(const QmlFollow); return d->sourceValue; } /*! \qmlproperty qreal Follow::source This property holds the source value which will be tracked. Bind to a property in order to track its changes. */ void QmlFollow::setSourceValue(qreal value) { Q_D(QmlFollow); if (d->sourceValue != value) { d->sourceValue = value; d->start(); } } /*! \qmlproperty qreal Follow::velocity This property holds the maximum velocity allowed when tracking the source. */ qreal QmlFollow::velocity() const { Q_D(const QmlFollow); return d->maxVelocity; } void QmlFollow::setVelocity(qreal velocity) { Q_D(QmlFollow); d->maxVelocity = velocity; d->velocityms = velocity / 1000.0; d->updateMode(); } /*! \qmlproperty qreal Follow::spring This property holds the spring constant The spring constant describes how strongly the target is pulled towards the source. Setting spring to 0 turns off spring tracking. Useful values 0 - 5.0 When a spring constant is set and the velocity property is greater than 0, velocity limits the maximum speed. */ qreal QmlFollow::spring() const { Q_D(const QmlFollow); return d->spring; } void QmlFollow::setSpring(qreal spring) { Q_D(QmlFollow); d->spring = spring; d->updateMode(); } /*! \qmlproperty qreal Follow::damping This property holds the spring damping constant The damping constant describes how quickly a sprung follower comes to rest. Useful range is 0 - 1.0 */ qreal QmlFollow::damping() const { Q_D(const QmlFollow); return d->damping; } void QmlFollow::setDamping(qreal damping) { Q_D(QmlFollow); if (damping > 1.) damping = 1.; d->damping = damping; } /*! \qmlproperty qreal Follow::epsilon This property holds the spring epsilon The epsilon is the rate and amount of change in the value which is close enough to 0 to be considered equal to zero. This will depend on the usage of the value. For pixel positions, 0.25 would suffice. For scale, 0.005 will suffice. The default is 0.01. Tuning this value can provide small performance improvements. */ qreal QmlFollow::epsilon() const { Q_D(const QmlFollow); return d->epsilon; } void QmlFollow::setEpsilon(qreal epsilon) { Q_D(QmlFollow); d->epsilon = epsilon; } /*! \qmlproperty qreal Follow::modulus This property holds the modulus value. Setting a \a modulus forces the target value to "wrap around" at the modulus. For example, setting the modulus to 360 will cause a value of 370 to wrap around to 10. */ qreal QmlFollow::modulus() const { Q_D(const QmlFollow); return d->modulus; } void QmlFollow::setModulus(qreal modulus) { Q_D(QmlFollow); d->modulus = modulus; } /*! \qmlproperty qreal Follow::followValue The current value. */ /*! \qmlproperty bool Follow::enabled This property holds whether the target will track the source. */ bool QmlFollow::enabled() const { Q_D(const QmlFollow); return d->enabled; } void QmlFollow::setEnabled(bool enabled) { Q_D(QmlFollow); d->enabled = enabled; if (enabled) d->start(); else d->stop(); } /*! \qmlproperty bool Follow::inSync This property is true when target is equal to the source; otherwise false. If inSync is true the target is not being animated. If \l enabled is false then inSync will also be false. */ bool QmlFollow::inSync() const { Q_D(const QmlFollow); return d->enabled && d->clock.state() != QAbstractAnimation::Running; } qreal QmlFollow::value() const { Q_D(const QmlFollow); return d->currentValue; } QT_END_NAMESPACE <|endoftext|>
<commit_before>// // ex7_01.cpp // Exercise 7.1 // // Created by pezy on 14/10/30. // Copyright (c) 2014 pezy. All rights reserved. // #include <iostream> #include <string> using std::cin; using std::cout; using std::endl; using std::string; struct Sales_data { string bookNo; unsigned units_sold = 0; double revenue = 0.0; }; int main() { Sales_data total; if (cin >> total.bookNo >> total.units_sold >> total.revenue) { Sales_data trans; while (cin >> trans.bookNo >> trans.units_sold >> trans.revenue) { if (total.bookNo == trans.bookNo) { total.units_sold += trans.units_sold; total.revenue += trans.revenue; } else { cout << total.bookNo << " " << total.units_sold << " " << total.revenue << endl; total = trans; } } cout << total.bookNo << " " << total.units_sold << " " << total.revenue << endl; } else { std::cerr << "No data?!" << std::endl; return -1; } return 0; } <commit_msg>Update ex7_01.cpp<commit_after>// // ex7_01.cpp // Exercise 7.1 // // Created by pezy on 14/10/30. // Copyright (c) 2014 pezy. All rights reserved. // #include <iostream> #include <string> using std::cin; using std::cout; using std::cerr; using std::endl; using std::string; struct Sales_data { string bookNo; unsigned units_sold = 0; double revenue = 0.0; }; int main() { Sales_data total; double price; if (cin >> total.bookNo >> total.units_sold >> price) { total.revenue=total.units_sold*price; Sales_data trans; while (cin >> trans.bookNo >> trans.units_sold >> price) { trans.revenue=trans.units_sold*price; if (total.bookNo == trans.bookNo) { total.units_sold += trans.units_sold; total.revenue += trans.revenue; } else { cout << total.bookNo << " " << total.units_sold << " " << total.revenue << endl; total.bookNo=trans.bookNo; total.units_sold=trans.units_sold; total.revenue=trans.revenue; } } cout << total.bookNo << " " << total.units_sold << " " << total.revenue << endl; } else { cerr << "No data?!" << endl; return -1; } return 0; } <|endoftext|>
<commit_before>#include "ClientConnection.hpp" #include "ClientDhLayer.hpp" #include "ClientRpcLayer.hpp" #include "CTelegramTransport.hpp" #include "SendPackageHelper.hpp" #include "TelegramUtils.hpp" #include "Utils.hpp" #include <QDateTime> namespace Telegram { namespace Client { class SendPackageHelper : public BaseSendPackageHelper { public: explicit SendPackageHelper(BaseConnection *connection) : BaseSendPackageHelper(), m_connection(connection) { } quint64 newMessageId(bool isReply) override { Q_UNUSED(isReply) quint64 ts = TelegramUtils::formatTimeStamp(QDateTime::currentMSecsSinceEpoch()); ts &= ~quint64(3); return m_connection->transport()->getNewMessageId(ts); } void sendPackage(const QByteArray &package) override { return m_connection->transport()->sendPackage(package); } protected: BaseConnection *m_connection; }; Connection::Connection(QObject *parent) : BaseConnection(parent) { m_senderHelper = new SendPackageHelper(this); m_dhLayer = new DhLayer(this); m_dhLayer->setSendPackageHelper(m_senderHelper); connect(m_dhLayer, &BaseDhLayer::stateChanged, this, &Connection::onClientDhStateChanged); m_rpcLayer = new RpcLayer(this); m_rpcLayer->setSendPackageHelper(m_senderHelper); } void Connection::setDcOption(const TLDcOption &dcOption) { m_dcOption = dcOption; } void Connection::setDcOption(const DcOption &dcOption) { TLDcOption opt; opt.ipAddress = dcOption.address; opt.port = dcOption.port; setDcOption(opt); } RpcLayer *Connection::rpcLayer() { return reinterpret_cast<RpcLayer*>(m_rpcLayer); } PendingOperation *Connection::connectToDc() { if (m_status != Status::Disconnected) { return PendingOperation::failOperation<PendingOperation>({ { QStringLiteral("text"), QStringLiteral("Connection is already in progress") } }); } #ifdef DEVELOPER_BUILD qDebug() << Q_FUNC_INFO << m_dcOption.id << m_dcOption.ipAddress << m_dcOption.port; #endif if (m_transport->state() != QAbstractSocket::UnconnectedState) { m_transport->disconnectFromHost(); // Ensure that there is no connection } PendingOperation *op = new PendingOperation(this); // TODO: Connect error to op->setFinishedWithError() setStatus(Status::Connecting, StatusReason::Local); // setAuthState(AuthStateNone); m_transport->connectToHost(m_dcOption.ipAddress, m_dcOption.port); connect(this, &Connection::statusChanged, [op] (Status status, StatusReason reason) { Q_UNUSED(reason) if (status == Status::Authenticated) { op->setFinished(); } }); // connect(m_transport, &CTelegramTransport::stateChanged, [op] (QAbstractSocket::SocketState transportState) { // if (transportState == QAbstractSocket::ConnectedState) { // op->setFinished(); // } // }); return op; } void Connection::onClientDhStateChanged() { if (m_dhLayer->state() == BaseDhLayer::State::HasKey) { if (!m_rpcLayer->sessionId()) { rpcLayer()->setSessionId(Utils::randomBytes<quint64>()); } } } } // Client namespace } // Telegram namespace <commit_msg>ClientConnection: Fail connectToDc operation on connection failed<commit_after>#include "ClientConnection.hpp" #include "ClientDhLayer.hpp" #include "ClientRpcLayer.hpp" #include "CTelegramTransport.hpp" #include "SendPackageHelper.hpp" #include "TelegramUtils.hpp" #include "Utils.hpp" #include <QDateTime> namespace Telegram { namespace Client { class SendPackageHelper : public BaseSendPackageHelper { public: explicit SendPackageHelper(BaseConnection *connection) : BaseSendPackageHelper(), m_connection(connection) { } quint64 newMessageId(bool isReply) override { Q_UNUSED(isReply) quint64 ts = TelegramUtils::formatTimeStamp(QDateTime::currentMSecsSinceEpoch()); ts &= ~quint64(3); return m_connection->transport()->getNewMessageId(ts); } void sendPackage(const QByteArray &package) override { return m_connection->transport()->sendPackage(package); } protected: BaseConnection *m_connection; }; Connection::Connection(QObject *parent) : BaseConnection(parent) { m_senderHelper = new SendPackageHelper(this); m_dhLayer = new DhLayer(this); m_dhLayer->setSendPackageHelper(m_senderHelper); connect(m_dhLayer, &BaseDhLayer::stateChanged, this, &Connection::onClientDhStateChanged); m_rpcLayer = new RpcLayer(this); m_rpcLayer->setSendPackageHelper(m_senderHelper); } void Connection::setDcOption(const TLDcOption &dcOption) { m_dcOption = dcOption; } void Connection::setDcOption(const DcOption &dcOption) { TLDcOption opt; opt.ipAddress = dcOption.address; opt.port = dcOption.port; setDcOption(opt); } RpcLayer *Connection::rpcLayer() { return reinterpret_cast<RpcLayer*>(m_rpcLayer); } PendingOperation *Connection::connectToDc() { if (m_status != Status::Disconnected) { return PendingOperation::failOperation<PendingOperation>({ { QStringLiteral("text"), QStringLiteral("Connection is already in progress") } }); } #ifdef DEVELOPER_BUILD qDebug() << Q_FUNC_INFO << m_dcOption.id << m_dcOption.ipAddress << m_dcOption.port; #endif if (m_transport->state() != QAbstractSocket::UnconnectedState) { m_transport->disconnectFromHost(); // Ensure that there is no connection } PendingOperation *op = new PendingOperation(this); // TODO: Connect error to op->setFinishedWithError() setStatus(Status::Connecting, StatusReason::Local); // setAuthState(AuthStateNone); m_transport->connectToHost(m_dcOption.ipAddress, m_dcOption.port); connect(m_transport, &CTelegramTransport::errorOccurred, [op] (QAbstractSocket::SocketError error, const QString &text) { op->setFinishedWithError({ { QStringLiteral("qtError"), error }, { QStringLiteral("qtErrorText"), text }, }); }); connect(this, &Connection::statusChanged, [op] (Status status, StatusReason reason) { Q_UNUSED(reason) if (status == Status::Authenticated) { op->setFinished(); } }); // connect(m_transport, &CTelegramTransport::stateChanged, [op] (QAbstractSocket::SocketState transportState) { // if (transportState == QAbstractSocket::ConnectedState) { // op->setFinished(); // } // }); return op; } void Connection::onClientDhStateChanged() { if (m_dhLayer->state() == BaseDhLayer::State::HasKey) { if (!m_rpcLayer->sessionId()) { rpcLayer()->setSessionId(Utils::randomBytes<quint64>()); } } } } // Client namespace } // Telegram namespace <|endoftext|>
<commit_before>#if !defined( __CINT__) || defined(__MAKECINT__) #include <iostream> #include <AliCDBManager.h> #include <AliCDBStorage.h> #include <AliCDBEntry.h> #include <AliCDBMetaData.h> #include "AliTRDgeometry.h" #include "AliTRDCalROC.h" #include "AliTRDCalPad.h" #include "AliTRDCalDet.h" #include "AliTRDCalChamberStatus.h" #include "AliTRDCalPadStatus.h" #include "AliTRDCalSingleChamberStatus.h" #include "AliTRDCalPIDLQ.h" #include "AliTRDCalMonitoring.h" #endif // Run numbers for the dummy file const Int_t gkDummyRunBeg = 0; const Int_t gkDummyRunEnd = 999999999; AliCDBStorage *gStorLoc = 0; //_____________________________________________________________________________ TObject *CreatePadObject(const char *shortName, const char *description , Float_t value) { AliTRDCalPad *calPad = new AliTRDCalPad(shortName, description); for (Int_t det = 0; det < AliTRDgeometry::kNdet; ++det) { AliTRDCalROC *calROC = calPad->GetCalROC(det); for (Int_t channel = 0; channel < calROC->GetNchannels(); ++channel) { calROC->SetValue(channel, value); } } return calPad; } //_____________________________________________________________________________ TObject *CreateDetObject(const char *shortName, const char *description , Float_t value) { AliTRDCalDet *object = new AliTRDCalDet(shortName, description); for (Int_t det = 0; det < AliTRDgeometry::kNdet; ++det) { object->SetValue(det, value); } return object; } //_____________________________________________________________________________ TObject *CreatePRFWidthObject() { AliTRDCalPad *calPad = new AliTRDCalPad("PRFWidth","PRFWidth"); for (Int_t iLayer = 0; iLayer < AliTRDgeometry::kNlayer; ++iLayer) { Float_t value = 0.0; switch (iLayer) { case 0: value = 0.515; break; case 1: value = 0.502; break; case 2: value = 0.491; break; case 3: value = 0.481; break; case 4: value = 0.471; break; case 5: value = 0.463; break; default: cout << "CreatePRFWidthObject: UNEXPECTED" << endl; return 0; } for (Int_t iStack = 0; iStack < AliTRDgeometry::kNstack; ++iStack) { for (Int_t iSector = 0; iSector < AliTRDgeometry::kNsector; ++iSector) { AliTRDCalROC *calROC = calPad->GetCalROC(iLayer,iStack,iSector); for (Int_t iChannel = 0; iChannel < calROC->GetNchannels(); ++iChannel) { calROC->SetValue(iChannel, value); } } } } return calPad; } //_____________________________________________________________________________ AliTRDCalChamberStatus *CreateChamberStatusObject() { AliTRDCalChamberStatus *obj = new AliTRDCalChamberStatus("chamberstatus" ,"chamberstatus"); for (Int_t i = 0; i < AliTRDgeometry::kNdet; ++i) { obj->SetStatus(i, AliTRDCalChamberStatus::kInstalled); } return obj; } //_____________________________________________________________________________ AliTRDCalPadStatus *CreatePadStatusObject() { AliTRDCalPadStatus *obj = new AliTRDCalPadStatus("padstatus" ,"padstatus"); return obj; } //_____________________________________________________________________________ AliTRDCalMonitoring *CreateMonitoringObject() { AliTRDCalMonitoring *obj = new AliTRDCalMonitoring(); return obj; } //_____________________________________________________________________________ TClonesArray* CreateRecoParamObject() { TClonesArray *recos = new TClonesArray("AliTRDrecoParam", 3); recos->SetOwner(kTRUE); AliTRDrecoParam *rec = 0x0; AliTRDrecoParam *reco = new((*recos)[0]) AliTRDrecoParam(*(rec = AliTRDrecoParam::GetLowFluxParam())); delete rec; // further settings for low flux reco param // reco->SetThisAndThat() reco = new((*recos)[1]) AliTRDrecoParam(*(rec = AliTRDrecoParam::GetHighFluxParam())); delete rec; reco = new((*recos)[2]) AliTRDrecoParam(*(rec = AliTRDrecoParam::GetCosmicTestParam())); delete rec; return recos; } //_____________________________________________________________________________ AliCDBMetaData *CreateMetaObject(const char *objectClassName) { AliCDBMetaData *md1= new AliCDBMetaData(); md1->SetObjectClassName(objectClassName); md1->SetResponsible("Christoph Blume"); md1->SetBeamPeriod(1); md1->SetAliRootVersion("05-16-00"); //root version md1->SetComment("Ideal calibration values"); return md1; } //_____________________________________________________________________________ void StoreObject(const char *cdbPath, TObject *object, AliCDBMetaData *metaData) { AliCDBId id1(cdbPath,gkDummyRunBeg,gkDummyRunEnd); gStorLoc->Put(object,id1,metaData); } //_____________________________________________________________________________ void AliTRDCreateDummyCDB() { cout << endl << "TRD :: Creating dummy CDB for the runs " << gkDummyRunBeg << " -- " << gkDummyRunEnd << endl; AliCDBManager *man = AliCDBManager::Instance(); gStorLoc = man->GetStorage("local://$ALICE_ROOT/OCDB"); if (!gStorLoc) { return; } TObject *obj = 0; AliCDBMetaData *metaData = 0; // // Reco Param Object // metaData= new AliCDBMetaData(); metaData->SetObjectClassName("TClonesArray"); metaData->SetResponsible("Alexandru Bercuci"); metaData->SetBeamPeriod(1); metaData->SetAliRootVersion("05-19-04"); //root version metaData->SetComment("Ideal reconstruction parameters for low, high and cosmic runs"); StoreObject("TRD/Calib/RecoParam",CreateRecoParamObject(),metaData); return; // // Pad objects // metaData = CreateMetaObject("AliTRDCalPad"); obj = CreatePadObject("LocalVdrift" ,"TRD drift velocities (local variations)",1); StoreObject("TRD/Calib/LocalVdrift" ,obj,metaData); obj = CreatePadObject("LocalT0" ,"T0 (local variations)",0); StoreObject("TRD/Calib/LocalT0" ,obj,metaData); obj = CreatePadObject("GainFactor" ,"GainFactor (local variations)",1); StoreObject("TRD/Calib/LocalGainFactor" ,obj,metaData); obj = CreatePRFWidthObject(); StoreObject("TRD/Calib/PRFWidth" ,obj,metaData); // // Detector objects // metaData = CreateMetaObject("AliTRDCalDet"); obj = CreateDetObject("ChamberVdrift" ,"TRD drift velocities (detector value)", 1.5); StoreObject("TRD/Calib/ChamberVdrift" ,obj,metaData); obj = CreateDetObject("ChamberT0" ,"T0 (detector value)",0); StoreObject("TRD/Calib/ChamberT0" ,obj,metaData); obj = CreateDetObject("ChamberGainFactor" ,"GainFactor (detector value)", 1); StoreObject("TRD/Calib/ChamberGainFactor" ,obj,metaData); // // Status objects // metaData = CreateMetaObject("AliTRDCalChamberStatus"); obj = CreateChamberStatusObject(); StoreObject("TRD/Calib/ChamberStatus" ,obj,metaData); metaData = CreateMetaObject("AliTRDCalPadStatus"); obj = CreatePadStatusObject(); StoreObject("TRD/Calib/PadStatus" ,obj,metaData); // // Monitoring object // metaData = CreateMetaObject("AliTRDCalMonitoring"); obj = CreateMonitoringObject(); StoreObject("TRD/Calib/MonitoringData" ,obj,metaData); } <commit_msg>Update by Raphaelle for missing objects<commit_after>#if !defined( __CINT__) || defined(__MAKECINT__) #include <iostream> #include <TMath.h> #include <AliCDBManager.h> #include <AliCDBStorage.h> #include <AliCDBEntry.h> #include <AliCDBMetaData.h> #include "AliTRDgeometry.h" #include "AliTRDCalROC.h" #include "AliTRDCalPad.h" #include "AliTRDCalDet.h" #include "AliTRDCalChamberStatus.h" #include "AliTRDCalPadStatus.h" #include "AliTRDCalSingleChamberStatus.h" #include "AliTRDCalPIDLQ.h" #include "AliTRDCalMonitoring.h" #endif // Run numbers for the dummy file const Int_t gkDummyRunBeg = 0; const Int_t gkDummyRunEnd = 999999999; AliCDBStorage *gStorLoc = 0; //_____________________________________________________________________________ TObject *CreatePadObject(const char *shortName, const char *description , Float_t value) { AliTRDCalPad *calPad = new AliTRDCalPad(shortName, description); for (Int_t det = 0; det < AliTRDgeometry::kNdet; ++det) { AliTRDCalROC *calROC = calPad->GetCalROC(det); for (Int_t channel = 0; channel < calROC->GetNchannels(); ++channel) { calROC->SetValue(channel, value); } } return calPad; } //_____________________________________________________________________________ TObject *CreateDetObject(const char *shortName, const char *description , Float_t value) { AliTRDCalDet *object = new AliTRDCalDet(shortName, description); for (Int_t det = 0; det < AliTRDgeometry::kNdet; ++det) { object->SetValue(det, value); } return object; } //_____________________________________________________________________________ TObject *CreatePRFWidthObject() { AliTRDCalPad *calPad = new AliTRDCalPad("PRFWidth","PRFWidth"); for (Int_t iLayer = 0; iLayer < AliTRDgeometry::kNlayer; ++iLayer) { Float_t value = 0.0; switch (iLayer) { case 0: value = 0.515; break; case 1: value = 0.502; break; case 2: value = 0.491; break; case 3: value = 0.481; break; case 4: value = 0.471; break; case 5: value = 0.463; break; default: cout << "CreatePRFWidthObject: UNEXPECTED" << endl; return 0; } for (Int_t iStack = 0; iStack < AliTRDgeometry::kNstack; ++iStack) { for (Int_t iSector = 0; iSector < AliTRDgeometry::kNsector; ++iSector) { AliTRDCalROC *calROC = calPad->GetCalROC(iLayer,iStack,iSector); for (Int_t iChannel = 0; iChannel < calROC->GetNchannels(); ++iChannel) { calROC->SetValue(iChannel, value); } } } } return calPad; } //_____________________________________________________________________________ TObject *CreateChamberExB() { AliTRDCalDet *calDet = new AliTRDCalDet("lorentz angle tan","lorentz angle tan (detector value)"); for (Int_t det = 0; det < AliTRDgeometry::kNdet; ++det) { calDet->SetValue(det,TMath::Tan(9.8/360.*2*TMath::Pi())); } return calDet; } //_____________________________________________________________________________ AliTRDCalChamberStatus *CreateChamberStatusObject() { AliTRDCalChamberStatus *obj = new AliTRDCalChamberStatus("chamberstatus" ,"chamberstatus"); for (Int_t i = 0; i < AliTRDgeometry::kNdet; ++i) { obj->SetStatus(i, AliTRDCalChamberStatus::kGood); } return obj; } //_____________________________________________________________________________ AliTRDCalPadStatus *CreatePadStatusObject() { AliTRDCalPadStatus *obj = new AliTRDCalPadStatus("padstatus" ,"padstatus"); return obj; } //_____________________________________________________________________________ AliTRDCalMonitoring *CreateMonitoringObject() { AliTRDCalMonitoring *obj = new AliTRDCalMonitoring(); return obj; } //_____________________________________________________________________________ TClonesArray* CreateRecoParamObject() { TClonesArray *recos = new TClonesArray("AliTRDrecoParam", 3); recos->SetOwner(kTRUE); AliTRDrecoParam *rec = 0x0; AliTRDrecoParam *reco = new((*recos)[0]) AliTRDrecoParam(*(rec = AliTRDrecoParam::GetLowFluxParam())); delete rec; // further settings for low flux reco param // reco->SetThisAndThat() reco = new((*recos)[1]) AliTRDrecoParam(*(rec = AliTRDrecoParam::GetHighFluxParam())); delete rec; reco = new((*recos)[2]) AliTRDrecoParam(*(rec = AliTRDrecoParam::GetCosmicTestParam())); delete rec; return recos; } //_____________________________________________________________________________ AliCDBMetaData *CreateMetaObject(const char *objectClassName) { AliCDBMetaData *md1= new AliCDBMetaData(); md1->SetObjectClassName(objectClassName); md1->SetResponsible("Christoph Blume"); md1->SetBeamPeriod(1); md1->SetAliRootVersion("05-16-00"); //root version md1->SetComment("Ideal calibration values"); return md1; } //_____________________________________________________________________________ void StoreObject(const char *cdbPath, TObject *object, AliCDBMetaData *metaData) { AliCDBId id1(cdbPath,gkDummyRunBeg,gkDummyRunEnd); gStorLoc->Put(object,id1,metaData); } //_____________________________________________________________________________ void AliTRDCreateDummyCDB() { cout << endl << "TRD :: Creating dummy CDB for the runs " << gkDummyRunBeg << " -- " << gkDummyRunEnd << endl; AliCDBManager *man = AliCDBManager::Instance(); gStorLoc = man->GetStorage("local://$ALICE_ROOT/OCDB"); if (!gStorLoc) { return; } TObject *obj = 0; AliCDBMetaData *metaData = 0; // // Reco Param Object // metaData= new AliCDBMetaData(); metaData->SetObjectClassName("TClonesArray"); metaData->SetResponsible("Alexandru Bercuci"); metaData->SetBeamPeriod(1); metaData->SetAliRootVersion("05-19-04"); //root version metaData->SetComment("Ideal reconstruction parameters for low, high and cosmic runs"); StoreObject("TRD/Calib/RecoParam",CreateRecoParamObject(),metaData); //return; // // Pad objects // metaData = CreateMetaObject("AliTRDCalPad"); obj = CreatePadObject("LocalVdrift" ,"TRD drift velocities (local variations)",1); StoreObject("TRD/Calib/LocalVdrift" ,obj,metaData); obj = CreatePadObject("LocalT0" ,"T0 (local variations)",0); StoreObject("TRD/Calib/LocalT0" ,obj,metaData); obj = CreatePadObject("GainFactor" ,"GainFactor (local variations)",1); StoreObject("TRD/Calib/LocalGainFactor" ,obj,metaData); obj = CreatePRFWidthObject(); StoreObject("TRD/Calib/PRFWidth" ,obj,metaData); obj = CreatePadObject("PadNoise" ,"PadNoise (local variations)",0.12); StoreObject("TRD/Calib/PadNoise" ,obj,metaData); // // Detector objects // metaData = CreateMetaObject("AliTRDCalDet"); obj = CreateDetObject("ChamberVdrift" ,"TRD drift velocities (detector value)", 1.5); StoreObject("TRD/Calib/ChamberVdrift" ,obj,metaData); obj = CreateDetObject("ChamberT0" ,"T0 (detector value)",0); StoreObject("TRD/Calib/ChamberT0" ,obj,metaData); obj = CreateDetObject("ChamberGainFactor" ,"GainFactor (detector value)", 1); StoreObject("TRD/Calib/ChamberGainFactor" ,obj,metaData); obj = CreateDetObject("DetNoise" ,"Det Noise (simple scaling value)", 10.0); StoreObject("TRD/Calib/DetNoise" ,obj,metaData); obj = CreateChamberExB(); StoreObject("TRD/Calib/ChamberExB" ,obj,metaData); // // Status objects // metaData = CreateMetaObject("AliTRDCalChamberStatus"); obj = CreateChamberStatusObject(); StoreObject("TRD/Calib/ChamberStatus" ,obj,metaData); metaData = CreateMetaObject("AliTRDCalPadStatus"); obj = CreatePadStatusObject(); StoreObject("TRD/Calib/PadStatus" ,obj,metaData); // // Monitoring object // metaData = CreateMetaObject("AliTRDCalMonitoring"); obj = CreateMonitoringObject(); StoreObject("TRD/Calib/MonitoringData" ,obj,metaData); } <|endoftext|>
<commit_before>#include <string> #include <memory> #include <sstream> #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #include <Windows.h> #include <Shlwapi.h> #include <dxgi.h> #include <d3d11.h> #include <DirectXMath.h> #include <D3Dcompiler.h> #include <wrl.h> #endif #include <dxfw/dxfw.h> class DxfwGuard { public: DxfwGuard() : m_is_initialized_(false) { m_is_initialized_ = dxfwInitialize(); } DxfwGuard(const DxfwGuard&) = delete; DxfwGuard& operator=(const DxfwGuard&) = delete; DxfwGuard(DxfwGuard&&) = delete; DxfwGuard& operator=(DxfwGuard&&) = delete; ~DxfwGuard() { if (m_is_initialized_) { dxfwTerminate(); } } bool IsInitialized() { return m_is_initialized_; } private: bool m_is_initialized_; }; class DxfwWindowDeleter { public: void operator()(dxfwWindow* window) const { dxfwDestroyWindow(window); } }; struct Vertex { Vertex() { } Vertex(float x, float y, float z, float r, float g, float b, float a) : position(x, y, z), color(r, g, b, a) { } DirectX::XMFLOAT3 position; DirectX::XMFLOAT4 color; }; void ErrorCallback(dxfwError error) { DXFW_ERROR_TRACE(__FILE__, __LINE__, error, true); } bool InitializeDeviceAndSwapChain(dxfwWindow* window, ID3D11Device** device, IDXGISwapChain** swap_chain, ID3D11DeviceContext** device_context) { // Device settings UINT create_device_flags = 0; #ifdef _DEBUG create_device_flags |= D3D11_CREATE_DEVICE_DEBUG; #endif D3D_DRIVER_TYPE driver_types[] = { D3D_DRIVER_TYPE_HARDWARE, }; UINT num_driver_types = 1; D3D_FEATURE_LEVEL feature_levels[] = { D3D_FEATURE_LEVEL_11_0 }; UINT num_feature_levels = 1; // SwapChain settings DXGI_SWAP_CHAIN_DESC swap_chain_desc; ZeroMemory(&swap_chain_desc, sizeof(swap_chain_desc)); HWND window_handle = dxfwGetHandle(window); uint32_t width; uint32_t height; dxfwGetWindowSize(window, &width, &height); swap_chain_desc.BufferCount = 1; swap_chain_desc.BufferDesc.Width = width; swap_chain_desc.BufferDesc.Height = height; swap_chain_desc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; swap_chain_desc.BufferDesc.RefreshRate.Numerator = 60; swap_chain_desc.BufferDesc.RefreshRate.Denominator = 1; swap_chain_desc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; swap_chain_desc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; swap_chain_desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; swap_chain_desc.OutputWindow = window_handle; swap_chain_desc.SampleDesc.Count = 1; swap_chain_desc.SampleDesc.Quality = 0; swap_chain_desc.Windowed = TRUE; swap_chain_desc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; // Create auto hr = S_OK; for (decltype(num_driver_types) driver_type_index = 0; driver_type_index < num_driver_types; driver_type_index++) { D3D_DRIVER_TYPE driver_type = driver_types[driver_type_index]; D3D_FEATURE_LEVEL result_feature_level; hr = D3D11CreateDeviceAndSwapChain(NULL, driver_type, NULL, create_device_flags, feature_levels, num_feature_levels, D3D11_SDK_VERSION, &swap_chain_desc, swap_chain, device, &result_feature_level, device_context); if (SUCCEEDED(hr)) { break; } if (FAILED(hr)) { DXFW_DIRECTX_TRACE(__FILE__, __LINE__, hr, false); } } if (FAILED(hr)) { DXFW_DIRECTX_TRACE(__FILE__, __LINE__, hr, true); return false; } return true; } bool InitializeDirect3d11(dxfwWindow* window, ID3D11Device** device, IDXGISwapChain** swap_chain, ID3D11DeviceContext** device_context, ID3D11RenderTargetView** render_target_view) { // Create device bool device_ok = InitializeDeviceAndSwapChain(window, device, swap_chain, device_context); if (!device_ok) { return false; } // Create our BackBuffer ID3D11Texture2D* back_buffer; auto back_buffer_result = (*swap_chain)->GetBuffer(0, __uuidof(ID3D11Texture2D), reinterpret_cast<void**>(&back_buffer)); if (FAILED(back_buffer_result)) { DXFW_DIRECTX_TRACE(__FILE__, __LINE__, back_buffer_result, true); return false; } // Create our Render Target auto rtv_result = (*device)->CreateRenderTargetView(back_buffer, NULL, render_target_view); if (FAILED(rtv_result)) { DXFW_DIRECTX_TRACE(__FILE__, __LINE__, rtv_result, true); return false; } // Back buffer is held by RTV, so we can release it here back_buffer->Release(); // Set our Render Target (*device_context)->OMSetRenderTargets(1, render_target_view, NULL); return true; } bool InitializeVertexShader(ID3D11Device* device, ID3DBlob** buffer, ID3D11VertexShader** vs) { Microsoft::WRL::ComPtr<ID3DBlob> error_blob; TCHAR base_path[MAX_PATH]; GetModuleFileName(nullptr, base_path, MAX_PATH); PathRemoveFileSpec(base_path); TCHAR full_path[MAX_PATH]; PathCombine(full_path, base_path, TEXT("shaders.hlsl")); HRESULT shader_compilation_result = D3DCompileFromFile(full_path, nullptr, D3D_COMPILE_STANDARD_FILE_INCLUDE, "VS", "vs_4_0", 0, 0, buffer, error_blob.GetAddressOf()); if (FAILED(shader_compilation_result)) { if (error_blob) { OutputDebugStringA((const char*)error_blob->GetBufferPointer()); } DXFW_DIRECTX_TRACE(__FILE__, __LINE__, shader_compilation_result, true); return false; } HRESULT shader_creation_result = device->CreateVertexShader((*buffer)->GetBufferPointer(), (*buffer)->GetBufferSize(), NULL, vs); if (FAILED(shader_creation_result)) { DXFW_DIRECTX_TRACE(__FILE__, __LINE__, shader_creation_result, true); return false; } return true; } bool InitializePixelShader(ID3D11Device* device, ID3DBlob** buffer, ID3D11PixelShader** ps) { Microsoft::WRL::ComPtr<ID3DBlob> error_blob; TCHAR base_path[MAX_PATH]; GetModuleFileName(nullptr, base_path, MAX_PATH); PathRemoveFileSpec(base_path); TCHAR full_path[MAX_PATH]; PathCombine(full_path, base_path, TEXT("shaders.hlsl")); HRESULT shader_compilation_result = D3DCompileFromFile(full_path, nullptr, D3D_COMPILE_STANDARD_FILE_INCLUDE, "PS", "ps_4_0", 0, 0, buffer, error_blob.GetAddressOf()); if (FAILED(shader_compilation_result)) { if (error_blob) { DXFW_TRACE(__FILE__, __LINE__, (const char*)error_blob->GetBufferPointer(), false); } DXFW_DIRECTX_TRACE(__FILE__, __LINE__, shader_compilation_result, true); return false; } HRESULT shader_creation_result = device->CreatePixelShader((*buffer)->GetBufferPointer(), (*buffer)->GetBufferSize(), NULL, ps); if (FAILED(shader_creation_result)) { DXFW_DIRECTX_TRACE(__FILE__, __LINE__, shader_creation_result, true); return false; } return true; } bool InitializeScene(dxfwWindow* window, ID3D11Device* device, ID3D11DeviceContext* device_context, ID3D11Buffer** triangle_vertex_buffer, ID3DBlob** vs_buffer, ID3D11VertexShader** vs, ID3DBlob** ps_buffer, ID3D11PixelShader** ps, ID3D11InputLayout** vertex_layout) { bool vs_ok = InitializeVertexShader(device, vs_buffer, vs); if (!vs_ok) { return false; } bool ps_ok = InitializePixelShader(device, ps_buffer, ps); if (!ps_ok) { return false; } // Set Vertex and Pixel Shaders device_context->VSSetShader(*vs, 0, 0); device_context->PSSetShader(*ps, 0, 0); // Create the vertex buffer Vertex v[] = { Vertex(0.0f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 1.0f), Vertex(0.5f, -0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f), Vertex(-0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f), }; D3D11_BUFFER_DESC vertexBufferDesc; ZeroMemory(&vertexBufferDesc, sizeof(vertexBufferDesc)); vertexBufferDesc.Usage = D3D11_USAGE_DEFAULT; vertexBufferDesc.ByteWidth = sizeof(Vertex) * 3; vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; vertexBufferDesc.CPUAccessFlags = 0; vertexBufferDesc.MiscFlags = 0; D3D11_SUBRESOURCE_DATA vertexBufferData; ZeroMemory(&vertexBufferData, sizeof(vertexBufferData)); vertexBufferData.pSysMem = v; HRESULT create_vertex_buffer_result = device->CreateBuffer(&vertexBufferDesc, &vertexBufferData, triangle_vertex_buffer); if (FAILED(create_vertex_buffer_result)) { DXFW_DIRECTX_TRACE(__FILE__, __LINE__, create_vertex_buffer_result, true); } // Set the vertex buffer UINT stride = sizeof(Vertex); UINT offset = 0; device_context->IASetVertexBuffers(0, 1, triangle_vertex_buffer, &stride, &offset); // Layout description D3D11_INPUT_ELEMENT_DESC layout[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; UINT layout_elements_count = 2; // Create the Input Layout HRESULT create_input_layout_result = device->CreateInputLayout(layout, layout_elements_count, (*vs_buffer)->GetBufferPointer(), (*vs_buffer)->GetBufferSize(), vertex_layout); if (FAILED(create_input_layout_result)) { DXFW_DIRECTX_TRACE(__FILE__, __LINE__, create_input_layout_result, true); } // Set the Input Layout device_context->IASetInputLayout(*vertex_layout); // Set Primitive Topology device_context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); // Create the viewport D3D11_VIEWPORT viewport; ZeroMemory(&viewport, sizeof(D3D11_VIEWPORT)); uint32_t width; uint32_t height; dxfwGetWindowSize(window, &width, &height); viewport.TopLeftX = 0; viewport.TopLeftY = 0; viewport.Width = static_cast<float>(width); viewport.Height = static_cast<float>(height); // Set the viewport device_context->RSSetViewports(1, &viewport); return true; } int main(int /* argc */, char** /* argv */) { DxfwGuard dxfw_guard; if (!dxfw_guard.IsInitialized()) { return -1; } dxfwSetErrorCallback(ErrorCallback); std::unique_ptr<dxfwWindow, DxfwWindowDeleter> window(dxfwCreateWindow(800, 600, "Hello DirectX")); if (!window) { return -1; } Microsoft::WRL::ComPtr<ID3D11Device> device; Microsoft::WRL::ComPtr<IDXGISwapChain> swap_chain; Microsoft::WRL::ComPtr<ID3D11DeviceContext> device_context; Microsoft::WRL::ComPtr<ID3D11RenderTargetView> render_target_view; bool direct3d11_ok = InitializeDirect3d11(window.get(), device.GetAddressOf(), swap_chain.GetAddressOf(), device_context.GetAddressOf(), render_target_view.GetAddressOf()); if (!direct3d11_ok) { return -1; } Microsoft::WRL::ComPtr<ID3D11Buffer> triangle_vertex_buffer; Microsoft::WRL::ComPtr<ID3DBlob> vs_buffer; Microsoft::WRL::ComPtr<ID3DBlob> ps_buffer; Microsoft::WRL::ComPtr<ID3D11VertexShader> vs; Microsoft::WRL::ComPtr<ID3D11PixelShader> ps; Microsoft::WRL::ComPtr<ID3D11InputLayout> vertex_layout; bool scene_ok = InitializeScene(window.get(), device.Get(), device_context.Get(), triangle_vertex_buffer.GetAddressOf(), vs_buffer.GetAddressOf(), vs.GetAddressOf(), ps_buffer.GetAddressOf(), ps.GetAddressOf(), vertex_layout.GetAddressOf()); if (!scene_ok) { return -1; } while (!dxfwShouldWindowClose(window.get())) { // Clear float bgColor[4] = { (0.0f, 0.0f, 0.0f, 0.0f) }; device_context->ClearRenderTargetView(render_target_view.Get(), bgColor); // Render device_context->Draw(3, 0); // Swap buffers swap_chain->Present(0, 0); dxfwPollOsEvents(); } device_context->ClearState(); return 0; } <commit_msg>Clean up triangle sample<commit_after>#include <string> #include <memory> #include <sstream> #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #include <Windows.h> #include <Shlwapi.h> #include <dxgi.h> #include <d3d11.h> #include <DirectXMath.h> #include <D3Dcompiler.h> #include <wrl.h> #endif #include <dxfw/dxfw.h> class DxfwGuard { public: DxfwGuard() : m_is_initialized_(false) { m_is_initialized_ = dxfwInitialize(); } DxfwGuard(const DxfwGuard&) = delete; DxfwGuard& operator=(const DxfwGuard&) = delete; DxfwGuard(DxfwGuard&&) = delete; DxfwGuard& operator=(DxfwGuard&&) = delete; ~DxfwGuard() { if (m_is_initialized_) { dxfwTerminate(); } } bool IsInitialized() { return m_is_initialized_; } private: bool m_is_initialized_; }; class DxfwWindowDeleter { public: void operator()(dxfwWindow* window) const { dxfwDestroyWindow(window); } }; struct Vertex { Vertex() { } Vertex(float x, float y, float z, float r, float g, float b, float a) : position(x, y, z), color(r, g, b, a) { } DirectX::XMFLOAT3 position; DirectX::XMFLOAT4 color; }; struct DirectXState { Microsoft::WRL::ComPtr<ID3D11Device> device; Microsoft::WRL::ComPtr<IDXGISwapChain> swap_chain; Microsoft::WRL::ComPtr<ID3D11DeviceContext> device_context; Microsoft::WRL::ComPtr<ID3D11RenderTargetView> render_target_view; }; struct Scene { Microsoft::WRL::ComPtr<ID3D11Buffer> triangle_vertex_buffer; Microsoft::WRL::ComPtr<ID3DBlob> vs_buffer; Microsoft::WRL::ComPtr<ID3DBlob> ps_buffer; Microsoft::WRL::ComPtr<ID3D11VertexShader> vs; Microsoft::WRL::ComPtr<ID3D11PixelShader> ps; Microsoft::WRL::ComPtr<ID3D11InputLayout> vertex_layout; }; void ErrorCallback(dxfwError error) { DXFW_ERROR_TRACE(__FILE__, __LINE__, error, true); } void GetBasePath(TCHAR* path) { GetModuleFileName(nullptr, path, MAX_PATH); PathRemoveFileSpec(path); } bool InitializeDeviceAndSwapChain(dxfwWindow* window, DirectXState* state) { // Device settings UINT create_device_flags = 0; #ifdef _DEBUG create_device_flags |= D3D11_CREATE_DEVICE_DEBUG; #endif D3D_DRIVER_TYPE driver_types[] = { D3D_DRIVER_TYPE_HARDWARE, }; UINT num_driver_types = 1; D3D_FEATURE_LEVEL feature_levels[] = { D3D_FEATURE_LEVEL_11_0 }; UINT num_feature_levels = 1; // SwapChain settings DXGI_SWAP_CHAIN_DESC swap_chain_desc; ZeroMemory(&swap_chain_desc, sizeof(swap_chain_desc)); HWND window_handle = dxfwGetHandle(window); uint32_t width; uint32_t height; dxfwGetWindowSize(window, &width, &height); swap_chain_desc.BufferCount = 1; swap_chain_desc.BufferDesc.Width = width; swap_chain_desc.BufferDesc.Height = height; swap_chain_desc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; swap_chain_desc.BufferDesc.RefreshRate.Numerator = 60; swap_chain_desc.BufferDesc.RefreshRate.Denominator = 1; swap_chain_desc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; swap_chain_desc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; swap_chain_desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; swap_chain_desc.OutputWindow = window_handle; swap_chain_desc.SampleDesc.Count = 1; swap_chain_desc.SampleDesc.Quality = 0; swap_chain_desc.Windowed = TRUE; swap_chain_desc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; // Create auto hr = S_OK; for (decltype(num_driver_types) driver_type_index = 0; driver_type_index < num_driver_types; driver_type_index++) { D3D_DRIVER_TYPE driver_type = driver_types[driver_type_index]; D3D_FEATURE_LEVEL result_feature_level; hr = D3D11CreateDeviceAndSwapChain(NULL, driver_type, NULL, create_device_flags, feature_levels, num_feature_levels, D3D11_SDK_VERSION, &swap_chain_desc, state->swap_chain.GetAddressOf(), state->device.GetAddressOf(), &result_feature_level, state->device_context.GetAddressOf()); if (SUCCEEDED(hr)) { break; } if (FAILED(hr)) { DXFW_DIRECTX_TRACE(__FILE__, __LINE__, hr, false); } } if (FAILED(hr)) { DXFW_DIRECTX_TRACE(__FILE__, __LINE__, hr, true); return false; } return true; } bool InitializeDirect3d11(dxfwWindow* window, DirectXState* state) { // Create device bool device_ok = InitializeDeviceAndSwapChain(window, state); if (!device_ok) { return false; } // Create our BackBuffer ID3D11Texture2D* back_buffer; auto back_buffer_result = state->swap_chain->GetBuffer(0, __uuidof(ID3D11Texture2D), reinterpret_cast<void**>(&back_buffer)); if (FAILED(back_buffer_result)) { DXFW_DIRECTX_TRACE(__FILE__, __LINE__, back_buffer_result, true); return false; } // Create our Render Target auto rtv_result = state->device->CreateRenderTargetView(back_buffer, NULL, state->render_target_view.GetAddressOf()); if (FAILED(rtv_result)) { DXFW_DIRECTX_TRACE(__FILE__, __LINE__, rtv_result, true); return false; } // Back buffer is held by RTV, so we can release it here back_buffer->Release(); // Set our Render Target state->device_context->OMSetRenderTargets(1, state->render_target_view.GetAddressOf(), NULL); return true; } bool InitializeVertexShader(TCHAR* base_path, ID3D11Device* device, ID3DBlob** buffer, ID3D11VertexShader** vs) { Microsoft::WRL::ComPtr<ID3DBlob> error_blob; TCHAR full_path[MAX_PATH]; PathCombine(full_path, base_path, TEXT("shaders.hlsl")); HRESULT shader_compilation_result = D3DCompileFromFile(full_path, nullptr, D3D_COMPILE_STANDARD_FILE_INCLUDE, "VS", "vs_4_0", 0, 0, buffer, error_blob.GetAddressOf()); if (FAILED(shader_compilation_result)) { if (error_blob) { OutputDebugStringA((const char*)error_blob->GetBufferPointer()); } DXFW_DIRECTX_TRACE(__FILE__, __LINE__, shader_compilation_result, true); return false; } HRESULT shader_creation_result = device->CreateVertexShader((*buffer)->GetBufferPointer(), (*buffer)->GetBufferSize(), NULL, vs); if (FAILED(shader_creation_result)) { DXFW_DIRECTX_TRACE(__FILE__, __LINE__, shader_creation_result, true); return false; } return true; } bool InitializePixelShader(TCHAR* base_path, ID3D11Device* device, ID3DBlob** buffer, ID3D11PixelShader** ps) { Microsoft::WRL::ComPtr<ID3DBlob> error_blob; TCHAR full_path[MAX_PATH]; PathCombine(full_path, base_path, TEXT("shaders.hlsl")); HRESULT shader_compilation_result = D3DCompileFromFile(full_path, nullptr, D3D_COMPILE_STANDARD_FILE_INCLUDE, "PS", "ps_4_0", 0, 0, buffer, error_blob.GetAddressOf()); if (FAILED(shader_compilation_result)) { if (error_blob) { DXFW_TRACE(__FILE__, __LINE__, (const char*)error_blob->GetBufferPointer(), false); } DXFW_DIRECTX_TRACE(__FILE__, __LINE__, shader_compilation_result, true); return false; } HRESULT shader_creation_result = device->CreatePixelShader((*buffer)->GetBufferPointer(), (*buffer)->GetBufferSize(), NULL, ps); if (FAILED(shader_creation_result)) { DXFW_DIRECTX_TRACE(__FILE__, __LINE__, shader_creation_result, true); return false; } return true; } bool CreateVertexBuffer(ID3D11Device* device, ID3D11Buffer** triangle_vertex_buffer) { Vertex v[] = { Vertex(0.0f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 1.0f), Vertex(0.5f, -0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f), Vertex(-0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f), }; D3D11_BUFFER_DESC vertexBufferDesc; ZeroMemory(&vertexBufferDesc, sizeof(vertexBufferDesc)); vertexBufferDesc.Usage = D3D11_USAGE_DEFAULT; vertexBufferDesc.ByteWidth = sizeof(Vertex) * 3; vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; vertexBufferDesc.CPUAccessFlags = 0; vertexBufferDesc.MiscFlags = 0; D3D11_SUBRESOURCE_DATA vertexBufferData; ZeroMemory(&vertexBufferData, sizeof(vertexBufferData)); vertexBufferData.pSysMem = v; HRESULT create_vertex_buffer_result = device->CreateBuffer(&vertexBufferDesc, &vertexBufferData, triangle_vertex_buffer); if (FAILED(create_vertex_buffer_result)) { DXFW_DIRECTX_TRACE(__FILE__, __LINE__, create_vertex_buffer_result, true); return false; } return true; } bool CreateInputLayout(ID3D11Device* device, ID3DBlob* vs_buffer, ID3D11InputLayout** vertex_layout) { D3D11_INPUT_ELEMENT_DESC layout[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; UINT layout_elements_count = 2; HRESULT create_input_layout_result = device->CreateInputLayout(layout, layout_elements_count, vs_buffer->GetBufferPointer(), vs_buffer->GetBufferSize(), vertex_layout); if (FAILED(create_input_layout_result)) { DXFW_DIRECTX_TRACE(__FILE__, __LINE__, create_input_layout_result, true); return false; } return true; } void CreateViewport(dxfwWindow* window, D3D11_VIEWPORT* viewport) { ZeroMemory(viewport, sizeof(D3D11_VIEWPORT)); uint32_t width; uint32_t height; dxfwGetWindowSize(window, &width, &height); viewport->TopLeftX = 0; viewport->TopLeftY = 0; viewport->Width = static_cast<float>(width); viewport->Height = static_cast<float>(height); } bool InitializeScene(TCHAR* base_path, dxfwWindow* window, DirectXState* state, Scene* scene) { bool vs_ok = InitializeVertexShader(base_path, state->device.Get(), scene->vs_buffer.GetAddressOf(), scene->vs.GetAddressOf()); if (!vs_ok) { return false; } bool ps_ok = InitializePixelShader(base_path, state->device.Get(), scene->ps_buffer.GetAddressOf(), scene->ps.GetAddressOf()); if (!ps_ok) { return false; } state->device_context->VSSetShader(scene->vs.Get(), 0, 0); state->device_context->PSSetShader(scene->ps.Get(), 0, 0); bool vb_ok = CreateVertexBuffer(state->device.Get(), scene->triangle_vertex_buffer.GetAddressOf()); if (!vb_ok) { return false; } UINT stride = sizeof(Vertex); UINT offset = 0; state->device_context->IASetVertexBuffers(0, 1, scene->triangle_vertex_buffer.GetAddressOf(), &stride, &offset); bool il_ok = CreateInputLayout(state->device.Get(), scene->vs_buffer.Get(), scene->vertex_layout.GetAddressOf()); if (!il_ok) { return false; } state->device_context->IASetInputLayout(scene->vertex_layout.Get()); state->device_context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); D3D11_VIEWPORT viewport; CreateViewport(window, &viewport); state->device_context->RSSetViewports(1, &viewport); return true; } int main(int /* argc */, char** /* argv */) { DxfwGuard dxfw_guard; if (!dxfw_guard.IsInitialized()) { return -1; } TCHAR base_path[MAX_PATH]; GetBasePath(base_path); dxfwSetErrorCallback(ErrorCallback); std::unique_ptr<dxfwWindow, DxfwWindowDeleter> window(dxfwCreateWindow(800, 600, "Hello DirectX")); if (!window) { return -1; } DirectXState state; bool direct3d11_ok = InitializeDirect3d11(window.get(), &state); if (!direct3d11_ok) { return -1; } Scene scene; bool scene_ok = InitializeScene(base_path, window.get(), &state, &scene); if (!scene_ok) { return -1; } while (!dxfwShouldWindowClose(window.get())) { // Clear float bgColor[4] = { (0.0f, 0.0f, 0.0f, 0.0f) }; state.device_context->ClearRenderTargetView(state.render_target_view.Get(), bgColor); // Render state.device_context->Draw(3, 0); // Swap buffers state.swap_chain->Present(0, 0); dxfwPollOsEvents(); } state.device_context->ClearState(); return 0; } <|endoftext|>
<commit_before>// This file is part of the dune-hdd project: // http://users.dune-project.org/projects/dune-hdd // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_HDD_LINEARELLIPTIC_DISCRETIZATIONS_DEFAULT_HH #define DUNE_HDD_LINEARELLIPTIC_DISCRETIZATIONS_DEFAULT_HH #include <map> #include <algorithm> #include <dune/stuff/common/crtp.hh> #include <dune/stuff/common/exceptions.hh> #include <dune/stuff/la/solver.hh> #include <dune/stuff/common/logging.hh> #include <dune/pymor/operators/base.hh> #include <dune/pymor/operators/affine.hh> #include <dune/pymor/functionals/affine.hh> #include <dune/gdt/discretefunction/default.hh> #include "interfaces.hh" namespace Dune { namespace HDD { namespace LinearElliptic { namespace Discretizations { // forward template< class ImpTraits > class ContainerBasedDefault; namespace internal { template< class MatrixImp, class VectorImp > class ContainerBasedDefaultTraits { public: typedef MatrixImp MatrixType; typedef VectorImp VectorType; typedef Pymor::Operators::LinearAffinelyDecomposedContainerBased< MatrixType, VectorType > OperatorType; typedef OperatorType ProductType; typedef Pymor::Functionals::LinearAffinelyDecomposedVectorBased< VectorType > FunctionalType; }; // class ContainerBasedDefaultTraits } // namespace internal template< class ImpTraits > class CachedDefault : public DiscretizationInterface< ImpTraits > { typedef DiscretizationInterface< ImpTraits > BaseType; typedef CachedDefault< ImpTraits > ThisType; public: using typename BaseType::GridViewType; using typename BaseType::BoundaryInfoType; using typename BaseType::ProblemType; using typename BaseType::TestSpaceType; using typename BaseType::AnsatzSpaceType; using typename BaseType::VectorType; private: typedef Stuff::Grid::BoundaryInfoProvider< typename GridViewType::Intersection > BoundaryInfoProvider; public: static std::string static_id() { return "hdd.linearelliptic.discretizations.cached"; } CachedDefault(const std::shared_ptr< const TestSpaceType >& test_spc, const std::shared_ptr< const AnsatzSpaceType > ansatz_spc, const Stuff::Common::Configuration& bnd_inf_cfg, const ProblemType& prb) : BaseType(prb) , test_space_(test_spc) , ansatz_space_(ansatz_spc) , boundary_info_cfg_(bnd_inf_cfg) , boundary_info_(BoundaryInfoProvider::create(boundary_info_cfg_.get< std::string >("type"), boundary_info_cfg_)) , problem_(prb) {} CachedDefault(const ThisType& other) = default; ThisType& operator=(const ThisType& other) = delete; const std::shared_ptr< const TestSpaceType >& test_space() const { return test_space_; } const std::shared_ptr< const AnsatzSpaceType >& ansatz_space() const { return test_space_; } const GridViewType& grid_view() const { return test_space_->grid_view(); } const Stuff::Common::Configuration& boundary_info_cfg() const { return boundary_info_cfg_; } const BoundaryInfoType& boundary_info() const { return *boundary_info_; } const ProblemType& problem() const { return problem_; } VectorType create_vector() const { return VectorType(ansatz_space_->mapper().size()); } void visualize(const VectorType& vector, const std::string filename, const std::string name, Pymor::Parameter mu = Pymor::Parameter()) const { VectorType tmp = vector.copy(); const auto vectors = this->available_vectors(); const auto result = std::find(vectors.begin(), vectors.end(), "dirichlet"); if (result != vectors.end()) { const auto dirichlet_vector = this->get_vector("dirichlet"); if (dirichlet_vector.parametric()) { const Pymor::Parameter mu_dirichlet = this->map_parameter(mu, "dirichlet"); if (mu_dirichlet.type() != dirichlet_vector.parameter_type()) DUNE_THROW(Pymor::Exceptions::wrong_parameter_type, mu_dirichlet.type() << " vs. " << dirichlet_vector.parameter_type()); tmp = dirichlet_vector.freeze_parameter(mu); } else tmp = *(dirichlet_vector.affine_part()); tmp += vector; } const GDT::ConstDiscreteFunction< AnsatzSpaceType, VectorType >function(*(ansatz_space()), tmp, name); function.visualize(filename); } // ... visualize(...) void solve(VectorType& vector, const Pymor::Parameter mu = Pymor::Parameter()) const { auto logger = DSC::TimedLogger().get(static_id()); const auto search_result = cache_.find(mu); if (search_result == cache_.end()) { logger.info() << "solving"; if (!mu.empty()) logger.info() << " for mu = " << mu; logger.info() << "... " << std::endl; uncached_solve(vector, mu); cache_.insert(std::make_pair(mu, Stuff::Common::make_unique< VectorType >(vector.copy()))); } else { logger.info() << "retrieving solution "; if (!mu.empty()) logger.info() << "for mu = " << mu << " "; logger.info() << "from cache... " << std::endl; const auto& result = *(search_result->second); vector = result; } } // ... solve(...) void uncached_solve(VectorType& vector, const Pymor::Parameter mu) const { CHECK_AND_CALL_CRTP(this->as_imp().uncached_solve(vector, mu)); } protected: const std::shared_ptr< const TestSpaceType > test_space_; const std::shared_ptr< const AnsatzSpaceType > ansatz_space_; const Stuff::Common::Configuration boundary_info_cfg_; const std::shared_ptr< const BoundaryInfoType > boundary_info_; const ProblemType& problem_; mutable std::map< Pymor::Parameter, std::shared_ptr< VectorType > > cache_; }; // class CachedDefault template< class ImpTraits > class ContainerBasedDefault : public CachedDefault< ImpTraits > { typedef CachedDefault< ImpTraits > BaseType; typedef ContainerBasedDefault< ImpTraits > ThisType; public: typedef ImpTraits Traits; typedef typename Traits::MatrixType MatrixType; typedef typename Traits::OperatorType OperatorType; typedef typename Traits::ProductType ProductType; typedef typename Traits::FunctionalType FunctionalType; using typename BaseType::GridViewType; using typename BaseType::BoundaryInfoType; using typename BaseType::ProblemType; using typename BaseType::TestSpaceType; using typename BaseType::AnsatzSpaceType; using typename BaseType::VectorType; protected: typedef Pymor::LA::AffinelyDecomposedContainer< MatrixType > AffinelyDecomposedMatrixType; typedef Pymor::LA::AffinelyDecomposedContainer< VectorType > AffinelyDecomposedVectorType; public: static std::string static_id() { return "hdd.linearelliptic.discretizations.containerbased"; } ContainerBasedDefault(const std::shared_ptr< const TestSpaceType >& test_spc, const std::shared_ptr< const AnsatzSpaceType >& ansatz_spc, const Stuff::Common::Configuration& bnd_inf_cfg, const ProblemType& prb) : BaseType(test_spc, ansatz_spc, bnd_inf_cfg, prb) , container_based_initialized_(false) , purely_neumann_(false) , matrix_(std::make_shared< AffinelyDecomposedMatrixType >()) , rhs_(std::make_shared< AffinelyDecomposedVectorType >()) {} ContainerBasedDefault(const ThisType& other) = default; ThisType& operator=(const ThisType& other) = delete; std::shared_ptr< AffinelyDecomposedMatrixType >& system_matrix() { return matrix_; } const std::shared_ptr< const AffinelyDecomposedMatrixType >& system_matrix() const { return matrix_; } std::shared_ptr< AffinelyDecomposedVectorType > rhs() { return rhs_; } const std::shared_ptr< const AffinelyDecomposedVectorType >& rhs() const { return rhs_; } OperatorType get_operator() const { assert_everything_is_ready(); return OperatorType(*matrix_); } FunctionalType get_rhs() const { assert_everything_is_ready(); return FunctionalType(*rhs_); } std::vector< std::string > available_products() const { if (products_.size() == 0) return std::vector< std::string >(); std::vector< std::string > ret; for (const auto& pair : products_) ret.push_back(pair.first); return ret; } // ... available_products(...) ProductType get_product(const std::string id) const { if (products_.size() == 0) DUNE_THROW(Stuff::Exceptions::you_are_using_this_wrong, "Do not call get_product() if available_products() is empty!"); const auto result = products_.find(id); if (result == products_.end()) DUNE_THROW(Stuff::Exceptions::wrong_input_given, id); return ProductType(*(result->second)); } // ... get_product(...) std::vector< std::string > available_vectors() const { if (vectors_.size() == 0) return std::vector< std::string >(); std::vector< std::string > ret; for (const auto& pair : vectors_) ret.push_back(pair.first); return ret; } // ... available_vectors(...) AffinelyDecomposedVectorType get_vector(const std::string id) const { if (vectors_.size() == 0) DUNE_THROW(Stuff::Exceptions::you_are_using_this_wrong, "Do not call get_vector() if available_vectors() is empty!"); const auto result = vectors_.find(id); if (result == vectors_.end()) DUNE_THROW(Stuff::Exceptions::wrong_input_given, id); return *(result->second); } // ... get_vector(...) /** * \brief solves for u_0 */ void uncached_solve(VectorType& vector, const Pymor::Parameter mu = Pymor::Parameter()) const { auto logger = DSC::TimedLogger().get(static_id()); assert_everything_is_ready(); if (mu.type() != this->parameter_type()) DUNE_THROW(Pymor::Exceptions::wrong_parameter_type, mu.type() << " vs. " << this->parameter_type()); const auto& rhs = *(this->rhs_); const auto& matrix = *(this->matrix_); if (purely_neumann_) { VectorType tmp_rhs = rhs.parametric() ? rhs.freeze_parameter(this->map_parameter(mu, "rhs")) : *(rhs.affine_part()); MatrixType tmp_system_matrix = matrix.parametric() ? matrix.freeze_parameter(this->map_parameter(mu, "lhs")) : *(matrix.affine_part()); tmp_system_matrix.unit_row(0); tmp_rhs.set_entry(0, 0.0); Stuff::LA::Solver< MatrixType >(tmp_system_matrix).apply(tmp_rhs, vector); vector -= vector.mean(); } else { // compute right hand side vector logger.debug() << "computing right hand side..." << std::endl; std::shared_ptr< const VectorType > rhs_vector; if (!rhs.parametric()) rhs_vector = rhs.affine_part(); else { const Pymor::Parameter mu_rhs = this->map_parameter(mu, "rhs"); rhs_vector = std::make_shared< const VectorType >(rhs.freeze_parameter(mu_rhs)); } logger.debug() << "computing system matrix..." << std::endl; const OperatorType lhsOperator(matrix); if (lhsOperator.parametric()) { const Pymor::Parameter mu_lhs = this->map_parameter(mu, "lhs"); const auto frozenOperator = lhsOperator.freeze_parameter(mu_lhs); frozenOperator.apply_inverse(*rhs_vector, vector); } else { const auto nonparametricOperator = lhsOperator.affine_part(); nonparametricOperator.apply_inverse(*rhs_vector, vector); } } } // ... uncached_solve(...) protected: void assert_everything_is_ready() const { if (!container_based_initialized_) DUNE_THROW(Stuff::Exceptions::you_are_using_this_wrong, "The implemented discretization has to fill 'matrix_' and 'rhs_' during init() and set " << "container_based_initialized_ to true!\n" << "The user has to call init() before calling any other method!"); } // ... assert_everything_is_ready() bool container_based_initialized_; bool purely_neumann_; std::shared_ptr< AffinelyDecomposedMatrixType > matrix_; std::shared_ptr< AffinelyDecomposedVectorType > rhs_; mutable std::map< std::string, std::shared_ptr< AffinelyDecomposedMatrixType > > products_; mutable std::map< std::string, std::shared_ptr< AffinelyDecomposedVectorType > > vectors_; }; // class ContainerBasedDefault } // namespace Discretizations } // namespace LinearElliptic } // namespace HDD } // namespace Dune #endif // DUNE_HDD_LINEARELLIPTIC_DISCRETIZATIONS_DEFAULT_HH <commit_msg>[linearelliptic.discretizations.base] update CachedDefault<commit_after>// This file is part of the dune-hdd project: // http://users.dune-project.org/projects/dune-hdd // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_HDD_LINEARELLIPTIC_DISCRETIZATIONS_DEFAULT_HH #define DUNE_HDD_LINEARELLIPTIC_DISCRETIZATIONS_DEFAULT_HH #include <map> #include <algorithm> #include <dune/stuff/common/crtp.hh> #include <dune/stuff/common/exceptions.hh> #include <dune/stuff/la/solver.hh> #include <dune/stuff/common/logging.hh> #include <dune/pymor/operators/base.hh> #include <dune/pymor/operators/affine.hh> #include <dune/pymor/functionals/affine.hh> #include <dune/gdt/discretefunction/default.hh> #include "interfaces.hh" namespace Dune { namespace HDD { namespace LinearElliptic { namespace Discretizations { // forward template< class ImpTraits > class ContainerBasedDefault; namespace internal { template< class MatrixImp, class VectorImp > class ContainerBasedDefaultTraits { public: typedef MatrixImp MatrixType; typedef VectorImp VectorType; typedef Pymor::Operators::LinearAffinelyDecomposedContainerBased< MatrixType, VectorType > OperatorType; typedef OperatorType ProductType; typedef Pymor::Functionals::LinearAffinelyDecomposedVectorBased< VectorType > FunctionalType; }; // class ContainerBasedDefaultTraits } // namespace internal template< class ImpTraits > class CachedDefault : public DiscretizationInterface< ImpTraits > { typedef DiscretizationInterface< ImpTraits > BaseType; typedef CachedDefault< ImpTraits > ThisType; public: using typename BaseType::GridViewType; using typename BaseType::BoundaryInfoType; using typename BaseType::ProblemType; using typename BaseType::TestSpaceType; using typename BaseType::AnsatzSpaceType; using typename BaseType::VectorType; private: typedef Stuff::Grid::BoundaryInfoProvider< typename GridViewType::Intersection > BoundaryInfoProvider; public: static std::string static_id() { return "hdd.linearelliptic.discretizations.cached"; } CachedDefault(const std::shared_ptr< const TestSpaceType >& test_spc, const std::shared_ptr< const AnsatzSpaceType > ansatz_spc, const Stuff::Common::Configuration& bnd_inf_cfg, const ProblemType& prb) : BaseType(prb) , test_space_(test_spc) , ansatz_space_(ansatz_spc) , boundary_info_cfg_(bnd_inf_cfg) , boundary_info_(BoundaryInfoProvider::create(boundary_info_cfg_.get< std::string >("type"), boundary_info_cfg_)) , problem_(prb) {} CachedDefault(const ThisType& other) = default; ThisType& operator=(const ThisType& other) = delete; const std::shared_ptr< const TestSpaceType >& test_space() const { return test_space_; } const std::shared_ptr< const AnsatzSpaceType >& ansatz_space() const { return test_space_; } const GridViewType& grid_view() const { return test_space_->grid_view(); } const Stuff::Common::Configuration& boundary_info_cfg() const { return boundary_info_cfg_; } const BoundaryInfoType& boundary_info() const { return *boundary_info_; } const ProblemType& problem() const { return problem_; } VectorType create_vector() const { return VectorType(ansatz_space_->mapper().size()); } void visualize(const VectorType& vector, const std::string filename, const std::string name, Pymor::Parameter mu = Pymor::Parameter()) const { VectorType tmp = vector.copy(); const auto vectors = this->available_vectors(); const auto result = std::find(vectors.begin(), vectors.end(), "dirichlet"); if (result != vectors.end()) { const auto dirichlet_vector = this->get_vector("dirichlet"); if (dirichlet_vector.parametric()) { const Pymor::Parameter mu_dirichlet = this->map_parameter(mu, "dirichlet"); if (mu_dirichlet.type() != dirichlet_vector.parameter_type()) DUNE_THROW(Pymor::Exceptions::wrong_parameter_type, mu_dirichlet.type() << " vs. " << dirichlet_vector.parameter_type()); tmp = dirichlet_vector.freeze_parameter(mu); } else tmp = *(dirichlet_vector.affine_part()); tmp += vector; } const GDT::ConstDiscreteFunction< AnsatzSpaceType, VectorType >function(*(ansatz_space()), tmp, name); function.visualize(filename); } // ... visualize(...) using BaseType::solve; void solve(const DSC::Configuration options, VectorType& vector, const Pymor::Parameter mu = Pymor::Parameter()) const { auto logger = DSC::TimedLogger().get(static_id()); const auto options_in_cache = cache_.find(options); bool exists = (options_in_cache != cache_.end()); typename std::map< Pymor::Parameter, std::shared_ptr< VectorType > >::const_iterator options_and_mu_in_cache; if (exists) { options_and_mu_in_cache = options_in_cache->second.find(mu); exists = (options_and_mu_in_cache != options_in_cache->second.end()); } if (!exists) { logger.info() << "solving"; if (!mu.empty()) logger.info() << " for mu = " << mu; logger.info() << "... " << std::endl; uncached_solve(options, vector, mu); cache_[options][mu] = Stuff::Common::make_unique< VectorType >(vector.copy()); } else { logger.info() << "retrieving solution "; if (!mu.empty()) logger.info() << "for mu = " << mu << " "; logger.info() << "from cache... " << std::endl; const auto& result = *(options_and_mu_in_cache->second); vector = result; } } // ... solve(...) void uncached_solve(const DSC::Configuration options, VectorType& vector, const Pymor::Parameter mu) const { CHECK_AND_CALL_CRTP(this->as_imp().uncached_solve(options, vector, mu)); } protected: const std::shared_ptr< const TestSpaceType > test_space_; const std::shared_ptr< const AnsatzSpaceType > ansatz_space_; const Stuff::Common::Configuration boundary_info_cfg_; const std::shared_ptr< const BoundaryInfoType > boundary_info_; const ProblemType& problem_; mutable std::map< DSC::Configuration, std::map< Pymor::Parameter, std::shared_ptr< VectorType > > > cache_; }; // class CachedDefault template< class ImpTraits > class ContainerBasedDefault : public CachedDefault< ImpTraits > { typedef CachedDefault< ImpTraits > BaseType; typedef ContainerBasedDefault< ImpTraits > ThisType; public: typedef ImpTraits Traits; typedef typename Traits::MatrixType MatrixType; typedef typename Traits::OperatorType OperatorType; typedef typename Traits::ProductType ProductType; typedef typename Traits::FunctionalType FunctionalType; using typename BaseType::GridViewType; using typename BaseType::BoundaryInfoType; using typename BaseType::ProblemType; using typename BaseType::TestSpaceType; using typename BaseType::AnsatzSpaceType; using typename BaseType::VectorType; protected: typedef Pymor::LA::AffinelyDecomposedContainer< MatrixType > AffinelyDecomposedMatrixType; typedef Pymor::LA::AffinelyDecomposedContainer< VectorType > AffinelyDecomposedVectorType; public: static std::string static_id() { return "hdd.linearelliptic.discretizations.containerbased"; } ContainerBasedDefault(const std::shared_ptr< const TestSpaceType >& test_spc, const std::shared_ptr< const AnsatzSpaceType >& ansatz_spc, const Stuff::Common::Configuration& bnd_inf_cfg, const ProblemType& prb) : BaseType(test_spc, ansatz_spc, bnd_inf_cfg, prb) , container_based_initialized_(false) , purely_neumann_(false) , matrix_(std::make_shared< AffinelyDecomposedMatrixType >()) , rhs_(std::make_shared< AffinelyDecomposedVectorType >()) {} ContainerBasedDefault(const ThisType& other) = default; ThisType& operator=(const ThisType& other) = delete; std::shared_ptr< AffinelyDecomposedMatrixType >& system_matrix() { return matrix_; } const std::shared_ptr< const AffinelyDecomposedMatrixType >& system_matrix() const { return matrix_; } std::shared_ptr< AffinelyDecomposedVectorType > rhs() { return rhs_; } const std::shared_ptr< const AffinelyDecomposedVectorType >& rhs() const { return rhs_; } OperatorType get_operator() const { assert_everything_is_ready(); return OperatorType(*matrix_); } FunctionalType get_rhs() const { assert_everything_is_ready(); return FunctionalType(*rhs_); } std::vector< std::string > available_products() const { if (products_.size() == 0) return std::vector< std::string >(); std::vector< std::string > ret; for (const auto& pair : products_) ret.push_back(pair.first); return ret; } // ... available_products(...) ProductType get_product(const std::string id) const { if (products_.size() == 0) DUNE_THROW(Stuff::Exceptions::you_are_using_this_wrong, "Do not call get_product() if available_products() is empty!"); const auto result = products_.find(id); if (result == products_.end()) DUNE_THROW(Stuff::Exceptions::wrong_input_given, id); return ProductType(*(result->second)); } // ... get_product(...) std::vector< std::string > available_vectors() const { if (vectors_.size() == 0) return std::vector< std::string >(); std::vector< std::string > ret; for (const auto& pair : vectors_) ret.push_back(pair.first); return ret; } // ... available_vectors(...) AffinelyDecomposedVectorType get_vector(const std::string id) const { if (vectors_.size() == 0) DUNE_THROW(Stuff::Exceptions::you_are_using_this_wrong, "Do not call get_vector() if available_vectors() is empty!"); const auto result = vectors_.find(id); if (result == vectors_.end()) DUNE_THROW(Stuff::Exceptions::wrong_input_given, id); return *(result->second); } // ... get_vector(...) /** * \brief solves for u_0 */ void uncached_solve(VectorType& vector, const Pymor::Parameter mu = Pymor::Parameter()) const { auto logger = DSC::TimedLogger().get(static_id()); assert_everything_is_ready(); if (mu.type() != this->parameter_type()) DUNE_THROW(Pymor::Exceptions::wrong_parameter_type, mu.type() << " vs. " << this->parameter_type()); const auto& rhs = *(this->rhs_); const auto& matrix = *(this->matrix_); if (purely_neumann_) { VectorType tmp_rhs = rhs.parametric() ? rhs.freeze_parameter(this->map_parameter(mu, "rhs")) : *(rhs.affine_part()); MatrixType tmp_system_matrix = matrix.parametric() ? matrix.freeze_parameter(this->map_parameter(mu, "lhs")) : *(matrix.affine_part()); tmp_system_matrix.unit_row(0); tmp_rhs.set_entry(0, 0.0); Stuff::LA::Solver< MatrixType >(tmp_system_matrix).apply(tmp_rhs, vector); vector -= vector.mean(); } else { // compute right hand side vector logger.debug() << "computing right hand side..." << std::endl; std::shared_ptr< const VectorType > rhs_vector; if (!rhs.parametric()) rhs_vector = rhs.affine_part(); else { const Pymor::Parameter mu_rhs = this->map_parameter(mu, "rhs"); rhs_vector = std::make_shared< const VectorType >(rhs.freeze_parameter(mu_rhs)); } logger.debug() << "computing system matrix..." << std::endl; const OperatorType lhsOperator(matrix); if (lhsOperator.parametric()) { const Pymor::Parameter mu_lhs = this->map_parameter(mu, "lhs"); const auto frozenOperator = lhsOperator.freeze_parameter(mu_lhs); frozenOperator.apply_inverse(*rhs_vector, vector); } else { const auto nonparametricOperator = lhsOperator.affine_part(); nonparametricOperator.apply_inverse(*rhs_vector, vector); } } } // ... uncached_solve(...) protected: void assert_everything_is_ready() const { if (!container_based_initialized_) DUNE_THROW(Stuff::Exceptions::you_are_using_this_wrong, "The implemented discretization has to fill 'matrix_' and 'rhs_' during init() and set " << "container_based_initialized_ to true!\n" << "The user has to call init() before calling any other method!"); } // ... assert_everything_is_ready() bool container_based_initialized_; bool purely_neumann_; std::shared_ptr< AffinelyDecomposedMatrixType > matrix_; std::shared_ptr< AffinelyDecomposedVectorType > rhs_; mutable std::map< std::string, std::shared_ptr< AffinelyDecomposedMatrixType > > products_; mutable std::map< std::string, std::shared_ptr< AffinelyDecomposedVectorType > > vectors_; }; // class ContainerBasedDefault } // namespace Discretizations } // namespace LinearElliptic } // namespace HDD } // namespace Dune #endif // DUNE_HDD_LINEARELLIPTIC_DISCRETIZATIONS_DEFAULT_HH <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org 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 version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #include <stdio.h> #include <dlfcn.h> #if MAC_OS_X_VERSION_MIN_REQUIRED < 1070 #include <cxxabi.h> #else #include <typeinfo> #endif #include <boost/unordered_map.hpp> #include <rtl/instance.hxx> #include <rtl/strbuf.hxx> #include <rtl/ustrbuf.hxx> #include <osl/diagnose.h> #include <osl/mutex.hxx> #include <com/sun/star/uno/genfunc.hxx> #include "com/sun/star/uno/RuntimeException.hpp" #include <typelib/typedescription.hxx> #include <uno/any2.h> #include "share.hxx" using namespace ::std; using namespace ::osl; using namespace ::rtl; using namespace ::com::sun::star::uno; #if MAC_OS_X_VERSION_MIN_REQUIRED < 1070 using namespace ::__cxxabiv1; #endif namespace CPPU_CURRENT_NAMESPACE { #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1070 // MacOSX10.4u.sdk/usr/include/c++/4.0.0/cxxabi.h defined // __cxxabiv1::__class_type_info and __cxxabiv1::__si_class_type_info but // MacOSX10.7.sdk/usr/include/cxxabi.h no longer does, so instances of those // classes need to be created manually: // std::type_info defined in <typeinfo> offers a protected ctor: struct FAKE_type_info: public std::type_info { FAKE_type_info(char const * name): type_info(name) {} }; // Modeled after __cxxabiv1::__si_class_type_info defined in // MacOSX10.4u.sdk/usr/include/c++/4.0.0/cxxabi.h (i.e., // abi::__si_class_type_info documented at // <http://www.codesourcery.com/public/cxx-abi/abi.html#rtti>): struct FAKE_si_class_type_info: public FAKE_type_info { FAKE_si_class_type_info(char const * name, std::type_info const * theBase): FAKE_type_info(name), base(theBase) {} std::type_info const * base; // actually a __cxxabiv1::__class_type_info pointer }; struct Base {}; struct Derived: Base {}; std::type_info * create_FAKE_class_type_info(char const * name) { std::type_info * p = new FAKE_type_info(name); // cxxabiv1::__class_type_info has no data members in addition to // std::type_info *reinterpret_cast< void ** >(p) = *reinterpret_cast< void * const * >( &typeid(Base)); // copy correct __cxxabiv1::__class_type_info vtable into place return p; } std::type_info * create_FAKE_si_class_type_info( char const * name, std::type_info const * base) { std::type_info * p = new FAKE_si_class_type_info(name, base); *reinterpret_cast< void ** >(p) = *reinterpret_cast< void * const * >( &typeid(Derived)); // copy correct __cxxabiv1::__si_class_type_info vtable into place return p; } #endif void dummy_can_throw_anything( char const * ) { } //================================================================================================== static OUString toUNOname( char const * p ) SAL_THROW(()) { #if OSL_DEBUG_LEVEL > 1 char const * start = p; #endif // example: N3com3sun4star4lang24IllegalArgumentExceptionE OUStringBuffer buf( 64 ); OSL_ASSERT( 'N' == *p ); ++p; // skip N while ('E' != *p) { // read chars count long n = (*p++ - '0'); while ('0' <= *p && '9' >= *p) { n *= 10; n += (*p++ - '0'); } buf.appendAscii( p, n ); p += n; if ('E' != *p) buf.append( (sal_Unicode)'.' ); } #if OSL_DEBUG_LEVEL > 1 OUString ret( buf.makeStringAndClear() ); OString c_ret( OUStringToOString( ret, RTL_TEXTENCODING_ASCII_US ) ); fprintf( stderr, "> toUNOname(): %s => %s\n", start, c_ret.getStr() ); return ret; #else return buf.makeStringAndClear(); #endif } //================================================================================================== class RTTI { typedef boost::unordered_map< OUString, type_info *, OUStringHash > t_rtti_map; Mutex m_mutex; t_rtti_map m_rttis; t_rtti_map m_generatedRttis; void * m_hApp; public: RTTI() SAL_THROW(()); ~RTTI() SAL_THROW(()); type_info * getRTTI( typelib_CompoundTypeDescription * ) SAL_THROW(()); }; //__________________________________________________________________________________________________ RTTI::RTTI() SAL_THROW(()) : m_hApp( dlopen( 0, RTLD_LAZY ) ) { } //__________________________________________________________________________________________________ RTTI::~RTTI() SAL_THROW(()) { dlclose( m_hApp ); } //__________________________________________________________________________________________________ type_info * RTTI::getRTTI( typelib_CompoundTypeDescription *pTypeDescr ) SAL_THROW(()) { type_info * rtti; OUString const & unoName = *(OUString const *)&pTypeDescr->aBase.pTypeName; MutexGuard guard( m_mutex ); t_rtti_map::const_iterator iFind( m_rttis.find( unoName ) ); if (iFind == m_rttis.end()) { // RTTI symbol OStringBuffer buf( 64 ); buf.append( RTL_CONSTASCII_STRINGPARAM("_ZTIN") ); sal_Int32 index = 0; do { OUString token( unoName.getToken( 0, '.', index ) ); buf.append( token.getLength() ); OString c_token( OUStringToOString( token, RTL_TEXTENCODING_ASCII_US ) ); buf.append( c_token ); } while (index >= 0); buf.append( 'E' ); OString symName( buf.makeStringAndClear() ); rtti = (type_info *)dlsym( m_hApp, symName.getStr() ); if (rtti) { pair< t_rtti_map::iterator, bool > insertion( m_rttis.insert( t_rtti_map::value_type( unoName, rtti ) ) ); SAL_WARN_IF( !insertion.second, "bridges", "inserting new rtti failed" ); } else { // try to lookup the symbol in the generated rtti map t_rtti_map::const_iterator iFind2( m_generatedRttis.find( unoName ) ); if (iFind2 == m_generatedRttis.end()) { // we must generate it ! // symbol and rtti-name is nearly identical, // the symbol is prefixed with _ZTI char const * rttiName = symName.getStr() +4; #if OSL_DEBUG_LEVEL > 1 fprintf( stderr,"generated rtti for %s\n", rttiName ); #endif if (pTypeDescr->pBaseTypeDescription) { // ensure availability of base type_info * base_rtti = getRTTI( (typelib_CompoundTypeDescription *)pTypeDescr->pBaseTypeDescription ); #if MAC_OS_X_VERSION_MIN_REQUIRED < 1070 rtti = new __si_class_type_info( strdup( rttiName ), (__class_type_info *)base_rtti ); #else rtti = create_FAKE_si_class_type_info( strdup( rttiName ), base_rtti ); #endif } else { // this class has no base class #if MAC_OS_X_VERSION_MIN_REQUIRED < 1070 rtti = new __class_type_info( strdup( rttiName ) ); #else rtti = create_FAKE_class_type_info( strdup( rttiName ) ); #endif } pair< t_rtti_map::iterator, bool > insertion( m_generatedRttis.insert( t_rtti_map::value_type( unoName, rtti ) ) ); SAL_WARN_IF( !insertion.second, "bridges", "inserting new generated rtti failed" ); } else // taking already generated rtti { rtti = iFind2->second; } } } else { rtti = iFind->second; } return rtti; } struct RTTISingleton: public rtl::Static< RTTI, RTTISingleton > {}; //-------------------------------------------------------------------------------------------------- static void deleteException( void * pExc ) { __cxa_exception const * header = ((__cxa_exception const *)pExc - 1); typelib_TypeDescription * pTD = 0; OUString unoName( toUNOname( header->exceptionType->name() ) ); ::typelib_typedescription_getByName( &pTD, unoName.pData ); OSL_ENSURE( pTD, "### unknown exception type! leaving out destruction => leaking!!!" ); if (pTD) { ::uno_destructData( pExc, pTD, cpp_release ); ::typelib_typedescription_release( pTD ); } } //================================================================================================== void raiseException( uno_Any * pUnoExc, uno_Mapping * pUno2Cpp ) { #if OSL_DEBUG_LEVEL > 1 OString cstr( OUStringToOString( *reinterpret_cast< OUString const * >( &pUnoExc->pType->pTypeName ), RTL_TEXTENCODING_ASCII_US ) ); fprintf( stderr, "> uno exception occurred: %s\n", cstr.getStr() ); #endif void * pCppExc; type_info * rtti; { // construct cpp exception object typelib_TypeDescription * pTypeDescr = 0; TYPELIB_DANGER_GET( &pTypeDescr, pUnoExc->pType ); OSL_ASSERT( pTypeDescr ); if (! pTypeDescr) { throw RuntimeException( OUString( RTL_CONSTASCII_USTRINGPARAM("cannot get typedescription for type ") ) + *reinterpret_cast< OUString const * >( &pUnoExc->pType->pTypeName ), Reference< XInterface >() ); } pCppExc = __cxa_allocate_exception( pTypeDescr->nSize ); ::uno_copyAndConvertData( pCppExc, pUnoExc->pData, pTypeDescr, pUno2Cpp ); // destruct uno exception ::uno_any_destruct( pUnoExc, 0 ); rtti = (type_info *)RTTISingleton::get().getRTTI( (typelib_CompoundTypeDescription *) pTypeDescr ); TYPELIB_DANGER_RELEASE( pTypeDescr ); OSL_ENSURE( rtti, "### no rtti for throwing exception!" ); if (! rtti) { throw RuntimeException( OUString( RTL_CONSTASCII_USTRINGPARAM("no rtti for type ") ) + *reinterpret_cast< OUString const * >( &pUnoExc->pType->pTypeName ), Reference< XInterface >() ); } } __cxa_throw( pCppExc, rtti, deleteException ); } //================================================================================================== void fillUnoException( __cxa_exception * header, uno_Any * pUnoExc, uno_Mapping * pCpp2Uno ) { if (! header) { RuntimeException aRE( OUString( RTL_CONSTASCII_USTRINGPARAM("no exception header!") ), Reference< XInterface >() ); Type const & rType = ::getCppuType( &aRE ); uno_type_any_constructAndConvert( pUnoExc, &aRE, rType.getTypeLibType(), pCpp2Uno ); #if OSL_DEBUG_LEVEL > 0 OString cstr( OUStringToOString( aRE.Message, RTL_TEXTENCODING_ASCII_US ) ); OSL_FAIL( cstr.getStr() ); #endif return; } typelib_TypeDescription * pExcTypeDescr = 0; OUString unoName( toUNOname( header->exceptionType->name() ) ); #if OSL_DEBUG_LEVEL > 1 OString cstr_unoName( OUStringToOString( unoName, RTL_TEXTENCODING_ASCII_US ) ); fprintf( stderr, "> c++ exception occurred: %s\n", cstr_unoName.getStr() ); #endif typelib_typedescription_getByName( &pExcTypeDescr, unoName.pData ); if (0 == pExcTypeDescr) { RuntimeException aRE( OUString( RTL_CONSTASCII_USTRINGPARAM("exception type not found: ") ) + unoName, Reference< XInterface >() ); Type const & rType = ::getCppuType( &aRE ); uno_type_any_constructAndConvert( pUnoExc, &aRE, rType.getTypeLibType(), pCpp2Uno ); #if OSL_DEBUG_LEVEL > 0 OString cstr( OUStringToOString( aRE.Message, RTL_TEXTENCODING_ASCII_US ) ); OSL_FAIL( cstr.getStr() ); #endif } else { // construct uno exception any uno_any_constructAndConvert( pUnoExc, header->adjustedPtr, pExcTypeDescr, pCpp2Uno ); typelib_typedescription_release( pExcTypeDescr ); } } } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>Check MACOSX_SDK_VERSION, not MAC_OS_X_VERSION_MIN_REQUIRED<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org 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 version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #include <stdio.h> #include <dlfcn.h> #if MACOSX_SDK_VERSION < 1070 #include <cxxabi.h> #else #include <typeinfo> #endif #include <boost/unordered_map.hpp> #include <rtl/instance.hxx> #include <rtl/strbuf.hxx> #include <rtl/ustrbuf.hxx> #include <osl/diagnose.h> #include <osl/mutex.hxx> #include <com/sun/star/uno/genfunc.hxx> #include "com/sun/star/uno/RuntimeException.hpp" #include <typelib/typedescription.hxx> #include <uno/any2.h> #include "share.hxx" using namespace ::std; using namespace ::osl; using namespace ::rtl; using namespace ::com::sun::star::uno; #if MACOSX_SDK_VERSION < 1070 using namespace ::__cxxabiv1; #endif namespace CPPU_CURRENT_NAMESPACE { #if MACOSX_SDK_VERSION >= 1070 // MacOSX10.4u.sdk/usr/include/c++/4.0.0/cxxabi.h defined // __cxxabiv1::__class_type_info and __cxxabiv1::__si_class_type_info but // MacOSX10.7.sdk/usr/include/cxxabi.h no longer does, so instances of those // classes need to be created manually: // std::type_info defined in <typeinfo> offers a protected ctor: struct FAKE_type_info: public std::type_info { FAKE_type_info(char const * name): type_info(name) {} }; // Modeled after __cxxabiv1::__si_class_type_info defined in // MacOSX10.4u.sdk/usr/include/c++/4.0.0/cxxabi.h (i.e., // abi::__si_class_type_info documented at // <http://www.codesourcery.com/public/cxx-abi/abi.html#rtti>): struct FAKE_si_class_type_info: public FAKE_type_info { FAKE_si_class_type_info(char const * name, std::type_info const * theBase): FAKE_type_info(name), base(theBase) {} std::type_info const * base; // actually a __cxxabiv1::__class_type_info pointer }; struct Base {}; struct Derived: Base {}; std::type_info * create_FAKE_class_type_info(char const * name) { std::type_info * p = new FAKE_type_info(name); // cxxabiv1::__class_type_info has no data members in addition to // std::type_info *reinterpret_cast< void ** >(p) = *reinterpret_cast< void * const * >( &typeid(Base)); // copy correct __cxxabiv1::__class_type_info vtable into place return p; } std::type_info * create_FAKE_si_class_type_info( char const * name, std::type_info const * base) { std::type_info * p = new FAKE_si_class_type_info(name, base); *reinterpret_cast< void ** >(p) = *reinterpret_cast< void * const * >( &typeid(Derived)); // copy correct __cxxabiv1::__si_class_type_info vtable into place return p; } #endif void dummy_can_throw_anything( char const * ) { } //================================================================================================== static OUString toUNOname( char const * p ) SAL_THROW(()) { #if OSL_DEBUG_LEVEL > 1 char const * start = p; #endif // example: N3com3sun4star4lang24IllegalArgumentExceptionE OUStringBuffer buf( 64 ); OSL_ASSERT( 'N' == *p ); ++p; // skip N while ('E' != *p) { // read chars count long n = (*p++ - '0'); while ('0' <= *p && '9' >= *p) { n *= 10; n += (*p++ - '0'); } buf.appendAscii( p, n ); p += n; if ('E' != *p) buf.append( (sal_Unicode)'.' ); } #if OSL_DEBUG_LEVEL > 1 OUString ret( buf.makeStringAndClear() ); OString c_ret( OUStringToOString( ret, RTL_TEXTENCODING_ASCII_US ) ); fprintf( stderr, "> toUNOname(): %s => %s\n", start, c_ret.getStr() ); return ret; #else return buf.makeStringAndClear(); #endif } //================================================================================================== class RTTI { typedef boost::unordered_map< OUString, type_info *, OUStringHash > t_rtti_map; Mutex m_mutex; t_rtti_map m_rttis; t_rtti_map m_generatedRttis; void * m_hApp; public: RTTI() SAL_THROW(()); ~RTTI() SAL_THROW(()); type_info * getRTTI( typelib_CompoundTypeDescription * ) SAL_THROW(()); }; //__________________________________________________________________________________________________ RTTI::RTTI() SAL_THROW(()) : m_hApp( dlopen( 0, RTLD_LAZY ) ) { } //__________________________________________________________________________________________________ RTTI::~RTTI() SAL_THROW(()) { dlclose( m_hApp ); } //__________________________________________________________________________________________________ type_info * RTTI::getRTTI( typelib_CompoundTypeDescription *pTypeDescr ) SAL_THROW(()) { type_info * rtti; OUString const & unoName = *(OUString const *)&pTypeDescr->aBase.pTypeName; MutexGuard guard( m_mutex ); t_rtti_map::const_iterator iFind( m_rttis.find( unoName ) ); if (iFind == m_rttis.end()) { // RTTI symbol OStringBuffer buf( 64 ); buf.append( RTL_CONSTASCII_STRINGPARAM("_ZTIN") ); sal_Int32 index = 0; do { OUString token( unoName.getToken( 0, '.', index ) ); buf.append( token.getLength() ); OString c_token( OUStringToOString( token, RTL_TEXTENCODING_ASCII_US ) ); buf.append( c_token ); } while (index >= 0); buf.append( 'E' ); OString symName( buf.makeStringAndClear() ); rtti = (type_info *)dlsym( m_hApp, symName.getStr() ); if (rtti) { pair< t_rtti_map::iterator, bool > insertion( m_rttis.insert( t_rtti_map::value_type( unoName, rtti ) ) ); SAL_WARN_IF( !insertion.second, "bridges", "inserting new rtti failed" ); } else { // try to lookup the symbol in the generated rtti map t_rtti_map::const_iterator iFind2( m_generatedRttis.find( unoName ) ); if (iFind2 == m_generatedRttis.end()) { // we must generate it ! // symbol and rtti-name is nearly identical, // the symbol is prefixed with _ZTI char const * rttiName = symName.getStr() +4; #if OSL_DEBUG_LEVEL > 1 fprintf( stderr,"generated rtti for %s\n", rttiName ); #endif if (pTypeDescr->pBaseTypeDescription) { // ensure availability of base type_info * base_rtti = getRTTI( (typelib_CompoundTypeDescription *)pTypeDescr->pBaseTypeDescription ); #if MACOSX_SDK_VERSION < 1070 rtti = new __si_class_type_info( strdup( rttiName ), (__class_type_info *)base_rtti ); #else rtti = create_FAKE_si_class_type_info( strdup( rttiName ), base_rtti ); #endif } else { // this class has no base class #if MACOSX_SDK_VERSION < 1070 rtti = new __class_type_info( strdup( rttiName ) ); #else rtti = create_FAKE_class_type_info( strdup( rttiName ) ); #endif } pair< t_rtti_map::iterator, bool > insertion( m_generatedRttis.insert( t_rtti_map::value_type( unoName, rtti ) ) ); SAL_WARN_IF( !insertion.second, "bridges", "inserting new generated rtti failed" ); } else // taking already generated rtti { rtti = iFind2->second; } } } else { rtti = iFind->second; } return rtti; } struct RTTISingleton: public rtl::Static< RTTI, RTTISingleton > {}; //-------------------------------------------------------------------------------------------------- static void deleteException( void * pExc ) { __cxa_exception const * header = ((__cxa_exception const *)pExc - 1); typelib_TypeDescription * pTD = 0; OUString unoName( toUNOname( header->exceptionType->name() ) ); ::typelib_typedescription_getByName( &pTD, unoName.pData ); OSL_ENSURE( pTD, "### unknown exception type! leaving out destruction => leaking!!!" ); if (pTD) { ::uno_destructData( pExc, pTD, cpp_release ); ::typelib_typedescription_release( pTD ); } } //================================================================================================== void raiseException( uno_Any * pUnoExc, uno_Mapping * pUno2Cpp ) { #if OSL_DEBUG_LEVEL > 1 OString cstr( OUStringToOString( *reinterpret_cast< OUString const * >( &pUnoExc->pType->pTypeName ), RTL_TEXTENCODING_ASCII_US ) ); fprintf( stderr, "> uno exception occurred: %s\n", cstr.getStr() ); #endif void * pCppExc; type_info * rtti; { // construct cpp exception object typelib_TypeDescription * pTypeDescr = 0; TYPELIB_DANGER_GET( &pTypeDescr, pUnoExc->pType ); OSL_ASSERT( pTypeDescr ); if (! pTypeDescr) { throw RuntimeException( OUString( RTL_CONSTASCII_USTRINGPARAM("cannot get typedescription for type ") ) + *reinterpret_cast< OUString const * >( &pUnoExc->pType->pTypeName ), Reference< XInterface >() ); } pCppExc = __cxa_allocate_exception( pTypeDescr->nSize ); ::uno_copyAndConvertData( pCppExc, pUnoExc->pData, pTypeDescr, pUno2Cpp ); // destruct uno exception ::uno_any_destruct( pUnoExc, 0 ); rtti = (type_info *)RTTISingleton::get().getRTTI( (typelib_CompoundTypeDescription *) pTypeDescr ); TYPELIB_DANGER_RELEASE( pTypeDescr ); OSL_ENSURE( rtti, "### no rtti for throwing exception!" ); if (! rtti) { throw RuntimeException( OUString( RTL_CONSTASCII_USTRINGPARAM("no rtti for type ") ) + *reinterpret_cast< OUString const * >( &pUnoExc->pType->pTypeName ), Reference< XInterface >() ); } } __cxa_throw( pCppExc, rtti, deleteException ); } //================================================================================================== void fillUnoException( __cxa_exception * header, uno_Any * pUnoExc, uno_Mapping * pCpp2Uno ) { if (! header) { RuntimeException aRE( OUString( RTL_CONSTASCII_USTRINGPARAM("no exception header!") ), Reference< XInterface >() ); Type const & rType = ::getCppuType( &aRE ); uno_type_any_constructAndConvert( pUnoExc, &aRE, rType.getTypeLibType(), pCpp2Uno ); #if OSL_DEBUG_LEVEL > 0 OString cstr( OUStringToOString( aRE.Message, RTL_TEXTENCODING_ASCII_US ) ); OSL_FAIL( cstr.getStr() ); #endif return; } typelib_TypeDescription * pExcTypeDescr = 0; OUString unoName( toUNOname( header->exceptionType->name() ) ); #if OSL_DEBUG_LEVEL > 1 OString cstr_unoName( OUStringToOString( unoName, RTL_TEXTENCODING_ASCII_US ) ); fprintf( stderr, "> c++ exception occurred: %s\n", cstr_unoName.getStr() ); #endif typelib_typedescription_getByName( &pExcTypeDescr, unoName.pData ); if (0 == pExcTypeDescr) { RuntimeException aRE( OUString( RTL_CONSTASCII_USTRINGPARAM("exception type not found: ") ) + unoName, Reference< XInterface >() ); Type const & rType = ::getCppuType( &aRE ); uno_type_any_constructAndConvert( pUnoExc, &aRE, rType.getTypeLibType(), pCpp2Uno ); #if OSL_DEBUG_LEVEL > 0 OString cstr( OUStringToOString( aRE.Message, RTL_TEXTENCODING_ASCII_US ) ); OSL_FAIL( cstr.getStr() ); #endif } else { // construct uno exception any uno_any_constructAndConvert( pUnoExc, header->adjustedPtr, pExcTypeDescr, pCpp2Uno ); typelib_typedescription_release( pExcTypeDescr ); } } } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/** * \file py_keyword_manager.cpp * \brief Exports python wrappers for keyword_manager, * see keyword_manager.h * \author Sergey Miryanov (sergey-miryanov), sergey.miryanov@gmail.com * \date 28.10.2009 * \copyright This source code is released under the terms of * the BSD License. See LICENSE for more details. * */ #include "bs_bos_core_data_storage_stdafx.h" #include "py_keyword_manager.h" #include "keyword_manager.h" #include "read_class.h" #include "data_class.h" #include "rs_mesh_iface.h" #include BS_FORCE_PLUGIN_IMPORT () #include BS_STOP_PLUGIN_IMPORT () #ifdef BSPY_EXPORTING_PLUGIN #include "export_python_wrapper.h" namespace blue_sky { namespace python { struct py_keyword_handler_iface_base : keyword_handler_iface { typedef keyword_params keyword_params_t; void handler (const std::string &, keyword_params_t &) { bs_throw_exception ("PURE CALL FROM PYTHON"); } }; struct py_keyword_handler_iface : py_keyword_handler_iface_base , boost::python::wrapper <py_keyword_handler_iface_base > { typedef keyword_params keyword_params_t; py_keyword_handler_iface () { } py_keyword_handler_iface (const py_keyword_handler_iface_base &) { } WRAP_PURE_METHOD (handler, void, 2, (const std::string &, keyword_params_t &)); }; //template <typename T> //void //register_keyword (T *t, const std::string &keyword, const typename T::shared_handler_t &handler, bool replace_existing) //{ // t->register_keyword (keyword, handler, replace_existing); //} template <typename T> smart_ptr <FRead, true> get_reader (T *t) { typedef smart_ptr <FRead, true> sp_reader_t; sp_reader_t reader (t->reader, bs_dynamic_cast ()); if (!reader) { bs_throw_exception (boost::format ("Can't cast params->reader to sp_reader_t (%s)") % t->reader->bs_resolve_type ().stype_); } return reader; } /* template <typename T> smart_ptr <idata<typename T::strategy_type>, true> get_data (T *t) { typedef smart_ptr <idata<typename T::strategy_type>, true> sp_idata_t; sp_idata_t data (t->data, bs_dynamic_cast ()); if (!data) { bs_throw_exception (boost::format ("Can't cast params->data to sp_idata_t (%s)") % t->data->bs_resolve_type ().stype_); } return data; } template <typename T> smart_ptr <rs_mesh_iface <typename T::strategy_type>, true> get_mesh (T *t) { typedef smart_ptr <rs_mesh_iface <typename T::strategy_type>, true> sp_mesh_t; sp_mesh_t mesh (t->mesh, bs_dynamic_cast ()); if (!mesh) { bs_throw_exception (boost::format ("Can't cast params->mesh to sp_mesh_t (%s)") % t->mesh->bs_resolve_type ().stype_); } return mesh; } template <typename T> smart_ptr <keyword_manager <typename T::strategy_type>, true> get_keyword_manager (T *t) { typedef smart_ptr <keyword_manager <typename T::strategy_type>, true> sp_keyword_manager_t; sp_keyword_manager_t km (t->km, bs_dynamic_cast ()); if (!km) { bs_throw_exception (boost::format ("Can't cast params->km to sp_keyword_manager_t (%s)") % t->km->bs_resolve_type ().stype_); } return km; } */ PY_EXPORTER (keyword_manager_exporter, default_exporter) //.def ("register_keyword", register_keyword <T>) .def ("register_i_pool_keyword", &T::register_i_pool_keyword) .def ("register_fp_pool_keyword", &T::py_register_fp_pool_keyword) .def ("register_keywords", &T::register_plugin_keywords) .def ("register_plugin_keywords", &T::register_plugin_keywords) .def ("list_active_keywords", &T::py_list_active_keywords) .def ("list_supported_keywords", &T::py_list_supported_keywords) .def ("is_keyword_supported", &T::is_keyword_supported) .def ("is_keyword_activated", &T::is_keyword_activated) .def ("init", &T::init) PY_EXPORTER_END; PY_EXPORTER (keyword_params_exporter, empty_exporter) .add_property ("hdm", make_function (get_reader <T>)) //.add_property ("data", make_function (get_data <T>)) //.add_property ("mesh", make_function (get_mesh <T>)) //.add_property ("keyword_manager", make_function (get_keyword_manager <T>)) PY_EXPORTER_END; PY_EXPORTER (keyword_handler_iface_exporter, empty_exporter) .def ("handler", &T::handler) PY_EXPORTER_END; void export_keyword_manager () { using namespace boost::python; base_exporter<keyword_manager_iface, empty_exporter>::export_class ("keyword_manager_iface"); class_exporter<keyword_manager, keyword_manager_iface, keyword_manager_exporter>::export_class ("keyword_manager"); //strategy_exporter::export_base_ext <keyword_params, keyword_params_exporter, class_type::concrete_class> ("keyword_params"); /* strategy_exporter::export_base_ext <keyword_handler_iface, empty_exporter, class_type::abstract_class> ("keyword_handler_iface"); strategy_exporter::export_class_ext <py_keyword_handler_iface, keyword_handler_iface, keyword_handler_iface_exporter, class_type::concrete_class> ("py_keyword_handler_iface"); strategy_exporter::export_base <keyword_manager, keyword_manager_exporter> ("keyword_manager"); */ } } // namespace python } // namespace blue_sky #endif <commit_msg>fix compillation bug in linux<commit_after>/** * \file py_keyword_manager.cpp * \brief Exports python wrappers for keyword_manager, * see keyword_manager.h * \author Sergey Miryanov (sergey-miryanov), sergey.miryanov@gmail.com * \date 28.10.2009 * \copyright This source code is released under the terms of * the BSD License. See LICENSE for more details. * */ #include "bs_bos_core_data_storage_stdafx.h" #include "py_keyword_manager.h" #include "keyword_manager.h" #include "read_class.h" #include "data_class.h" #include "rs_mesh_iface.h" #include BS_FORCE_PLUGIN_IMPORT () #include BS_STOP_PLUGIN_IMPORT () #ifdef BSPY_EXPORTING_PLUGIN #include "export_python_wrapper.h" namespace blue_sky { namespace python { struct py_keyword_handler_iface_base : keyword_handler_iface { typedef keyword_params keyword_params_t; void handler (const std::string &, keyword_params_t &) { bs_throw_exception ("PURE CALL FROM PYTHON"); } }; struct py_keyword_handler_iface : py_keyword_handler_iface_base , boost::python::wrapper <py_keyword_handler_iface_base > { typedef keyword_params keyword_params_t; py_keyword_handler_iface () { } py_keyword_handler_iface (const py_keyword_handler_iface_base &) { } WRAP_PURE_METHOD (handler, void, 2, (const std::string &, keyword_params_t &)); }; //template <typename T> //void //register_keyword (T *t, const std::string &keyword, const typename T::shared_handler_t &handler, bool replace_existing) //{ // t->register_keyword (keyword, handler, replace_existing); //} template <typename T> smart_ptr <FRead, true> get_reader (T *t) { typedef smart_ptr <FRead, true> sp_reader_t; sp_reader_t reader (t->reader, bs_dynamic_cast ()); if (!reader) { bs_throw_exception (boost::format ("Can't cast params->reader to sp_reader_t (%s)") % t->reader->bs_resolve_type ().stype_); } return reader; } /* template <typename T> smart_ptr <idata<typename T::strategy_type>, true> get_data (T *t) { typedef smart_ptr <idata<typename T::strategy_type>, true> sp_idata_t; sp_idata_t data (t->data, bs_dynamic_cast ()); if (!data) { bs_throw_exception (boost::format ("Can't cast params->data to sp_idata_t (%s)") % t->data->bs_resolve_type ().stype_); } return data; } template <typename T> smart_ptr <rs_mesh_iface <typename T::strategy_type>, true> get_mesh (T *t) { typedef smart_ptr <rs_mesh_iface <typename T::strategy_type>, true> sp_mesh_t; sp_mesh_t mesh (t->mesh, bs_dynamic_cast ()); if (!mesh) { bs_throw_exception (boost::format ("Can't cast params->mesh to sp_mesh_t (%s)") % t->mesh->bs_resolve_type ().stype_); } return mesh; } template <typename T> smart_ptr <keyword_manager <typename T::strategy_type>, true> get_keyword_manager (T *t) { typedef smart_ptr <keyword_manager <typename T::strategy_type>, true> sp_keyword_manager_t; sp_keyword_manager_t km (t->km, bs_dynamic_cast ()); if (!km) { bs_throw_exception (boost::format ("Can't cast params->km to sp_keyword_manager_t (%s)") % t->km->bs_resolve_type ().stype_); } return km; } */ PY_EXPORTER (keyword_manager_exporter, default_exporter) //.def ("register_keyword", register_keyword <T>) .def ("register_i_pool_keyword", &T::register_i_pool_keyword) .def ("register_fp_pool_keyword", &T::py_register_fp_pool_keyword) .def ("register_keywords", &T::register_plugin_keywords) .def ("register_plugin_keywords", &T::register_plugin_keywords) .def ("list_active_keywords", &T::py_list_active_keywords) .def ("list_supported_keywords", &T::py_list_supported_keywords) .def ("is_keyword_supported", &T::is_keyword_supported) .def ("is_keyword_activated", &T::is_keyword_activated) .def ("init", &T::init) PY_EXPORTER_END; PY_EXPORTER (keyword_params_exporter, empty_exporter) .add_property ("hdm", make_function (get_reader <T>)) //.add_property ("data", make_function (get_data <T>)) //.add_property ("mesh", make_function (get_mesh <T>)) //.add_property ("keyword_manager", make_function (get_keyword_manager <T>)) PY_EXPORTER_END; PY_EXPORTER (keyword_handler_iface_exporter, empty_exporter) .def ("handler", &T::handler) PY_EXPORTER_END; void export_keyword_manager () { using namespace boost::python; base_exporter<keyword_manager_iface, empty_exporter>::export_class ("keyword_manager_iface"); //class_exporter<keyword_manager, keyword_manager_iface, keyword_manager_exporter>::export_class ("keyword_manager"); //strategy_exporter::export_base_ext <keyword_params, keyword_params_exporter, class_type::concrete_class> ("keyword_params"); /* strategy_exporter::export_base_ext <keyword_handler_iface, empty_exporter, class_type::abstract_class> ("keyword_handler_iface"); strategy_exporter::export_class_ext <py_keyword_handler_iface, keyword_handler_iface, keyword_handler_iface_exporter, class_type::concrete_class> ("py_keyword_handler_iface"); strategy_exporter::export_base <keyword_manager, keyword_manager_exporter> ("keyword_manager"); */ } } // namespace python } // namespace blue_sky #endif <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: xmlfilter.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: rt $ $Date: 2007-11-09 08:19:11 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef DBA_XMLFILTER_HXX #define DBA_XMLFILTER_HXX #ifndef _COM_SUN_STAR_CONTAINER_XNAMED_HPP_ #include <com/sun/star/container/XNamed.hpp> #endif #ifndef _COM_SUN_STAR_DOCUMENT_XFILTER_HPP_ #include <com/sun/star/document/XFilter.hpp> #endif #ifndef _COM_SUN_STAR_DOCUMENT_XIMPORTER_HPP_ #include <com/sun/star/document/XImporter.hpp> #endif #ifndef _COM_SUN_STAR_DOCUMENT_XEXPORTER_HPP_ #include <com/sun/star/document/XExporter.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_ #include <com/sun/star/lang/XInitialization.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_ #include <com/sun/star/lang/XComponent.hpp> #endif #ifndef _CPPUHELPER_IMPLBASE1_HXX_ #include <cppuhelper/implbase1.hxx> #endif #ifndef _CPPUHELPER_IMPLBASE5_HXX_ #include <cppuhelper/implbase5.hxx> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_IO_XACTIVEDATASOURCE_HPP_ #include <com/sun/star/io/XActiveDataSource.hpp> #endif #ifndef _OSL_DIAGNOSE_H_ #include <osl/diagnose.h> #endif #ifndef _UNOTOOLS_TEMPFILE_HXX #include <unotools/tempfile.hxx> #endif #ifndef _UNOTOOLS_LOCALFILEHELPER_HXX #include <unotools/localfilehelper.hxx> #endif #ifndef _UNTOOLS_UCBSTREAMHELPER_HXX #include <unotools/ucbstreamhelper.hxx> #endif #ifndef _XMLOFF_XMLIMP_HXX #include <xmloff/xmlimp.hxx> #endif #ifndef _DBASHARED_APITOOLS_HXX_ #include "apitools.hxx" #endif #ifndef _COMPHELPER_STLTYPES_HXX_ #include <comphelper/stl_types.hxx> #endif #include <memory> namespace dbaxml { using namespace ::xmloff::token; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::container; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::document; using namespace ::com::sun::star::text; using namespace ::com::sun::star::io; using namespace ::com::sun::star::xml::sax; // ------------- // - ODBFilter - // ------------- class ODBFilter : public SvXMLImport { public: DECLARE_STL_USTRINGACCESS_MAP(Sequence<PropertyValue>,TPropertyNameMap); typedef ::std::vector< ::com::sun::star::beans::PropertyValue> TInfoSequence; private: TPropertyNameMap m_aQuerySettings; TPropertyNameMap m_aTablesSettings; TInfoSequence m_aInfoSequence; Reference< XComponent > m_xSrcDoc; mutable ::std::auto_ptr<SvXMLTokenMap> m_pDocElemTokenMap; mutable ::std::auto_ptr<SvXMLTokenMap> m_pDatabaseElemTokenMap; mutable ::std::auto_ptr<SvXMLTokenMap> m_pDataSourceElemTokenMap; mutable ::std::auto_ptr<SvXMLTokenMap> m_pLoginElemTokenMap; mutable ::std::auto_ptr<SvXMLTokenMap> m_pDatabaseDescriptionElemTokenMap; mutable ::std::auto_ptr<SvXMLTokenMap> m_pDataSourceInfoElemTokenMap; mutable ::std::auto_ptr<SvXMLTokenMap> m_pDocumentsElemTokenMap; mutable ::std::auto_ptr<SvXMLTokenMap> m_pComponentElemTokenMap; mutable ::std::auto_ptr<SvXMLTokenMap> m_pQueryElemTokenMap; mutable ::std::auto_ptr<SvXMLTokenMap> m_pColumnElemTokenMap; mutable UniReference < XMLPropertySetMapper > m_xTableStylesPropertySetMapper; mutable UniReference < XMLPropertySetMapper > m_xColumnStylesPropertySetMapper; Reference<XPropertySet> m_xDataSource; sal_Int32 m_nPreviewMode; bool m_bNewFormat; sal_Bool implImport( const Sequence< PropertyValue >& rDescriptor ) throw (RuntimeException); /** fills the map with the Properties @param _rValue The Any where the sequence resists in. @param _rMap The map to fill. */ void fillPropertyMap(const Any& _rValue,TPropertyNameMap& _rMap); SvXMLImportContext* CreateStylesContext(const ::rtl::OUString& rLocalName, const Reference< XAttributeList>& xAttrList, sal_Bool bIsAutoStyle ); protected: // SvXMLImport virtual SvXMLImportContext *CreateContext( sal_uInt16 nPrefix, const ::rtl::OUString& rLocalName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList ); virtual ~ODBFilter() throw(); public: ODBFilter( const Reference< XMultiServiceFactory >& _rxMSF ); // XFilter virtual sal_Bool SAL_CALL filter( const Sequence< PropertyValue >& rDescriptor ) throw(RuntimeException); // XServiceInfo DECLARE_SERVICE_INFO_STATIC( ); // helper class virtual void SetViewSettings(const com::sun::star::uno::Sequence<com::sun::star::beans::PropertyValue>& aViewProps); virtual void SetConfigurationSettings(const com::sun::star::uno::Sequence<com::sun::star::beans::PropertyValue>& aConfigProps); inline Reference< XMultiServiceFactory > getORB() { return getServiceFactory(); } inline Reference<XPropertySet> getDataSource() const { return m_xDataSource; } inline const TPropertyNameMap& getQuerySettings() const { return m_aQuerySettings;} inline const TPropertyNameMap& getTableSettings() const { return m_aTablesSettings;} const SvXMLTokenMap& GetDocElemTokenMap() const; const SvXMLTokenMap& GetDatabaseElemTokenMap() const; const SvXMLTokenMap& GetDataSourceElemTokenMap() const; const SvXMLTokenMap& GetLoginElemTokenMap() const; const SvXMLTokenMap& GetDatabaseDescriptionElemTokenMap() const; const SvXMLTokenMap& GetDataSourceInfoElemTokenMap() const; const SvXMLTokenMap& GetDocumentsElemTokenMap() const; const SvXMLTokenMap& GetComponentElemTokenMap() const; const SvXMLTokenMap& GetQueryElemTokenMap() const; const SvXMLTokenMap& GetColumnElemTokenMap() const; UniReference < XMLPropertySetMapper > GetTableStylesPropertySetMapper() const; UniReference < XMLPropertySetMapper > GetColumnStylesPropertySetMapper() const; /** add a Info to the sequence which will be appened to the data source @param _rInfo The property to append. */ inline void addInfo(const ::com::sun::star::beans::PropertyValue& _rInfo) { m_aInfoSequence.push_back(_rInfo); } void setPropertyInfo(); const ::std::map< sal_uInt16,com::sun::star::beans::Property>& GetDataSourceInfoDefaulValueMap() const; inline bool isNewFormat() const { return m_bNewFormat; } inline void setNewFormat(bool _bNewFormat) { m_bNewFormat = _bNewFormat; } }; // ----------------------------------------------------------------------------- } // dbaxml // ----------------------------------------------------------------------------- #endif // DBA_XMLFILTER_HXX <commit_msg>INTEGRATION: CWS dba24g_SRC680 (1.6.52); FILE MERGED 2008/01/31 07:40:19 oj 1.6.52.1: import of odf12 for db files<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: xmlfilter.hxx,v $ * * $Revision: 1.7 $ * * last change: $Author: vg $ $Date: 2008-02-12 13:24:40 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef DBA_XMLFILTER_HXX #define DBA_XMLFILTER_HXX #ifndef _COM_SUN_STAR_CONTAINER_XNAMED_HPP_ #include <com/sun/star/container/XNamed.hpp> #endif #ifndef _COM_SUN_STAR_DOCUMENT_XFILTER_HPP_ #include <com/sun/star/document/XFilter.hpp> #endif #ifndef _COM_SUN_STAR_DOCUMENT_XIMPORTER_HPP_ #include <com/sun/star/document/XImporter.hpp> #endif #ifndef _COM_SUN_STAR_DOCUMENT_XEXPORTER_HPP_ #include <com/sun/star/document/XExporter.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_ #include <com/sun/star/lang/XInitialization.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_ #include <com/sun/star/lang/XComponent.hpp> #endif #ifndef _CPPUHELPER_IMPLBASE1_HXX_ #include <cppuhelper/implbase1.hxx> #endif #ifndef _CPPUHELPER_IMPLBASE5_HXX_ #include <cppuhelper/implbase5.hxx> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_IO_XACTIVEDATASOURCE_HPP_ #include <com/sun/star/io/XActiveDataSource.hpp> #endif #ifndef _OSL_DIAGNOSE_H_ #include <osl/diagnose.h> #endif #ifndef _UNOTOOLS_TEMPFILE_HXX #include <unotools/tempfile.hxx> #endif #ifndef _UNOTOOLS_LOCALFILEHELPER_HXX #include <unotools/localfilehelper.hxx> #endif #ifndef _UNTOOLS_UCBSTREAMHELPER_HXX #include <unotools/ucbstreamhelper.hxx> #endif #ifndef _XMLOFF_XMLIMP_HXX #include <xmloff/xmlimp.hxx> #endif #ifndef _DBASHARED_APITOOLS_HXX_ #include "apitools.hxx" #endif #ifndef _COMPHELPER_STLTYPES_HXX_ #include <comphelper/stl_types.hxx> #endif #include <memory> namespace dbaxml { using namespace ::xmloff::token; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::container; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::document; using namespace ::com::sun::star::text; using namespace ::com::sun::star::io; using namespace ::com::sun::star::xml::sax; // ------------- // - ODBFilter - // ------------- class ODBFilter : public SvXMLImport { public: DECLARE_STL_USTRINGACCESS_MAP(Sequence<PropertyValue>,TPropertyNameMap); typedef ::std::vector< ::com::sun::star::beans::PropertyValue> TInfoSequence; private: TPropertyNameMap m_aQuerySettings; TPropertyNameMap m_aTablesSettings; TInfoSequence m_aInfoSequence; Reference< XComponent > m_xSrcDoc; mutable ::std::auto_ptr<SvXMLTokenMap> m_pDocElemTokenMap; mutable ::std::auto_ptr<SvXMLTokenMap> m_pDatabaseElemTokenMap; mutable ::std::auto_ptr<SvXMLTokenMap> m_pDataSourceElemTokenMap; mutable ::std::auto_ptr<SvXMLTokenMap> m_pLoginElemTokenMap; mutable ::std::auto_ptr<SvXMLTokenMap> m_pDatabaseDescriptionElemTokenMap; mutable ::std::auto_ptr<SvXMLTokenMap> m_pDataSourceInfoElemTokenMap; mutable ::std::auto_ptr<SvXMLTokenMap> m_pDocumentsElemTokenMap; mutable ::std::auto_ptr<SvXMLTokenMap> m_pComponentElemTokenMap; mutable ::std::auto_ptr<SvXMLTokenMap> m_pQueryElemTokenMap; mutable ::std::auto_ptr<SvXMLTokenMap> m_pColumnElemTokenMap; mutable UniReference < XMLPropertySetMapper > m_xTableStylesPropertySetMapper; mutable UniReference < XMLPropertySetMapper > m_xColumnStylesPropertySetMapper; Reference<XPropertySet> m_xDataSource; sal_Int32 m_nPreviewMode; bool m_bNewFormat; sal_Bool implImport( const Sequence< PropertyValue >& rDescriptor ) throw (RuntimeException); /** fills the map with the Properties @param _rValue The Any where the sequence resists in. @param _rMap The map to fill. */ void fillPropertyMap(const Any& _rValue,TPropertyNameMap& _rMap); SvXMLImportContext* CreateStylesContext(sal_uInt16 nPrefix,const ::rtl::OUString& rLocalName, const Reference< XAttributeList>& xAttrList, sal_Bool bIsAutoStyle ); protected: // SvXMLImport virtual SvXMLImportContext *CreateContext( sal_uInt16 nPrefix, const ::rtl::OUString& rLocalName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList ); virtual ~ODBFilter() throw(); public: ODBFilter( const Reference< XMultiServiceFactory >& _rxMSF ); // XFilter virtual sal_Bool SAL_CALL filter( const Sequence< PropertyValue >& rDescriptor ) throw(RuntimeException); // XServiceInfo DECLARE_SERVICE_INFO_STATIC( ); // helper class virtual void SetViewSettings(const com::sun::star::uno::Sequence<com::sun::star::beans::PropertyValue>& aViewProps); virtual void SetConfigurationSettings(const com::sun::star::uno::Sequence<com::sun::star::beans::PropertyValue>& aConfigProps); inline Reference< XMultiServiceFactory > getORB() { return getServiceFactory(); } inline Reference<XPropertySet> getDataSource() const { return m_xDataSource; } inline const TPropertyNameMap& getQuerySettings() const { return m_aQuerySettings;} inline const TPropertyNameMap& getTableSettings() const { return m_aTablesSettings;} const SvXMLTokenMap& GetDocElemTokenMap() const; const SvXMLTokenMap& GetDatabaseElemTokenMap() const; const SvXMLTokenMap& GetDataSourceElemTokenMap() const; const SvXMLTokenMap& GetLoginElemTokenMap() const; const SvXMLTokenMap& GetDatabaseDescriptionElemTokenMap() const; const SvXMLTokenMap& GetDataSourceInfoElemTokenMap() const; const SvXMLTokenMap& GetDocumentsElemTokenMap() const; const SvXMLTokenMap& GetComponentElemTokenMap() const; const SvXMLTokenMap& GetQueryElemTokenMap() const; const SvXMLTokenMap& GetColumnElemTokenMap() const; UniReference < XMLPropertySetMapper > GetTableStylesPropertySetMapper() const; UniReference < XMLPropertySetMapper > GetColumnStylesPropertySetMapper() const; /** add a Info to the sequence which will be appened to the data source @param _rInfo The property to append. */ inline void addInfo(const ::com::sun::star::beans::PropertyValue& _rInfo) { m_aInfoSequence.push_back(_rInfo); } void setPropertyInfo(); const ::std::map< sal_uInt16,com::sun::star::beans::Property>& GetDataSourceInfoDefaulValueMap() const; inline bool isNewFormat() const { return m_bNewFormat; } inline void setNewFormat(bool _bNewFormat) { m_bNewFormat = _bNewFormat; } }; // ----------------------------------------------------------------------------- } // dbaxml // ----------------------------------------------------------------------------- #endif // DBA_XMLFILTER_HXX <|endoftext|>
<commit_before>/****************************************************************************** This source file is part of the Avogadro project. This source code is released under the 3-Clause BSD License, (see "LICENSE"). ******************************************************************************/ #include "closecontacts.h" #include <avogadro/core/array.h> #include <avogadro/core/bond.h> #include <avogadro/core/elements.h> #include <avogadro/core/neighborperceiver.h> #include <avogadro/qtgui/molecule.h> #include <avogadro/rendering/dashedlinegeometry.h> #include <avogadro/rendering/geometrynode.h> #include <avogadro/rendering/groupnode.h> #include <QtCore/QSettings> #include <QtWidgets/QDoubleSpinBox> #include <QtWidgets/QFormLayout> #include <QtWidgets/QVBoxLayout> #include <QtWidgets/QWidget> namespace Avogadro::QtPlugins { using Core::Array; using Core::Bond; using Core::NeighborPerceiver; using QtGui::Molecule; using QtGui::PluginLayerManager; using Rendering::DashedLineGeometry; using Rendering::GeometryNode; using Rendering::GroupNode; CloseContacts::CloseContacts(QObject *p) : ScenePlugin(p) { m_layerManager = PluginLayerManager(m_name); QSettings settings; m_maximumDistance = settings.value("closeContacts/maximumDistance", 2.5).toDouble(); } CloseContacts::~CloseContacts() {} static bool checkPairNot1213(const Molecule &molecule, Index i, Index n) { static Array<Index> bondedCache; static Index lastIndex; static bool lastIndexValid = false; if (!lastIndexValid || lastIndex != i) { bondedCache.clear(); for (const Bond *b : molecule.bonds(i)) bondedCache.push_back(b->atom1().index() == i ? b->atom2().index() : b->atom1().index()); lastIndex = i; lastIndexValid = true; } for (const Bond *b : molecule.bonds(n)) { Index m = (b->atom1().index() == n ? b->atom2() : b->atom1()).index(); if (m == i) // exclude 1-2 pairs return false; for (Index bn: bondedCache) if (bn == m) // exclude 1-3 pairs return false; } return true; } void CloseContacts::process(const Molecule &molecule, Rendering::GroupNode &node) { Vector3ub color(128, 128, 128); NeighborPerceiver perceiver(molecule.atomPositions3d(), m_maximumDistance); std::vector<bool> isAtomEnabled(molecule.atomCount()); for (Index i = 0; i < molecule.atomCount(); ++i) isAtomEnabled[i] = m_layerManager.atomEnabled(i); auto *geometry = new GeometryNode; node.addChild(geometry); auto *lines = new DashedLineGeometry; lines->identifier().molecule = &molecule; lines->identifier().type = Rendering::BondType; lines->setLineWidth(2.0); geometry->addDrawable(lines); Array<Index> neighbors; for (Index i = 0; i < molecule.atomCount(); ++i) { if (!isAtomEnabled[i]) continue; Vector3 pos = molecule.atomPosition3d(i); perceiver.getNeighborsInclusiveInPlace(neighbors, pos); for (Index n : neighbors) { if (n <= i) // check each pair only once continue; if (!isAtomEnabled[n]) continue; if (!checkPairNot1213(molecule, i, n)) continue; Vector3 npos = molecule.atomPosition3d(n); double distance = (npos - pos).norm(); if (distance < m_maximumDistance) lines->addDashedLine(pos.cast<float>(), npos.cast<float>(), color, 8); } } } QWidget *CloseContacts::setupWidget() { auto *widget = new QWidget(qobject_cast<QWidget *>(this->parent())); auto *v = new QVBoxLayout; // maximum distance auto *spin = new QDoubleSpinBox; spin->setRange(1.5, 10.0); spin->setSingleStep(0.1); spin->setDecimals(1); spin->setSuffix(tr(" Å")); spin->setValue(m_maximumDistance); QObject::connect(spin, SIGNAL(valueChanged(double)), this, SLOT(setMaximumDistance(double))); auto *form = new QFormLayout; form->addRow(QObject::tr("Maximum distance:"), spin); v->addLayout(form); v->addStretch(1); widget->setLayout(v); return widget; } void CloseContacts::setMaximumDistance(double maximumDistance) { m_maximumDistance = float(maximumDistance); emit drawablesChanged(); QSettings settings; settings.setValue("closeContacts/maximumDistance", m_maximumDistance); } } // namespace Avogadro <commit_msg>Initial salt bridge implementation (#1021)<commit_after>/****************************************************************************** This source file is part of the Avogadro project. This source code is released under the 3-Clause BSD License, (see "LICENSE"). ******************************************************************************/ #include "closecontacts.h" #include <avogadro/core/array.h> #include <avogadro/core/atom.h> #include <avogadro/core/bond.h> #include <avogadro/core/elements.h> #include <avogadro/core/neighborperceiver.h> #include <avogadro/core/residue.h> #include <avogadro/qtgui/molecule.h> #include <avogadro/rendering/dashedlinegeometry.h> #include <avogadro/rendering/geometrynode.h> #include <avogadro/rendering/groupnode.h> #include <QtCore/QSettings> #include <QtWidgets/QDoubleSpinBox> #include <QtWidgets/QFormLayout> #include <QtWidgets/QVBoxLayout> #include <QtWidgets/QWidget> namespace Avogadro::QtPlugins { using Core::Array; using Core::Atom; using Core::Bond; using Core::NeighborPerceiver; using QtGui::Molecule; using QtGui::PluginLayerManager; using Rendering::DashedLineGeometry; using Rendering::GeometryNode; using Rendering::GroupNode; CloseContacts::CloseContacts(QObject *p) : ScenePlugin(p) { m_layerManager = PluginLayerManager(m_name); QSettings settings; m_maximumDistance = settings.value("closeContacts/maximumDistance", 2.5).toDouble(); } CloseContacts::~CloseContacts() {} static bool checkPairNot1213(const Molecule &molecule, Index i, Index n) { static Array<Index> bondedCache; static Index lastIndex; static bool lastIndexValid = false; if (!lastIndexValid || lastIndex != i) { bondedCache.clear(); for (const Bond *b : molecule.bonds(i)) bondedCache.push_back(b->atom1().index() == i ? b->atom2().index() : b->atom1().index()); lastIndex = i; lastIndexValid = true; } for (const Bond *b : molecule.bonds(n)) { Index m = (b->atom1().index() == n ? b->atom2() : b->atom1()).index(); if (m == i) // exclude 1-2 pairs return false; for (Index bn: bondedCache) if (bn == m) // exclude 1-3 pairs return false; } return true; } void addChargedAtom( Array<Vector3> &positions, Array<signed char> &charges, Array<Index> &residues, const Molecule &molecule, Index residueId, Atom atom, double charge ) { auto pos = molecule.atomPosition3d(atom.index()); if (molecule.formalCharge(atom.index()) != 0) { for (Index i = 0; i < positions.size(); i++) { if ((positions[i] - pos).norm() < 0.00001) { residues[i] = residueId; return; } } } positions.push_back(pos); charges.push_back(charge); residues.push_back(residueId); } void CloseContacts::process(const Molecule &molecule, Rendering::GroupNode &node) { Vector3ub color(128, 128, 128); //Add general contacts NeighborPerceiver perceiver(molecule.atomPositions3d(), m_maximumDistance); std::vector<bool> isAtomEnabled(molecule.atomCount()); for (Index i = 0; i < molecule.atomCount(); ++i) isAtomEnabled[i] = m_layerManager.atomEnabled(i); auto *geometry = new GeometryNode; node.addChild(geometry); auto *lines = new DashedLineGeometry; lines->identifier().molecule = &molecule; lines->identifier().type = Rendering::BondType; lines->setLineWidth(2.0); geometry->addDrawable(lines); Array<Index> neighbors; for (Index i = 0; i < molecule.atomCount(); ++i) { if (!isAtomEnabled[i]) continue; Vector3 pos = molecule.atomPosition3d(i); perceiver.getNeighborsInclusiveInPlace(neighbors, pos); for (Index n : neighbors) { if (n <= i) // check each pair only once continue; if (!isAtomEnabled[n]) continue; if (!checkPairNot1213(molecule, i, n)) continue; Vector3 npos = molecule.atomPosition3d(n); double distance = (npos - pos).norm(); if (distance < m_maximumDistance) lines->addDashedLine(pos.cast<float>(), npos.cast<float>(), color, 8); } } // Add charged atoms Array<Vector3> positions; Array<signed char> charges; Array<Index> residues; for (Index i = 0; i < molecule.atomCount(); ++i) { if (molecule.formalCharge(i) != 0) { if (!isAtomEnabled[i]) continue; positions.push_back(molecule.atomPosition3d(i)); charges.push_back(molecule.formalCharge(i)); residues.push_back(Index(0) - 1); } } // Add predicted charged atoms from residues for (const auto &r: molecule.residues()) { if (!r.residueName().compare("LYS")) { addChargedAtom(positions, charges, residues, molecule, r.residueId(), r.getAtomByName("NZ"), 1.0); } else if (!r.residueName().compare("ARG")) { addChargedAtom(positions, charges, residues, molecule, r.residueId(), r.getAtomByName("NE"), 1.0); addChargedAtom(positions, charges, residues, molecule, r.residueId(), r.getAtomByName("NH1"), 1.0); addChargedAtom(positions, charges, residues, molecule, r.residueId(), r.getAtomByName("NH2"), 1.0); } else if (!r.residueName().compare("HIS")) { addChargedAtom(positions, charges, residues, molecule, r.residueId(), r.getAtomByName("ND1"), 1.0); } else if (!r.residueName().compare("ASP")) { addChargedAtom(positions, charges, residues, molecule, r.residueId(), r.getAtomByName("OD1"), -1.0); addChargedAtom(positions, charges, residues, molecule, r.residueId(), r.getAtomByName("OD2"), -1.0); } else if (!r.residueName().compare("GLU")) { addChargedAtom(positions, charges, residues, molecule, r.residueId(), r.getAtomByName("OE1"), -1.0); addChargedAtom(positions, charges, residues, molecule, r.residueId(), r.getAtomByName("OE2"), -1.0); } } // detect contacts among them NeighborPerceiver ionPerceiver(positions, 4.0); for (Index i = 0; i < positions.size(); ++i) { const Vector3 &pos = positions[i]; ionPerceiver.getNeighborsInclusiveInPlace(neighbors, pos); for (Index n: neighbors) { if (n <= i) // check each pair only once continue; if (residues[n] == residues[i] && residues[i] != Index(0) - 1) continue; // ignore intra-residue interactions Vector3 npos = positions[n]; double distance = (npos - pos).norm(); if (distance < 4.0) { if (charges[i] * charges[n] > 0.0) lines->addDashedLine(pos.cast<float>(), npos.cast<float>(), Vector3ub(255, 0, 0), 8); else lines->addDashedLine(pos.cast<float>(), npos.cast<float>(), Vector3ub(255, 0, 255), 8); } } } } QWidget *CloseContacts::setupWidget() { auto *widget = new QWidget(qobject_cast<QWidget *>(this->parent())); auto *v = new QVBoxLayout; // maximum distance auto *spin = new QDoubleSpinBox; spin->setRange(1.5, 10.0); spin->setSingleStep(0.1); spin->setDecimals(1); spin->setSuffix(tr(" Å")); spin->setValue(m_maximumDistance); QObject::connect(spin, SIGNAL(valueChanged(double)), this, SLOT(setMaximumDistance(double))); auto *form = new QFormLayout; form->addRow(QObject::tr("Maximum distance:"), spin); v->addLayout(form); v->addStretch(1); widget->setLayout(v); return widget; } void CloseContacts::setMaximumDistance(double maximumDistance) { m_maximumDistance = float(maximumDistance); emit drawablesChanged(); QSettings settings; settings.setValue("closeContacts/maximumDistance", m_maximumDistance); } } // namespace Avogadro <|endoftext|>
<commit_before>/* * Copyright 2014 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "DMPDFTask.h" #include "DMExpectationsTask.h" #include "DMPDFRasterizeTask.h" #include "DMUtil.h" #include "DMWriteTask.h" #include "SkCommandLineFlags.h" #include "SkDocument.h" DEFINE_bool(pdf, true, "PDF backend master switch."); namespace DM { PDFTask::PDFTask(const char* suffix, Reporter* reporter, TaskRunner* taskRunner, const Expectations& expectations, skiagm::GMRegistry::Factory factory, RasterizePdfProc rasterizePdfProc) : CpuTask(reporter, taskRunner) , fGM(factory(NULL)) , fName(UnderJoin(fGM->getName(), suffix)) , fExpectations(expectations) , fRasterize(rasterizePdfProc) {} namespace { class SinglePagePDF { public: SinglePagePDF(SkScalar width, SkScalar height) : fDocument(SkDocument::CreatePDF(&fWriteStream)) , fCanvas(fDocument->beginPage(width, height)) {} SkCanvas* canvas() { return fCanvas; } SkData* end() { fCanvas->flush(); fDocument->endPage(); fDocument->close(); return fWriteStream.copyToData(); } private: SkDynamicMemoryWStream fWriteStream; SkAutoTUnref<SkDocument> fDocument; SkCanvas* fCanvas; }; } // namespace void PDFTask::draw() { SinglePagePDF pdf(fGM->width(), fGM->height()); //TODO(mtklein): GM doesn't do this. Why not? //pdf.canvas()->concat(fGM->getInitialTransform()); fGM->draw(pdf.canvas()); SkAutoTUnref<SkData> pdfData(pdf.end()); SkASSERT(pdfData.get()); if (!(fGM->getFlags() & skiagm::GM::kSkipPDFRasterization_Flag)) { this->spawnChild(SkNEW_ARGS(PDFRasterizeTask, (*this, pdfData.get(), fExpectations, fRasterize))); } this->spawnChild(SkNEW_ARGS(WriteTask, (*this, pdfData.get(), ".pdf"))); } bool PDFTask::shouldSkip() const { if (!FLAGS_pdf) { return true; } if (fGM->getFlags() & skiagm::GM::kSkipPDF_Flag) { return true; } return false; } } // namespace DM <commit_msg>Disable PDF in dm for tonight. It's crashy.<commit_after>/* * Copyright 2014 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "DMPDFTask.h" #include "DMExpectationsTask.h" #include "DMPDFRasterizeTask.h" #include "DMUtil.h" #include "DMWriteTask.h" #include "SkCommandLineFlags.h" #include "SkDocument.h" // The PDF backend is not threadsafe. If you run dm with --pdf repeatedly, you // will quickly find yourself crashed. (while catchsegv out/Release/dm;; end). // // TODO(mtklein): re-enable by default, maybe moving to its own single thread. DEFINE_bool(pdf, false, "PDF backend master switch."); namespace DM { PDFTask::PDFTask(const char* suffix, Reporter* reporter, TaskRunner* taskRunner, const Expectations& expectations, skiagm::GMRegistry::Factory factory, RasterizePdfProc rasterizePdfProc) : CpuTask(reporter, taskRunner) , fGM(factory(NULL)) , fName(UnderJoin(fGM->getName(), suffix)) , fExpectations(expectations) , fRasterize(rasterizePdfProc) {} namespace { class SinglePagePDF { public: SinglePagePDF(SkScalar width, SkScalar height) : fDocument(SkDocument::CreatePDF(&fWriteStream)) , fCanvas(fDocument->beginPage(width, height)) {} SkCanvas* canvas() { return fCanvas; } SkData* end() { fCanvas->flush(); fDocument->endPage(); fDocument->close(); return fWriteStream.copyToData(); } private: SkDynamicMemoryWStream fWriteStream; SkAutoTUnref<SkDocument> fDocument; SkCanvas* fCanvas; }; } // namespace void PDFTask::draw() { SinglePagePDF pdf(fGM->width(), fGM->height()); //TODO(mtklein): GM doesn't do this. Why not? //pdf.canvas()->concat(fGM->getInitialTransform()); fGM->draw(pdf.canvas()); SkAutoTUnref<SkData> pdfData(pdf.end()); SkASSERT(pdfData.get()); if (!(fGM->getFlags() & skiagm::GM::kSkipPDFRasterization_Flag)) { this->spawnChild(SkNEW_ARGS(PDFRasterizeTask, (*this, pdfData.get(), fExpectations, fRasterize))); } this->spawnChild(SkNEW_ARGS(WriteTask, (*this, pdfData.get(), ".pdf"))); } bool PDFTask::shouldSkip() const { if (!FLAGS_pdf) { return true; } if (fGM->getFlags() & skiagm::GM::kSkipPDF_Flag) { return true; } return false; } } // namespace DM <|endoftext|>
<commit_before>#include "ffmpeg_video_target.h" #include "except.h" #ifdef USE_BOOST_TIMER #include <boost/timer/timer.hpp> #endif namespace gg { VideoTargetFFmpeg::VideoTargetFFmpeg(const std::string codec) : _codec(NULL), _codec_name(""), _frame(NULL), _framerate(-1), _sws_context(NULL), _format_context(NULL), _stream(NULL), _frame_index(0) { if (codec != "H265") { std::string msg; msg.append("Codec ") .append(codec) .append(" not recognised"); throw VideoTargetError(msg); } #ifdef FFMPEG_HWACCEL _codec_name = "nvenc_hevc"; #else _codec_name = "libx265"; #endif av_register_all(); } void VideoTargetFFmpeg::init(const std::string filepath, const float framerate) { if (framerate <= 0) throw VideoTargetError("Negative fps does not make sense"); if (framerate - (int) framerate > 0) throw VideoTargetError("Only integer framerates are supported"); _framerate = (int) framerate; check_filetype_support(filepath, "mp4"); _filepath = filepath; /* allocate the output media context */ avformat_alloc_output_context2(&_format_context, NULL, NULL, _filepath.c_str()); if (_format_context == NULL) // Use MP4 as default if context cannot be deduced from file extension avformat_alloc_output_context2(&_format_context, NULL, "mp4", NULL); if (_format_context == NULL) throw VideoTargetError("Could not allocate output media context"); _codec = avcodec_find_encoder_by_name(_codec_name.c_str()); if (not _codec) throw VideoTargetError("Codec not found"); _stream = avformat_new_stream(_format_context, _codec); if (_stream == NULL) throw VideoTargetError("Could not allocate stream"); _stream->id = _format_context->nb_streams-1; // TODO isn't this wrong? } void VideoTargetFFmpeg::append(const VideoFrame_BGRA & frame) { if (_framerate <= 0) throw VideoTargetError("Video target not initialised"); // return value buffers int ret, got_output; // if first frame, initialise if (_frame == NULL) { #ifdef USE_BOOST_TIMER #ifndef timer_format_str #define timer_format_str \ std::string(", %w, %u, %s, %t, %p" \ ", wall (s), user (s), system (s), user+system (s), CPU (pc)\n") #endif boost::timer::auto_cpu_timer t("a) _frame == NULL" + timer_format_str); #endif // TODO - is _codec_context ever being modified after first frame? /* TODO: using default reduces filesize * but should we set it nonetheless? */ // _stream->codec->bit_rate = 400000; _stream->codec->width = frame.cols(); _stream->codec->height = frame.rows(); _stream->time_base = (AVRational){ 1, _framerate }; _stream->codec->time_base = _stream->time_base; _stream->codec->gop_size = 12; /* TODO emit one intra frame every twelve frames at most */ _stream->codec->pix_fmt = AV_PIX_FMT_YUV420P; /* Some formats want stream headers to be separate. */ if (_format_context->oformat->flags & AVFMT_GLOBALHEADER) _stream->codec->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; switch (_stream->codec->codec_id) { case AV_CODEC_ID_H264: case AV_CODEC_ID_HEVC: #ifdef FFMPEG_HWACCEL // nop ret = 0; #else /* TODO will this work in real-time with a framegrabber ? * "slow" produces 2x larger file compared to "ultrafast", * but with a substantial visual quality degradation * (judged using the coloured chessboard pattern) * "fast" is a trade-off: visual quality looks similar * while file size is reasonable */ ret = av_opt_set(_stream->codec->priv_data, "preset", "fast", 0); #endif if (ret != 0) throw VideoTargetError("Could not set codec-specific options"); /* Resolution must be a multiple of two, as required * by H264 and H265. Introduce a one-pixel padding for * non-complying dimension(s). */ _stream->codec->width += _stream->codec->width % 2 == 0 ? 0 : 1; _stream->codec->height += _stream->codec->height % 2 == 0 ? 0 : 1; break; default: // nop break; } /* open it */ if (avcodec_open2(_stream->codec, _codec, NULL) < 0) throw VideoTargetError("Could not open codec"); _frame = av_frame_alloc(); if (not _frame) throw VideoTargetError("Could not allocate video frame"); _frame->format = _stream->codec->pix_fmt; _frame->width = _stream->codec->width; _frame->height = _stream->codec->height; /* allocate the buffers for the frame data */ // TODO #25 what influence does 32 have on performance? ret = av_frame_get_buffer(_frame, 32); if (ret < 0) throw VideoTargetError("Could not allocate frame data"); /* Now that all the parameters are set, we can open the audio and * video codecs and allocate the necessary encode buffers. */ av_dump_format(_format_context, 0, _filepath.c_str(), 1); /* open the output file, if needed */ if (!(_format_context->oformat->flags & AVFMT_NOFILE)) { ret = avio_open(&_format_context->pb, _filepath.c_str(), AVIO_FLAG_WRITE); if (ret < 0) { std::string msg; msg.append("File ") .append(_filepath) .append(" could not be opened"); throw VideoTargetError(msg); } } /* Write the stream header, if any. */ ret = avformat_write_header(_format_context, NULL); if (ret < 0) throw VideoTargetError("Could not write header to file"); /* Open context for converting BGRA pixels to YUV420p */ _sws_context = sws_getContext( frame.cols(), frame.rows(), AV_PIX_FMT_BGRA, frame.cols(), frame.rows(), _stream->codec->pix_fmt, 0, NULL, NULL, NULL); if (_sws_context == NULL) throw VideoTargetError("Could not allocate Sws context"); // To be incremented for each frame, used as pts _frame_index = 0; // Packet to be used when writing frames av_init_packet(&_packet); // TODO #25 data gets allocated each time? _packet.data = NULL; // packet data will be allocated by the encoder _packet.size = 0; _bgra_stride[0] = 4*frame.cols(); } { // START auto_cpu_timer scope #ifdef USE_BOOST_TIMER boost::timer::auto_cpu_timer t("a) av_frame_make_writable" + timer_format_str); #endif /* when we pass a frame to the encoder, it may keep a reference to it * internally; * make sure we do not overwrite it here */ // TODO #25 why not only once? ret = av_frame_make_writable(_frame); if (ret < 0) throw VideoTargetError("Could not make frame writeable"); } // END auto_cpu_timer scope { // START auto_cpu_timer scope #ifdef USE_BOOST_TIMER boost::timer::auto_cpu_timer t("a) sws_scale" + timer_format_str); #endif /* convert pixel format */ _src_data_ptr[0] = frame.data(); sws_scale(_sws_context, _src_data_ptr, _bgra_stride, // BGRA has one plane 0, frame.rows(), _frame->data, _frame->linesize ); _frame->pts = _frame_index++; } // END auto_cpu_timer scope { // START auto_cpu_timer scope #ifdef USE_BOOST_TIMER boost::timer::auto_cpu_timer t("a) encode_and_write" + timer_format_str); #endif /* encode the image */ encode_and_write(_frame, got_output); } // END auto_cpu_timer scope } void VideoTargetFFmpeg::encode_and_write(AVFrame * frame, int & got_output) { int ret; { #ifdef USE_BOOST_TIMER boost::timer::auto_cpu_timer t("aa) avcodec_encode_video2" + timer_format_str); #endif ret = avcodec_encode_video2(_stream->codec, &_packet, frame, &got_output); } if (ret < 0) throw VideoTargetError("Error encoding frame"); if (got_output) { { #ifdef USE_BOOST_TIMER boost::timer::auto_cpu_timer t("aa) av_packet_rescale_ts" + timer_format_str); #endif /* rescale output packet timestamp values from codec to stream timebase */ av_packet_rescale_ts(&_packet, _stream->codec->time_base, _stream->time_base); // TODO - above time bases are the same, or not? _packet.stream_index = _stream->index; } { #ifdef USE_BOOST_TIMER boost::timer::auto_cpu_timer t("aa) av_interleaved_write_frame" + timer_format_str); #endif /* Write the compressed frame to the media file. */ int ret = av_interleaved_write_frame(_format_context, &_packet); } if (ret < 0) throw VideoTargetError("Could not interleaved write frame"); // av_packet_unref(&packet); taken care of by av_interleaved_write_frame } } void VideoTargetFFmpeg::finalise() { /* get the delayed frames */ for (int got_output = 1; got_output; ) encode_and_write(NULL, got_output); /* Write the trailer, if any. The trailer must be written before you * close the CodecContexts open when you wrote the header; otherwise * av_write_trailer() may try to use memory that was freed on * av_codec_close(). */ av_write_trailer(_format_context); if (_stream->codec) avcodec_close(_stream->codec); if (_frame) av_frame_free(&_frame); // av_freep(&_frame->data[0]); no need for this because _frame never manages its own data if (_sws_context) sws_freeContext(_sws_context); if (!(_format_context->oformat->flags & AVFMT_NOFILE)) /* Close the output file. */ avio_closep(&_format_context->pb); /* free the stream */ avformat_free_context(_format_context); // default values, for next init _codec = NULL; _codec_name = ""; _frame = NULL; _framerate = -1; _sws_context = NULL; _format_context = NULL; _stream = NULL; _frame_index = 0; } } <commit_msg>Issue #25: now all boost timer scopes marked, and also corrected indentation<commit_after>#include "ffmpeg_video_target.h" #include "except.h" #ifdef USE_BOOST_TIMER #include <boost/timer/timer.hpp> #endif namespace gg { VideoTargetFFmpeg::VideoTargetFFmpeg(const std::string codec) : _codec(NULL), _codec_name(""), _frame(NULL), _framerate(-1), _sws_context(NULL), _format_context(NULL), _stream(NULL), _frame_index(0) { if (codec != "H265") { std::string msg; msg.append("Codec ") .append(codec) .append(" not recognised"); throw VideoTargetError(msg); } #ifdef FFMPEG_HWACCEL _codec_name = "nvenc_hevc"; #else _codec_name = "libx265"; #endif av_register_all(); } void VideoTargetFFmpeg::init(const std::string filepath, const float framerate) { if (framerate <= 0) throw VideoTargetError("Negative fps does not make sense"); if (framerate - (int) framerate > 0) throw VideoTargetError("Only integer framerates are supported"); _framerate = (int) framerate; check_filetype_support(filepath, "mp4"); _filepath = filepath; /* allocate the output media context */ avformat_alloc_output_context2(&_format_context, NULL, NULL, _filepath.c_str()); if (_format_context == NULL) // Use MP4 as default if context cannot be deduced from file extension avformat_alloc_output_context2(&_format_context, NULL, "mp4", NULL); if (_format_context == NULL) throw VideoTargetError("Could not allocate output media context"); _codec = avcodec_find_encoder_by_name(_codec_name.c_str()); if (not _codec) throw VideoTargetError("Codec not found"); _stream = avformat_new_stream(_format_context, _codec); if (_stream == NULL) throw VideoTargetError("Could not allocate stream"); _stream->id = _format_context->nb_streams-1; // TODO isn't this wrong? } void VideoTargetFFmpeg::append(const VideoFrame_BGRA & frame) { if (_framerate <= 0) throw VideoTargetError("Video target not initialised"); // return value buffers int ret, got_output; // if first frame, initialise if (_frame == NULL) { #ifdef USE_BOOST_TIMER #ifndef timer_format_str #define timer_format_str \ std::string(", %w, %u, %s, %t, %p" \ ", wall (s), user (s), system (s), user+system (s), CPU (pc)\n") #endif boost::timer::auto_cpu_timer t("a) _frame == NULL" + timer_format_str); #endif // TODO - is _codec_context ever being modified after first frame? /* TODO: using default reduces filesize * but should we set it nonetheless? */ // _stream->codec->bit_rate = 400000; _stream->codec->width = frame.cols(); _stream->codec->height = frame.rows(); _stream->time_base = (AVRational){ 1, _framerate }; _stream->codec->time_base = _stream->time_base; _stream->codec->gop_size = 12; /* TODO emit one intra frame every twelve frames at most */ _stream->codec->pix_fmt = AV_PIX_FMT_YUV420P; /* Some formats want stream headers to be separate. */ if (_format_context->oformat->flags & AVFMT_GLOBALHEADER) _stream->codec->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; switch (_stream->codec->codec_id) { case AV_CODEC_ID_H264: case AV_CODEC_ID_HEVC: #ifdef FFMPEG_HWACCEL // nop ret = 0; #else /* TODO will this work in real-time with a framegrabber ? * "slow" produces 2x larger file compared to "ultrafast", * but with a substantial visual quality degradation * (judged using the coloured chessboard pattern) * "fast" is a trade-off: visual quality looks similar * while file size is reasonable */ ret = av_opt_set(_stream->codec->priv_data, "preset", "fast", 0); #endif if (ret != 0) throw VideoTargetError("Could not set codec-specific options"); /* Resolution must be a multiple of two, as required * by H264 and H265. Introduce a one-pixel padding for * non-complying dimension(s). */ _stream->codec->width += _stream->codec->width % 2 == 0 ? 0 : 1; _stream->codec->height += _stream->codec->height % 2 == 0 ? 0 : 1; break; default: // nop break; } /* open it */ if (avcodec_open2(_stream->codec, _codec, NULL) < 0) throw VideoTargetError("Could not open codec"); _frame = av_frame_alloc(); if (not _frame) throw VideoTargetError("Could not allocate video frame"); _frame->format = _stream->codec->pix_fmt; _frame->width = _stream->codec->width; _frame->height = _stream->codec->height; /* allocate the buffers for the frame data */ // TODO #25 what influence does 32 have on performance? ret = av_frame_get_buffer(_frame, 32); if (ret < 0) throw VideoTargetError("Could not allocate frame data"); /* Now that all the parameters are set, we can open the audio and * video codecs and allocate the necessary encode buffers. */ av_dump_format(_format_context, 0, _filepath.c_str(), 1); /* open the output file, if needed */ if (!(_format_context->oformat->flags & AVFMT_NOFILE)) { ret = avio_open(&_format_context->pb, _filepath.c_str(), AVIO_FLAG_WRITE); if (ret < 0) { std::string msg; msg.append("File ") .append(_filepath) .append(" could not be opened"); throw VideoTargetError(msg); } } /* Write the stream header, if any. */ ret = avformat_write_header(_format_context, NULL); if (ret < 0) throw VideoTargetError("Could not write header to file"); /* Open context for converting BGRA pixels to YUV420p */ _sws_context = sws_getContext( frame.cols(), frame.rows(), AV_PIX_FMT_BGRA, frame.cols(), frame.rows(), _stream->codec->pix_fmt, 0, NULL, NULL, NULL); if (_sws_context == NULL) throw VideoTargetError("Could not allocate Sws context"); // To be incremented for each frame, used as pts _frame_index = 0; // Packet to be used when writing frames av_init_packet(&_packet); // TODO #25 data gets allocated each time? _packet.data = NULL; // packet data will be allocated by the encoder _packet.size = 0; _bgra_stride[0] = 4*frame.cols(); } { // START auto_cpu_timer scope #ifdef USE_BOOST_TIMER boost::timer::auto_cpu_timer t("a) av_frame_make_writable" + timer_format_str); #endif /* when we pass a frame to the encoder, it may keep a reference to it * internally; * make sure we do not overwrite it here */ // TODO #25 why not only once? ret = av_frame_make_writable(_frame); if (ret < 0) throw VideoTargetError("Could not make frame writeable"); } // END auto_cpu_timer scope { // START auto_cpu_timer scope #ifdef USE_BOOST_TIMER boost::timer::auto_cpu_timer t("a) sws_scale" + timer_format_str); #endif /* convert pixel format */ _src_data_ptr[0] = frame.data(); sws_scale(_sws_context, _src_data_ptr, _bgra_stride, // BGRA has one plane 0, frame.rows(), _frame->data, _frame->linesize ); _frame->pts = _frame_index++; } // END auto_cpu_timer scope { // START auto_cpu_timer scope #ifdef USE_BOOST_TIMER boost::timer::auto_cpu_timer t("a) encode_and_write" + timer_format_str); #endif /* encode the image */ encode_and_write(_frame, got_output); } // END auto_cpu_timer scope } void VideoTargetFFmpeg::encode_and_write(AVFrame * frame, int & got_output) { int ret; { // START auto_cpu_timer scope #ifdef USE_BOOST_TIMER boost::timer::auto_cpu_timer t("aa) avcodec_encode_video2" + timer_format_str); #endif ret = avcodec_encode_video2(_stream->codec, &_packet, frame, &got_output); } // END auto_cpu_timer scope if (ret < 0) throw VideoTargetError("Error encoding frame"); if (got_output) { { // START auto_cpu_timer scope #ifdef USE_BOOST_TIMER boost::timer::auto_cpu_timer t("aa) av_packet_rescale_ts" + timer_format_str); #endif /* rescale output packet timestamp values from codec to stream timebase */ av_packet_rescale_ts(&_packet, _stream->codec->time_base, _stream->time_base); // TODO - above time bases are the same, or not? _packet.stream_index = _stream->index; } // END auto_cpu_timer scope { // START auto_cpu_timer scope #ifdef USE_BOOST_TIMER boost::timer::auto_cpu_timer t("aa) av_interleaved_write_frame" + timer_format_str); #endif /* Write the compressed frame to the media file. */ int ret = av_interleaved_write_frame(_format_context, &_packet); } if (ret < 0) throw VideoTargetError("Could not interleaved write frame"); // av_packet_unref(&packet); taken care of by av_interleaved_write_frame } } void VideoTargetFFmpeg::finalise() { /* get the delayed frames */ for (int got_output = 1; got_output; ) encode_and_write(NULL, got_output); /* Write the trailer, if any. The trailer must be written before you * close the CodecContexts open when you wrote the header; otherwise * av_write_trailer() may try to use memory that was freed on * av_codec_close(). */ av_write_trailer(_format_context); if (_stream->codec) avcodec_close(_stream->codec); if (_frame) av_frame_free(&_frame); // av_freep(&_frame->data[0]); no need for this because _frame never manages its own data if (_sws_context) sws_freeContext(_sws_context); if (!(_format_context->oformat->flags & AVFMT_NOFILE)) /* Close the output file. */ avio_closep(&_format_context->pb); /* free the stream */ avformat_free_context(_format_context); // default values, for next init _codec = NULL; _codec_name = ""; _frame = NULL; _framerate = -1; _sws_context = NULL; _format_context = NULL; _stream = NULL; _frame_index = 0; } } <|endoftext|>
<commit_before>#include <derecho/derecho.h> #include <derecho/view.h> #include <vector> #include <fstream> using namespace derecho; using std::vector; using std::pair; class CookedMessages : public mutils::ByteRepresentable { vector<pair<uint, uint>> msgs; // vector of (nodeid, msg #) public: CookedMessages () {} CookedMessages (const vector<pair<uint,uint>>& msgs) : msgs(msgs){ } void send(uint nodeid, uint local_counter){ msgs.push_back(std::make_pair(node_id, local_counter)); std::cout << "Node " << node_id << " sent msg " << msg << std::endl; } vector<pair<uint, uint>> return_order() { return msgs; } bool verify_order (vector<pair<uint, uint>> v) { if(v.size() != msgs.size()){ std::cout << "State vector sizes differ" << std::endl; return false; } uint order[counter] = {}; uint fst, snd; std::vector<pair<uint, uint>>::iterator a = msgs.begin(); std::vector<pair<uint, uint>>::iterator b = v.begin(); while(a != msgs.end()){ fst = a->first; snd = a->second; if(*a != *b){ std::cout << "Global order error!" << std::endl; return false; } else if(snd != order[fst] + 1){ // may want to loosen to snd <= order[fst] std::cout << "Local order error!" << std::endl; return false; } order[fst] = snd; ++a; ++b; } std::cout << "Pass" << std::endl; return true; } // default state DEFAULT_SERIALIZATION_SUPPORT(CookedMessages, msgs); // what operations you want as part of the subgroup REGISTER_RPC_FUNCTIONS(CookedMessages, send, verify_order); }; int main(int argc, char *argv[]) { if(argc < 2) { std::cout << "Provide the number of nodes as a command line argument" << std::endl; exit(1); } const uint32_t num_nodes = atoi(argv[1]); node_id_t my_id; ip_addr leader_ip, my_ip; std::cout << "Enter my id: " << std::endl; std::cin >> my_id; std::cout << "Enter my ip: " << std::endl; std::cin >> my_ip; std::cout << "Enter leader's ip: " << std::endl; std::cin >> leader_ip; Group<Messages>* group; auto delivery_callback = [my_id](subgroup_id_t subgroup_id, node_id_t sender_id, message_id_t index, char* buf, long long int size) { // null message filter if(size == 0) { return; } std::cout << "In the delivery callback for subgroup_id=" << subgroup_id << ", sender=" << sender_id << std::endl; std::cout << "Message: " << buf << std::endl; return; }; CallbackSet callbacks{delivery_callback}; std::map<std::type_index, shard_view_generator_t> subgroup_membership_functions{{std::type_index(typeid(TicketBookingSystem)), [num_nodes](const View& view, int&, bool) { auto& members = view.members; auto num_members = members.size(); if (num_members < num_nodes) { throw subgroup_provisioning_exception(); } subgroup_shard_layout_t layout(num_members); // for (uint i = 0; i < num_members; ++i) { // layout[i].push_back(view.make_subview(vector<uint32_t>{members[i], members[(i+1)%num_members], members[(i+2)%num_members]})); // layout[i]. layout[0].push_back(view.make_subview(vector<uint32_t>(members))); // } return layout; }}}; auto ticket_subgroup_factory = [num_tickets=100u] (PersistentRegistry*) {return std::make_unique<TicketBookingSystem>(num_tickets);}; const unsigned long long int max_msg_size = 200; DerechoParams derecho_params{max_msg_size, max_msg_size, max_msg_size}; SubgroupInfo subgroup_info(subgroup_membership_functions); auto view_upcall = [](const View& view) { std::cout << "The members are: " << std::endl; for (auto m : view.members) { std::cout << m << " "; } std::cout << std::endl; }; if(my_id == 0) { group = new Group<TicketBookingSystem>(my_id, my_ip, callbacks, subgroup_info, derecho_params, vector<view_upcall_t>{view_upcall}, ticket_subgroup_factory); } else { group = new Group<TicketBookingSystem>(my_id, my_ip, leader_ip, callbacks, subgroup_info, vector<view_upcall_t>{view_upcall}, ticket_subgroup_factory); } std::cout << "Finished constructing/joining the group" << std::endl; auto group_members = group->get_members(); uint32_t my_rank = -1; std::cout << "Members are" << std::endl; for(uint i = 0; i < group_members.size(); ++i) { std::cout << group_members[i] << " "; if(group_members[i] == my_id) { my_rank = i; } } std::cout << std::endl; if (my_rank == (uint32_t) -1) { exit(1); } // wait until groups are provisioned // // all members book a ticket // Replicated<TicketBookingSystem>& ticketBookingHandle = group->get_subgroup<TicketBookingSystem>(); int num_messages = argv[]; for (int counter = 0; counter < num_messages; ++counter) { properhandle.ordered_send<RPC_NAME(send)>(node_id, counter); } // rpc::QueryResults<bool> results = ticketBookingHandle.ordered_query<RPC_NAME(book)>(my_rank); // rpc::QueryResults<bool>::ReplyMap& replies = results.get(); // for (auto& reply_pair: replies) { // std::cout << "Reply from node " << reply_pair.first << ": " << std::boolalpha << reply_pair.second.get() << std::endl; // } std::cout << "End of main. Waiting indefinitely" << std::endl; while(true) { } return 0; } <commit_msg>moving to branch<commit_after><|endoftext|>
<commit_before>/** Copyright (c) 2009 James Wynn (james@jameswynn.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. James Wynn james@jameswynn.com */ #include <FileWatcher/FileWatcherOSX.h> #if FILEWATCHER_PLATFORM == FILEWATCHER_PLATFORM_KQUEUE #include <sys/event.h> #include <sys/time.h> #include <sys/stat.h> #include <unistd.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <dirent.h> #include <string.h> void handleAction(const FW::String& filename, FW::Actions::Action action); namespace FW { #define MAX_CHANGE_EVENT_SIZE 2000 typedef struct kevent KEvent; struct EntryStruct { EntryStruct(const char* filename, time_t mtime = 0) : mFilename(filename), mModifiedTime(mtime) { } ~EntryStruct() { delete[] mFilename; } const char* mFilename; time_t mModifiedTime; }; int comparator(const void* ke1, const void* ke2) { /*KEvent* kevent1 = (KEvent*) ke1; KEvent* kevent2 = (KEvent*) ke2; EntryStruct* event1 = (EntryStruct*)kevent1->udata; EntryStruct* event2 = (EntryStruct*)kevent2->udata; return strcmp(event1->mFilename, event2->mFilename); */ return strcmp(((EntryStruct*)(((KEvent*)(ke1))->udata))->mFilename, ((EntryStruct*)(((KEvent*)(ke2))->udata))->mFilename); } struct WatchStruct { WatchID mWatchID; String mDirName; FileWatchListener* mListener; // index 0 is always the directory KEvent mChangeList[MAX_CHANGE_EVENT_SIZE]; size_t mChangeListCount; WatchStruct(WatchID watchid, const String& dirname, FileWatchListener* listener) : mWatchID(watchid), mDirName(dirname), mListener(listener) { mChangeListCount = 0; addAll(); } void addFile(const String& name, bool imitEvents = true) { //fprintf(stderr, "ADDED: %s\n", name.c_str()); // create entry struct stat attrib; stat(name.c_str(), &attrib); int fd = open(name.c_str(), O_RDONLY); if(fd == -1) throw FileNotFoundException(name); ++mChangeListCount; char* namecopy = new char[name.length() + 1]; strncpy(namecopy, name.c_str(), name.length()); namecopy[name.length()] = 0; EntryStruct* entry = new EntryStruct(namecopy, attrib.st_mtime); // set the event data at the end of the list EV_SET(&mChangeList[mChangeListCount], fd, EVFILT_VNODE, EV_ADD | EV_ENABLE | EV_ONESHOT, NOTE_DELETE | NOTE_EXTEND | NOTE_WRITE | NOTE_ATTRIB, 0, (void*)entry); // qsort qsort(mChangeList + 1, mChangeListCount, sizeof(KEvent), comparator); Actions::Action a; // handle action if(imitEvents) //;// handleAction(name, Action::Add); // AMS handleAction(name, Actions::Add);// FW::Actions::Action::Add); } void removeFile(const String& name, bool imitEvents = true) { // bsearch KEvent target; EntryStruct tempEntry(name.c_str(), 0); target.udata = &tempEntry; KEvent* ke = (KEvent*)bsearch(&target, &mChangeList, mChangeListCount + 1, sizeof(KEvent), comparator); if(!ke) ;// throw FileNotFoundException(directory); // AMS tempEntry.mFilename = 0; // delete close(ke->ident); delete((EntryStruct*)ke->udata); memset(ke, 0, sizeof(KEvent)); // move end to current memcpy(ke, &mChangeList[mChangeListCount], sizeof(KEvent)); memset(&mChangeList[mChangeListCount], 0, sizeof(KEvent)); --mChangeListCount; // qsort qsort(mChangeList + 1, mChangeListCount, sizeof(KEvent), comparator); // handle action if(imitEvents) ; // handleAction(name, Action::Delete); // AMS } // called when the directory is actually changed // means a file has been added or removed // rescans the watched directory adding/removing files and sending notices void rescan() { // if new file, call addFile // if missing file, call removeFile // if timestamp modified, call handleAction(filename, ACTION_MODIFIED); DIR* dir = opendir(mDirName.c_str()); if(!dir) return; struct dirent* dentry; KEvent* ke = &mChangeList[1]; EntryStruct* entry = 0; struct stat attrib; while((dentry = readdir(dir)) != NULL) { String fname = mDirName + "/" + dentry->d_name; stat(fname.c_str(), &attrib); if(!S_ISREG(attrib.st_mode)) continue; if(ke <= &mChangeList[mChangeListCount]) { entry = (EntryStruct*)ke->udata; int result = strcmp(entry->mFilename, fname.c_str()); //fprintf(stderr, "[%s cmp %s]\n", entry->mFilename, fname.c_str()); if(result == 0) { stat(entry->mFilename, &attrib); time_t timestamp = attrib.st_mtime; if(entry->mModifiedTime != timestamp) { entry->mModifiedTime = timestamp; // handleAction(entry->mFilename, Action::Modified); // AMS } ke++; } else if(result < 0) { // f1 was deleted removeFile(entry->mFilename); ke++; } else { // f2 was created addFile(fname); ke++; } } else { // just add addFile(fname); ke++; } }//end while closedir(dir); }; #if 0 // AMS void handleAction(const String& filename, /*FileWatcher::*/Action action) { mListener->handleFileAction(mWatchID, mDirName, filename, action); } #endif void addAll() { // add base dir int fd = open(mDirName.c_str(), O_RDONLY); EV_SET(&mChangeList[0], fd, EVFILT_VNODE, EV_ADD | EV_ENABLE | EV_ONESHOT, NOTE_DELETE | NOTE_EXTEND | NOTE_WRITE | NOTE_ATTRIB, 0, 0); //fprintf(stderr, "ADDED: %s\n", mDirName.c_str()); // scan directory and call addFile(name, false) on each file DIR* dir = opendir(mDirName.c_str()); if(!dir) ; // throw FileNotFoundException(directory); // AMS Action a; struct dirent* entry; struct stat attrib; while((entry = readdir(dir)) != NULL) { String fname = (mDirName + "/" + String(entry->d_name)); stat(fname.c_str(), &attrib); if(S_ISREG(attrib.st_mode)) addFile(fname, false); //else // fprintf(stderr, "NOT ADDED: %s (%d)\n", fname.c_str(), attrib.st_mode); }//end while closedir(dir); } void removeAll() { KEvent* ke = NULL; // go through list removing each file and sending an event for(int i = 0; i < mChangeListCount; ++i) { ke = &mChangeList[i]; //handleAction(name, Action::Delete); EntryStruct* entry = (EntryStruct*)ke->udata; // handleAction(entry->mFilename, Action::Delete); // ams // delete close(ke->ident); delete((EntryStruct*)ke->udata); } } }; void FileWatcherOSX::update() { int nev = 0; struct kevent event; WatchMap::iterator iter = mWatches.begin(); WatchMap::iterator end = mWatches.end(); for(; iter != end; ++iter) { WatchStruct* watch = iter->second; while((nev = kevent(mDescriptor, (KEvent*)&(watch->mChangeList), watch->mChangeListCount + 1, &event, 1, &mTimeOut)) != 0) { if(nev == -1) perror("kevent"); else { EntryStruct* entry = 0; if((entry = (EntryStruct*)event.udata) != 0) { //fprintf(stderr, "File: %s -- ", (char*)entry->mFilename); if(event.fflags & NOTE_DELETE) { //fprintf(stderr, "File deleted\n"); //watch->handleAction(entry->mFilename, Action::Delete); watch->removeFile(entry->mFilename); } if(event.fflags & NOTE_EXTEND || event.fflags & NOTE_WRITE || event.fflags & NOTE_ATTRIB) { //fprintf(stderr, "modified\n"); //watch->rescan(); struct stat attrib; stat(entry->mFilename, &attrib); entry->mModifiedTime = attrib.st_mtime; ; // watch->handleAction(entry->mFilename, Action::Modified); // AMS } } else { //fprintf(stderr, "Dir: %s -- rescanning\n", watch->mDirName.c_str()); watch->rescan(); } } } } } //-------- FileWatcherOSX::FileWatcherOSX() { mDescriptor = kqueue(); mTimeOut.tv_sec = 0; mTimeOut.tv_nsec = 0; } //-------- FileWatcherOSX::~FileWatcherOSX() { WatchMap::iterator iter = mWatches.begin(); WatchMap::iterator end = mWatches.end(); for(; iter != end; ++iter) { delete iter->second; } mWatches.clear(); close(mDescriptor); } //-------- WatchID FileWatcherOSX::addWatch(const String& directory, FileWatchListener* watcher) { /* int fd = open(directory.c_str(), O_RDONLY); if(fd == -1) perror("open"); EV_SET(&change, fd, EVFILT_VNODE, EV_ADD | EV_ENABLE | EV_ONESHOT, NOTE_DELETE | NOTE_EXTEND | NOTE_WRITE | NOTE_ATTRIB, 0, (void*)"testing"); */ WatchStruct* watch = new WatchStruct(++mLastWatchID, directory, watcher); mWatches.insert(std::make_pair(mLastWatchID, watch)); return mLastWatchID; } //-------- void FileWatcherOSX::removeWatch(const String& directory) { WatchMap::iterator iter = mWatches.begin(); WatchMap::iterator end = mWatches.end(); for(; iter != end; ++iter) { if(directory == iter->second->mDirName) { removeWatch(iter->first); return; } } } //-------- void FileWatcherOSX::removeWatch(WatchID watchid) { WatchMap::iterator iter = mWatches.find(watchid); if(iter == mWatches.end()) return; WatchStruct* watch = iter->second; mWatches.erase(iter); //inotify_rm_watch(mFD, watchid); delete watch; watch = 0; } //-------- void FileWatcherOSX::handleAction(WatchStruct* watch, const String& filename, unsigned long action) { } };//namespace FW #endif//FILEWATCHER_PLATFORM_KQUEUE #if 1// AMS void handleAction(const FW::String& filename, FW::Actions::Action action) { ;//mListener->handleFileAction(mWatchID, mDirName, filename, action); } #endif void func() { FW::Actions::Action a; } <commit_msg>Added Comments on planned changes<commit_after>/** Copyright (c) 2009 James Wynn (james@jameswynn.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. James Wynn james@jameswynn.com */ /* Plan: */ /* FIXED compilation errors w/ exception Do Fix Namespace - should not be using closure here. */ #include <FileWatcher/FileWatcherOSX.h> #if FILEWATCHER_PLATFORM == FILEWATCHER_PLATFORM_KQUEUE #include <sys/event.h> #include <sys/time.h> #include <sys/stat.h> #include <unistd.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <dirent.h> #include <string.h> void handleAction(const FW::String& filename, FW::Actions::Action action); namespace FW { #define MAX_CHANGE_EVENT_SIZE 2000 typedef struct kevent KEvent; struct EntryStruct { EntryStruct(const char* filename, time_t mtime = 0) : mFilename(filename), mModifiedTime(mtime) { } ~EntryStruct() { delete[] mFilename; } const char* mFilename; time_t mModifiedTime; }; int comparator(const void* ke1, const void* ke2) { /*KEvent* kevent1 = (KEvent*) ke1; KEvent* kevent2 = (KEvent*) ke2; EntryStruct* event1 = (EntryStruct*)kevent1->udata; EntryStruct* event2 = (EntryStruct*)kevent2->udata; return strcmp(event1->mFilename, event2->mFilename); */ return strcmp(((EntryStruct*)(((KEvent*)(ke1))->udata))->mFilename, ((EntryStruct*)(((KEvent*)(ke2))->udata))->mFilename); } struct WatchStruct { WatchID mWatchID; String mDirName; FileWatchListener* mListener; // index 0 is always the directory KEvent mChangeList[MAX_CHANGE_EVENT_SIZE]; size_t mChangeListCount; WatchStruct(WatchID watchid, const String& dirname, FileWatchListener* listener) : mWatchID(watchid), mDirName(dirname), mListener(listener) { mChangeListCount = 0; addAll(); } void addFile(const String& name, bool imitEvents = true) { //fprintf(stderr, "ADDED: %s\n", name.c_str()); // create entry struct stat attrib; stat(name.c_str(), &attrib); int fd = open(name.c_str(), O_RDONLY); if(fd == -1) throw FileNotFoundException(name); ++mChangeListCount; char* namecopy = new char[name.length() + 1]; strncpy(namecopy, name.c_str(), name.length()); namecopy[name.length()] = 0; EntryStruct* entry = new EntryStruct(namecopy, attrib.st_mtime); // set the event data at the end of the list EV_SET(&mChangeList[mChangeListCount], fd, EVFILT_VNODE, EV_ADD | EV_ENABLE | EV_ONESHOT, NOTE_DELETE | NOTE_EXTEND | NOTE_WRITE | NOTE_ATTRIB, 0, (void*)entry); // qsort qsort(mChangeList + 1, mChangeListCount, sizeof(KEvent), comparator); Actions::Action a; // handle action if(imitEvents) //;// handleAction(name, Action::Add); // AMS handleAction(name, Actions::Add);// FW::Actions::Action::Add); } void removeFile(const String& name, bool imitEvents = true) { // bsearch KEvent target; EntryStruct tempEntry(name.c_str(), 0); target.udata = &tempEntry; KEvent* ke = (KEvent*)bsearch(&target, &mChangeList, mChangeListCount + 1, sizeof(KEvent), comparator); if(!ke) ;// throw FileNotFoundException(directory); // AMS tempEntry.mFilename = 0; // delete close(ke->ident); delete((EntryStruct*)ke->udata); memset(ke, 0, sizeof(KEvent)); // move end to current memcpy(ke, &mChangeList[mChangeListCount], sizeof(KEvent)); memset(&mChangeList[mChangeListCount], 0, sizeof(KEvent)); --mChangeListCount; // qsort qsort(mChangeList + 1, mChangeListCount, sizeof(KEvent), comparator); // handle action if(imitEvents) ; // handleAction(name, Action::Delete); // AMS } // called when the directory is actually changed // means a file has been added or removed // rescans the watched directory adding/removing files and sending notices void rescan() { // if new file, call addFile // if missing file, call removeFile // if timestamp modified, call handleAction(filename, ACTION_MODIFIED); DIR* dir = opendir(mDirName.c_str()); if(!dir) return; struct dirent* dentry; KEvent* ke = &mChangeList[1]; EntryStruct* entry = 0; struct stat attrib; while((dentry = readdir(dir)) != NULL) { String fname = mDirName + "/" + dentry->d_name; stat(fname.c_str(), &attrib); if(!S_ISREG(attrib.st_mode)) continue; if(ke <= &mChangeList[mChangeListCount]) { entry = (EntryStruct*)ke->udata; int result = strcmp(entry->mFilename, fname.c_str()); //fprintf(stderr, "[%s cmp %s]\n", entry->mFilename, fname.c_str()); if(result == 0) { stat(entry->mFilename, &attrib); time_t timestamp = attrib.st_mtime; if(entry->mModifiedTime != timestamp) { entry->mModifiedTime = timestamp; // handleAction(entry->mFilename, Action::Modified); // AMS } ke++; } else if(result < 0) { // f1 was deleted removeFile(entry->mFilename); ke++; } else { // f2 was created addFile(fname); ke++; } } else { // just add addFile(fname); ke++; } }//end while closedir(dir); }; #if 0 // AMS void handleAction(const String& filename, /*FileWatcher::*/Action action) { mListener->handleFileAction(mWatchID, mDirName, filename, action); } #endif void addAll() { // add base dir int fd = open(mDirName.c_str(), O_RDONLY); EV_SET(&mChangeList[0], fd, EVFILT_VNODE, EV_ADD | EV_ENABLE | EV_ONESHOT, NOTE_DELETE | NOTE_EXTEND | NOTE_WRITE | NOTE_ATTRIB, 0, 0); //fprintf(stderr, "ADDED: %s\n", mDirName.c_str()); // scan directory and call addFile(name, false) on each file DIR* dir = opendir(mDirName.c_str()); if(!dir) ; // throw FileNotFoundException(directory); // AMS Action a; struct dirent* entry; struct stat attrib; while((entry = readdir(dir)) != NULL) { String fname = (mDirName + "/" + String(entry->d_name)); stat(fname.c_str(), &attrib); if(S_ISREG(attrib.st_mode)) addFile(fname, false); //else // fprintf(stderr, "NOT ADDED: %s (%d)\n", fname.c_str(), attrib.st_mode); }//end while closedir(dir); } void removeAll() { KEvent* ke = NULL; // go through list removing each file and sending an event for(int i = 0; i < mChangeListCount; ++i) { ke = &mChangeList[i]; //handleAction(name, Action::Delete); EntryStruct* entry = (EntryStruct*)ke->udata; // handleAction(entry->mFilename, Action::Delete); // ams // delete close(ke->ident); delete((EntryStruct*)ke->udata); } } }; void FileWatcherOSX::update() { int nev = 0; struct kevent event; WatchMap::iterator iter = mWatches.begin(); WatchMap::iterator end = mWatches.end(); for(; iter != end; ++iter) { WatchStruct* watch = iter->second; while((nev = kevent(mDescriptor, (KEvent*)&(watch->mChangeList), watch->mChangeListCount + 1, &event, 1, &mTimeOut)) != 0) { if(nev == -1) perror("kevent"); else { EntryStruct* entry = 0; if((entry = (EntryStruct*)event.udata) != 0) { //fprintf(stderr, "File: %s -- ", (char*)entry->mFilename); if(event.fflags & NOTE_DELETE) { //fprintf(stderr, "File deleted\n"); //watch->handleAction(entry->mFilename, Action::Delete); watch->removeFile(entry->mFilename); } if(event.fflags & NOTE_EXTEND || event.fflags & NOTE_WRITE || event.fflags & NOTE_ATTRIB) { //fprintf(stderr, "modified\n"); //watch->rescan(); struct stat attrib; stat(entry->mFilename, &attrib); entry->mModifiedTime = attrib.st_mtime; ; // watch->handleAction(entry->mFilename, Action::Modified); // AMS } } else { //fprintf(stderr, "Dir: %s -- rescanning\n", watch->mDirName.c_str()); watch->rescan(); } } } } } //-------- FileWatcherOSX::FileWatcherOSX() { mDescriptor = kqueue(); mTimeOut.tv_sec = 0; mTimeOut.tv_nsec = 0; } //-------- FileWatcherOSX::~FileWatcherOSX() { WatchMap::iterator iter = mWatches.begin(); WatchMap::iterator end = mWatches.end(); for(; iter != end; ++iter) { delete iter->second; } mWatches.clear(); close(mDescriptor); } //-------- WatchID FileWatcherOSX::addWatch(const String& directory, FileWatchListener* watcher) { /* int fd = open(directory.c_str(), O_RDONLY); if(fd == -1) perror("open"); EV_SET(&change, fd, EVFILT_VNODE, EV_ADD | EV_ENABLE | EV_ONESHOT, NOTE_DELETE | NOTE_EXTEND | NOTE_WRITE | NOTE_ATTRIB, 0, (void*)"testing"); */ WatchStruct* watch = new WatchStruct(++mLastWatchID, directory, watcher); mWatches.insert(std::make_pair(mLastWatchID, watch)); return mLastWatchID; } //-------- void FileWatcherOSX::removeWatch(const String& directory) { WatchMap::iterator iter = mWatches.begin(); WatchMap::iterator end = mWatches.end(); for(; iter != end; ++iter) { if(directory == iter->second->mDirName) { removeWatch(iter->first); return; } } } //-------- void FileWatcherOSX::removeWatch(WatchID watchid) { WatchMap::iterator iter = mWatches.find(watchid); if(iter == mWatches.end()) return; WatchStruct* watch = iter->second; mWatches.erase(iter); //inotify_rm_watch(mFD, watchid); delete watch; watch = 0; } //-------- void FileWatcherOSX::handleAction(WatchStruct* watch, const String& filename, unsigned long action) { } };//namespace FW #endif//FILEWATCHER_PLATFORM_KQUEUE #if 1// AMS void handleAction(const FW::String& filename, FW::Actions::Action action) { ;//mListener->handleFileAction(mWatchID, mDirName, filename, action); } #endif void func() { FW::Actions::Action a; } <|endoftext|>
<commit_before>/*################################################### ##################Cic-Cac-Coe###################### ######## All rights reserved to SAFAD(C) ########## ###########Please read the LICENSE file############ ###################################################*/ #include <iostream> #include <cstdlib> #include <vector> #include <algorithm> using namespace std; //This is our board, 0 => empty, 1 => X, 2 => O vector<int> originalBoard; //the game is running or not ? 1 yes , 0 no int status = 0; //turns 1 = player1, 2 = player2 OR CPU char turn = 1; //to define the character we put in the column char block; //the user input int selection; //AI vs Human int opponent; int checkGame(vector<int> board); void run(); //show the board char ReplaceBlocks(int blockId){ switch(blockId) { case 1: return 'X'; //it is the first player.. case 0: return ' '; //an empty block case 2: return 'O'; //second player here.. } return ' '; } void DrawBoard() { for(int i=0; i<7; i+=3) { cout << " " << ReplaceBlocks(originalBoard[i]) <<" | "<< ReplaceBlocks(originalBoard[i+1]) << " | " << ReplaceBlocks(originalBoard[i+2]) << endl; if (i != 6) { cout << "---+---+---" <<endl; } } } //tell them spike, tell them its a draw !! void show_draw(){ cout << "Nothing to see here Peeps, its a Draw" << endl; } //show winner ! void show_winner(){ cout << "Winner is Player " << turn << " congratulations !!" << endl; } //check who won ! bool check_winner(vector<int> board){ for(int i=0; i<7; i+=3) { if((board[i] == 2 && board[i+1] == 2 && board[i+2] == 2) || (board[i] == 1 && board[i+1] == 1 && board[i+2] == 1)){ return true; } } for(int i=0; i<3; i++) { if((board[i] == 2 && board[i+3] == 2 && board[i+6] == 2) || (board[i] == 1 && board[i+3] == 1 && board[i+6] == 1)){ return true; } } for(int i=0; i<3; i+=2) { if((board[i] == 2 && board[4] == 2 && board[8-i] == 2) || (board[i] == 1 && board[4] == 1 && board[8-i] == 1)){ return true; } } return false; } bool check_draw(vector<int> board){ if (std::count(board.begin(), board.end(), '0') < 0) { //there still are no more moves //now lets see if someone one if (!check_winner(board)) { return true; } } return false; } //validates the user input bool validate_selection(int selection){ //first we check if it is out of range if (selection > 8 || selection < 0) { return false; } if(originalBoard[selection] == 1 || originalBoard[selection] == 2){ return false; } else { return true; } } //function to switch from player one to two and vice versa void switch_turns(){ turn = (turn == 1) ? 2 : 1; run(); } void check_status(vector<int> board){ int gameStatus = checkGame(board); //before we switch turns, we check if the user won or not if(gameStatus == 0){ switch_turns(); } //what if the game is a Draw ? else if(gameStatus == 2){ show_draw(); status = 0; } else if(gameStatus == 1){ //winnnnnn show_winner(); status = 0; } } vector<int> getAllPossibleMoves(vector<int> board){ vector<int> spaces; for (int i = 0; i < 9; ++i) { if (board[i] == '0') { //this is the chosen one spaces.push_back(i); } } return spaces; } //we use this function to check the game status, is it won, or draw //int unfinished = 0, won = 1, draw = 2; int checkGame(vector<int> board){ if(check_winner(board)){ return 1; } //what if the game is a Draw ? else if(check_draw(board)){ return 2; } return 0; } int getScore(vector<int> board, char turn){ int bestScore = 0, iterations = 0, MAXWIN = 100, penalty = -5; //here, we read all the possible moves, and choose the best based on the score //score, MAXWIN = 100, DRAW = 0, MAXLOSE = -5 //The MAXWIN score is acheived by doing the least of iterations //MAXLOSE score is achieved by doing the most of iterations, this means the computer, if he is going to lose, choose the longest path //How to calculate score: MAXWIN += -5*(iterations); MAXLOSE += 5*(iterations); //first we get all the possible moves vector<int> moves = getAllPossibleMoves(board); //now we loop through every possibility for(std::vector<int>::size_type i = 0; i != moves.size(); i++) { //okay so for this we clone the board, add our move vector<int> newBoard(board); //then we add a move newBoard[moves[i]] = turn; //now we check if the game is won or a draw if (checkGame(newBoard) == 1){ //this move, wins the game, but who won? //if the AI wins : calculate the score, if it is better, save it as best score //if the opponent wins : we calculate the lose score, compare it if it is better, then save it.. int score; if (turn == 2) { //its me mittens! score = MAXWIN + penalty*iterations; }else{ //its the human being... score = -MAXWIN + penalty*iterations; } bestScore = (bestScore < score) ? score : bestScore; }else if (checkGame(newBoard) == 2){ //its a draw, we see if the bestScore is a losing score, we rather draw than lose.. bestScore = (bestScore < 0) ? 0 : bestScore; }else{ //the game is unfinished ++iterations; //now we create a new board, and get its best score.. vector<int> clonedBoard(newBoard); char newTurn = (turn == 1) ? 2 : 1; int score = getScore(clonedBoard,newTurn); bestScore = (bestScore < score) ? score : bestScore; } } return bestScore; } bool opponentMove(vector<int> board){ bool win = false; vector<int> opponentMoves = getAllPossibleMoves(board); for(std::vector<int>::size_type i = 0; i != opponentMoves.size(); i++) { vector<int> newBoard(originalBoard); newBoard[opponentMoves[i]] = 1; if (checkGame(newBoard) == 1) { win = true; break; } } return win; } int nextMove(){ //first we see, if the game has just begun //first we generate a list of all possible moves //then we loop over it over each choice, if the game can be lost on the next human move //priority = 0 if draw, 1 if lose, 2 if win; int bestScore = 0, bestPriority, bestMove = 0; vector<int> moves = getAllPossibleMoves(originalBoard); int size = moves.size(); if (size == 8) { int random = rand() % moves[7] + moves[0]; return moves[random]; } //now we see what the opponent would pick.. if (opponentMove(originalBoard)) { /* code */ } for(std::vector<int>::size_type i = 0; i != size; i++) { vector<int> newBoard(originalBoard); newBoard[moves[i]] = 2; //now we check whether the move wins us or not int priority = checkGame(newBoard); if (priority > bestPriority && priority != 0) { bestPriority = priority; bestMove = moves[i]; } else if (priority == 0) { //the game is unfinished, if true it means he can win if (!opponentMove(newBoard) && priority > bestPriority) { bestPriority = priority; bestMove = moves[i]; } } } return bestMove; } void AI(){ //cout << "Calculating..." << endl; int next = nextMove(); //now we use it on screen if(validate_selection(next)){ originalBoard[next] = 2; check_status(originalBoard); } else{ AI(); } } void player(){ cout << "Player " << turn << " Please enter a valid number (0-8) :" <<endl; cin >> selection; if(validate_selection(selection)){ originalBoard[selection] = turn; check_status(originalBoard); }else{ //his choice is invalid cout << "invalid move" << endl; player(); } } //function to show the board void run(){ DrawBoard(); //Artificial Inteligence :) if(opponent == 2 && turn == 2){ AI(); } else{ player(); } } int main(){ //we first populate the board with dummy strings char dummy[9] = {'0','0','0','0','0','0','0','0','0'}; for(int index=0;index<9; ++index) { originalBoard.push_back(dummy[index]); } if(status == 0){ cout << "Play VS :" << endl; cout << "1. Human" << endl; cout << "2. AI (CPU)" << endl; cin >> opponent; status = 1; } run(); } <commit_msg>Implemented MinMax, it feels a bit bad, but I will work it out<commit_after>/*################################################### ##################Cic-Cac-Coe###################### ######## All rights reserved to SAFAD(C) ########## ###########Please read the LICENSE file############ ###################################################*/ #include <iostream> #include <cstdlib> #include <vector> #include <algorithm> using namespace std; //This is our board, 0 => empty, 1 => X, 2 => O vector<int> originalBoard; //the game is running or not ? 1 yes , 0 no int status = 0; //turns 1 = player1, -1 = player2 OR CPU char turn = -1; //to define the character we put in the column char block; //the user input int selection; //AI vs Human int opponent; int checkGame(vector<int> board); void run(); //show the board char ReplaceBlocks(int blockId){ switch(blockId) { case -1: return 'X'; //it is the first player.. case 0: return ' '; //an empty block case 1: return 'O'; //second player here.. } return ' '; } void DrawBoard() { for(int i=0; i<7; i+=3) { cout << " " << ReplaceBlocks(originalBoard[i]) <<" | "<< ReplaceBlocks(originalBoard[i+1]) << " | " << ReplaceBlocks(originalBoard[i+2]) << endl; if (i != 6) { cout << "---+---+---" <<endl; } } } //tell them spike, tell them its a draw !! void show_draw(){ cout << "Nothing to see here Peeps, its a Draw" << endl; } //show winner ! void show_winner(){ cout << "Winner is Player " << turn << " congratulations !!" << endl; } //check who won ! int check_winner(vector<int> board){ for(int i=0; i<7; i+=3) { if((board[i] == -1 && board[i+1] == -1 && board[i+2] == -1) || (board[i] == 1 && board[i+1] == 1 && board[i+2] == 1)){ return board[i]; } } for(int i=0; i<3; i++) { if((board[i] == -1 && board[i+3] == -1 && board[i+6] == -1) || (board[i] == 1 && board[i+3] == 1 && board[i+6] == 1)){ return board[i]; } } for(int i=0; i<3; i+=2) { if((board[i] == -1 && board[4] == -1 && board[8-i] == -1) || (board[i] == 1 && board[4] == 1 && board[8-i] == 1)){ return board[i]; } } return 0; } bool check_draw(vector<int> board){ if (std::count(board.begin(), board.end(), 0) < 0) { //there still are no more moves //now lets see if someone one if (!check_winner(board)) { return true; } } return false; } //validates the user input bool validate_selection(int selection){ //first we check if it is out of range if (selection > 8 || selection < 0) { return false; } if(originalBoard[selection] == 1 || originalBoard[selection] == -1){ return false; } else { return true; } } //function to switch from player one to two and vice versa void switch_turns(){ turn = (turn == 1) ? -1 : 1; run(); } void check_status(vector<int> board){ int gameStatus = checkGame(board); //before we switch turns, we check if the user won or not if(gameStatus == 0){ switch_turns(); } //what if the game is a Draw ? else if(gameStatus == 2){ show_draw(); status = 0; } else if(gameStatus == 1){ //winnnnnn show_winner(); status = 0; } } vector<int> getAllPossibleMoves(vector<int> board){ vector<int> spaces; for (int i = 0; i < 9; ++i) { if (board[i] == 0) { //this is the chosen one spaces.push_back(i); } } return spaces; } //we use this function to check the game status, is it won, or draw //int unfinished = 0, won = 1, draw = 2; int checkGame(vector<int> board){ if(check_winner(board)){ return 1; } //what if the game is a Draw ? else if(check_draw(board)){ return 2; } return 0; } int minmax(vector<int> board, int player){ //player == 1 => X, == -1 => O int win = check_winner(board), bestScore = -2, bestMove = -1; if (win > 0) return player*win; for(std::vector<int>::size_type i = 0; i != originalBoard.size(); i++) { if (board[i] == 0) { board[i] = player; int score = -minmax(board, -player); cout << score << endl; if (score > bestScore) { bestScore = score; bestMove = i; } board[i] = 0; } } if(bestMove == -1) return 0; return bestScore; } void AI(){ //cout << "Calculating..." << endl; int bestScore = -2, bestMove = -1; for(std::vector<int>::size_type i = 0; i != originalBoard.size(); i++) { if (originalBoard[i] == 0) { originalBoard[i] = 1; int score = -minmax(originalBoard, -1); originalBoard[i] = 0; if (score > bestScore) { bestScore = score; bestMove = i; } } } //now we use it on screen originalBoard[bestMove] = 1; check_status(originalBoard); } void player(){ cout << "Player " << turn << " Please enter a valid number (0-8) :" <<endl; cin >> selection; if(validate_selection(selection)){ originalBoard[selection] = turn; check_status(originalBoard); }else{ //his choice is invalid cout << "invalid move" << endl; player(); } } //function to show the board void run(){ if (opponent == 2) { if (turn == -1) { DrawBoard(); } }else{ DrawBoard(); } //Artificial Inteligence :) if(opponent == 2 && turn == 1){ AI(); } else{ player(); } } int main(){ //we first populate the board with dummy strings int dummy[9] = {0,0,0,0,0,0,0,0,0}; for(int index=0;index<9; ++index) { originalBoard.push_back(dummy[index]); } if(status == 0){ cout << "Play VS :" << endl; cout << "1. Human" << endl; cout << "2. AI (CPU)" << endl; cin >> opponent; status = 1; } run(); } <|endoftext|>
<commit_before>/** * \file t_LA.cpp * \brief * \date Oct 13, 2010 * \author Vernkin Chen */ #include <ilplib.hpp> #include <string> #include <util/ustring/UString.h> #include "la_bin_test_def.h" using namespace std; using namespace la; using namespace izenelib::util; void testTokenizer() { Tokenizer tokenizer; string input; do { cout << "Input ('x' to exit): "; getline( cin, input ); if( input == "x" || input == "X" ) break; UString ustr( input, IO_ENCODING ); { TermList specialTerms; TermList primTerms; cout << "-------------- tokenize( query, specialTerms, primTerms ) ---------------" << endl; tokenizer.tokenize(ustr, specialTerms, primTerms ); cout << "1. SPECIAL TERMS" << endl; printTermList( specialTerms ); cout << "2. Primary TERMS" << endl; printTermList( primTerms ); } { TermList rawTerms; cout << "-------------- tokenizeWhite( query, rawTerms ) ---------------" << endl; tokenizer.tokenizeWhite(ustr, rawTerms ); printTermList( rawTerms ); } { TermList primTerms; cout << "-------------- tokenize( query, primTerms ) ---------------" << endl; tokenizer.tokenize(ustr, primTerms ); printTermList( primTerms ); } } while( true ); } void printUsage() { cout << "Usage: ./t_LA [tok | char | cn | en | kr | multi | ngram | matrix | token(token analyzer) | none(empty analyzer)]" << endl; } boost::shared_ptr<Analyzer> getCMAAnalyzer() { ChineseAnalyzer* cana = new ChineseAnalyzer( getCmaKnowledgePath() ); cana->setLabelMode(); cana->setAnalysisType(ChineseAnalyzer::minimum_match); boost::shared_ptr<Analyzer> cbana( cana ); return cbana; } boost::shared_ptr<Analyzer> getKMAAnalyzer() { KoreanAnalyzer* kana = new KoreanAnalyzer( getKmaKnowledgePath() ); kana->setLabelMode(); boost::shared_ptr<Analyzer> kbana( kana ); return kbana; } int main( int argc, char** argv ) { if( argc < 2 ) { printUsage(); exit(1); } string type = argv[1]; if( type == "tok" ) { testTokenizer(); exit(0); } LA la; boost::shared_ptr<Analyzer> analyzer; bool extractSynonym = false; if( type == "char" ) { cout << "CharAnalyzer Addition Params: [all | part] [tolowcase]" << endl; CharAnalyzer* ana = new CharAnalyzer; for( int i = 2; i < argc; ++i ) { string arg = argv[i]; if( arg == "all" ) ana->setSeparateAll(true); else if( arg == "part" ) ana->setSeparateAll(false); else if( arg == "tolowcase" ) ana->setCaseSensitive(false); else cerr << "Invalid Parameter: " << arg << endl; } analyzer.reset( ana ); } else if( type == "cn" ) { cout << "ChineseAnalyzer Addition Params: [max | min | mmm | min_u] [label | index | stop | synonym | inner]" << endl; ChineseAnalyzer* ana = new ChineseAnalyzer( getCmaKnowledgePath() ); ana->setLabelMode(); ana->setCaseSensitive(false); ana->setAnalysisType(ChineseAnalyzer::minimum_match); for( int i = 2; i < argc; ++i ) { string arg = argv[i]; if( arg == "max" ) ana->setAnalysisType(ChineseAnalyzer::maximum_match); else if( arg == "min" ) ana->setAnalysisType(ChineseAnalyzer::minimum_match); else if( arg == "min_u" ) ana->setAnalysisType(ChineseAnalyzer::minimum_match_with_unigram); else if( arg == "mmm" ) ana->setAnalysisType(ChineseAnalyzer::maximum_entropy); else if( arg == "label" ) ana->setLabelMode(); else if( arg == "index" ) ana->setIndexMode(); else if( arg == "stop") ana->setRemoveStopwords(); else if( arg == "synonym") { extractSynonym = true; //ana->setExtractSynonym(true); } else if( arg == "inner") { ChineseAnalyzer* inner_ana = new ChineseAnalyzer( getCmaKnowledgePath() ); inner_ana->setLabelMode(); inner_ana->setCaseSensitive(false); inner_ana->setAnalysisType(ChineseAnalyzer::minimum_match_no_overlap); inner_ana->setExtractSynonym(false); boost::shared_ptr<Analyzer> analyzer(inner_ana); ana->setInnerAnalyzer(analyzer); } else cerr << "Invalid Parameter: " << arg << endl; } analyzer.reset( ana ); } else if( type == "en" ) { analyzer.reset( new EnglishAnalyzer ); } else if( type == "kr" ) { cout << "KoreanAnalyzer Addition Params: [label | index]" << endl; KoreanAnalyzer* ana = new KoreanAnalyzer( getKmaKnowledgePath() ); ana->setLabelMode(); for( int i = 2; i < argc; ++i ) { string arg = argv[i]; if( arg == "label" ) ana->setLabelMode(); else if( arg == "index" ) ana->setIndexMode(); else cerr << "Invalid Parameter: " << arg << endl; } analyzer.reset( ana ); } else if( type == "multi" ) { ChineseAnalyzer* cana = new ChineseAnalyzer( getCmaKnowledgePath() ); cana->setLabelMode(); cana->setAnalysisType(ChineseAnalyzer::minimum_match); boost::shared_ptr<Analyzer> cbana( cana ); KoreanAnalyzer* kana = new KoreanAnalyzer( getKmaKnowledgePath() ); kana->setLabelMode(); boost::shared_ptr<Analyzer> kbana( kana ); EnglishAnalyzer* eana = new EnglishAnalyzer; boost::shared_ptr<Analyzer> ebana( eana ); MultiLanguageAnalyzer* mana = new MultiLanguageAnalyzer; mana->setDefaultAnalyzer( kbana ); mana->setAnalyzer( MultiLanguageAnalyzer::CHINESE, cbana ); mana->setAnalyzer( MultiLanguageAnalyzer::ENGLISH, ebana ); analyzer.reset( mana ); } else if( type == "ngram" ) { cout << "NGramAnalyzer Addition Params: min max flag" << endl; int min = 2; int max = 3; if( argc > 2 ) min = atoi( argv[2] ); if( argc > 3 ) max = atoi( argv[3] ); if( min < 1 ) min = 2; if( max < min ) max = min + 1; unsigned int apartFlag = 0; if( argc > 4 ) apartFlag = (unsigned int)atoi( argv[4] ); cout << "[NGramAnalyzer] min = " << min << ", max = " << max << ", apartFlag = " << hex << apartFlag << endl; analyzer.reset( new NGramAnalyzer( 2, 3, 1024000, apartFlag ) ); } else if( type == "matrix" ) { analyzer.reset( new MatrixAnalyzer( true, true) ); } else if( type == "token" ) { analyzer.reset( new TokenAnalyzer ); } else if( type == "none" ) { // do nothing } else { cerr << "Unknown analyzer type: " << type << endl; exit(1); } bool toHalfWidthString = false; for( int i = 2; i < argc; ++i ) { string arg = argv[i]; if (arg == "half-width") { toHalfWidthString = true; } } la.setAnalyzer( analyzer ); string input; do { cout << "Input ('x' to exit): "; getline( cin, input ); if( input == "x" || input == "X" ) break; UString ustr( input, IO_ENCODING ); if ( toHalfWidthString ) { la::convertFull2HalfWidth(ustr); string str; ustr.convertString(str, UString::UTF_8); cout << "Input (full-with chars are converted to half-with): " << str << endl; } { TermList termList; cout << "-------------- process( query, termList ) ---------------" << endl; la.process( ustr, termList ); printTermList( termList ); cout << "-------------- toExpandedString ---------------" << endl; UString exp = toExpandedString(termList); exp.displayStringInfo(UString::UTF_8, cout); cout << endl; if (extractSynonym) { cout << "============== process with synonym =====================" << endl; termList.clear(); la.processSynonym( ustr, termList); printTermList( termList ); cout << "============== toExpandedString ================" << endl; UString exp = toExpandedString(termList); exp.displayStringInfo(UString::UTF_8, cout); cout << endl; } } } while( true ); return 0; } <commit_msg>initialize language identifier in t_LACMD<commit_after>/** * \file t_LA.cpp * \brief * \date Oct 13, 2010 * \author Vernkin Chen */ #include <ilplib.hpp> #include <string> #include <util/ustring/UString.h> #include "la_bin_test_def.h" using namespace std; using namespace la; using namespace izenelib::util; void testTokenizer() { Tokenizer tokenizer; string input; do { cout << "Input ('x' to exit): "; getline( cin, input ); if( input == "x" || input == "X" ) break; UString ustr( input, IO_ENCODING ); { TermList specialTerms; TermList primTerms; cout << "-------------- tokenize( query, specialTerms, primTerms ) ---------------" << endl; tokenizer.tokenize(ustr, specialTerms, primTerms ); cout << "1. SPECIAL TERMS" << endl; printTermList( specialTerms ); cout << "2. Primary TERMS" << endl; printTermList( primTerms ); } { TermList rawTerms; cout << "-------------- tokenizeWhite( query, rawTerms ) ---------------" << endl; tokenizer.tokenizeWhite(ustr, rawTerms ); printTermList( rawTerms ); } { TermList primTerms; cout << "-------------- tokenize( query, primTerms ) ---------------" << endl; tokenizer.tokenize(ustr, primTerms ); printTermList( primTerms ); } } while( true ); } void printUsage() { cout << "Usage: ./t_LA [tok | char | cn | en | kr | multi | ngram | matrix | token(token analyzer) | none(empty analyzer)]" << endl; } boost::shared_ptr<Analyzer> getCMAAnalyzer() { ChineseAnalyzer* cana = new ChineseAnalyzer( getCmaKnowledgePath() ); cana->setLabelMode(); cana->setAnalysisType(ChineseAnalyzer::minimum_match); boost::shared_ptr<Analyzer> cbana( cana ); return cbana; } boost::shared_ptr<Analyzer> getKMAAnalyzer() { KoreanAnalyzer* kana = new KoreanAnalyzer( getKmaKnowledgePath() ); kana->setLabelMode(); boost::shared_ptr<Analyzer> kbana( kana ); return kbana; } int main( int argc, char** argv ) { if( argc < 2 ) { printUsage(); exit(1); } string type = argv[1]; if( type == "tok" ) { testTokenizer(); exit(0); } LA la; boost::shared_ptr<Analyzer> analyzer; bool extractSynonym = false; if( type == "char" ) { cout << "CharAnalyzer Addition Params: [all | part] [tolowcase]" << endl; CharAnalyzer* ana = new CharAnalyzer; for( int i = 2; i < argc; ++i ) { string arg = argv[i]; if( arg == "all" ) ana->setSeparateAll(true); else if( arg == "part" ) ana->setSeparateAll(false); else if( arg == "tolowcase" ) ana->setCaseSensitive(false); else cerr << "Invalid Parameter: " << arg << endl; } analyzer.reset( ana ); } else if( type == "cn" ) { cout << "ChineseAnalyzer Addition Params: [max | min | mmm | min_u] [label | index | stop | synonym | inner]" << endl; ChineseAnalyzer* ana = new ChineseAnalyzer( getCmaKnowledgePath() ); ana->setLabelMode(); ana->setCaseSensitive(false); ana->setAnalysisType(ChineseAnalyzer::minimum_match); for( int i = 2; i < argc; ++i ) { string arg = argv[i]; if( arg == "max" ) ana->setAnalysisType(ChineseAnalyzer::maximum_match); else if( arg == "min" ) ana->setAnalysisType(ChineseAnalyzer::minimum_match); else if( arg == "min_u" ) ana->setAnalysisType(ChineseAnalyzer::minimum_match_with_unigram); else if( arg == "mmm" ) ana->setAnalysisType(ChineseAnalyzer::maximum_entropy); else if( arg == "label" ) ana->setLabelMode(); else if( arg == "index" ) ana->setIndexMode(); else if( arg == "stop") ana->setRemoveStopwords(); else if( arg == "synonym") { extractSynonym = true; //ana->setExtractSynonym(true); } else if( arg == "inner") { ChineseAnalyzer* inner_ana = new ChineseAnalyzer( getCmaKnowledgePath() ); inner_ana->setLabelMode(); inner_ana->setCaseSensitive(false); inner_ana->setAnalysisType(ChineseAnalyzer::minimum_match_no_overlap); inner_ana->setExtractSynonym(false); boost::shared_ptr<Analyzer> analyzer(inner_ana); ana->setInnerAnalyzer(analyzer); } else cerr << "Invalid Parameter: " << arg << endl; } analyzer.reset( ana ); } else if( type == "en" ) { analyzer.reset( new EnglishAnalyzer ); } else if( type == "kr" ) { cout << "KoreanAnalyzer Addition Params: [label | index]" << endl; KoreanAnalyzer* ana = new KoreanAnalyzer( getKmaKnowledgePath() ); ana->setLabelMode(); for( int i = 2; i < argc; ++i ) { string arg = argv[i]; if( arg == "label" ) ana->setLabelMode(); else if( arg == "index" ) ana->setIndexMode(); else cerr << "Invalid Parameter: " << arg << endl; } analyzer.reset( ana ); } else if( type == "multi" ) { ChineseAnalyzer* cana = new ChineseAnalyzer( getCmaKnowledgePath() ); cana->setLabelMode(); cana->setAnalysisType(ChineseAnalyzer::minimum_match); boost::shared_ptr<Analyzer> cbana( cana ); KoreanAnalyzer* kana = new KoreanAnalyzer( getKmaKnowledgePath() ); kana->setLabelMode(); boost::shared_ptr<Analyzer> kbana( kana ); EnglishAnalyzer* eana = new EnglishAnalyzer; boost::shared_ptr<Analyzer> ebana( eana ); MultiLanguageAnalyzer* mana = new MultiLanguageAnalyzer; mana->setDefaultAnalyzer( kbana ); mana->setAnalyzer( MultiLanguageAnalyzer::CHINESE, cbana ); mana->setAnalyzer( MultiLanguageAnalyzer::ENGLISH, ebana ); ilplib::langid::Factory* langIdFactory = ilplib::langid::Factory::instance(); MultiLanguageAnalyzer::langIdAnalyzer_ = langIdFactory->createAnalyzer(); ilplib::langid::Knowledge* langIdKnowledge_ = langIdFactory->createKnowledge(); langIdKnowledge_->loadEncodingModel("../db/langid/model/encoding.bin"); langIdKnowledge_->loadLanguageModel("../db/langid/model/language.bin"); MultiLanguageAnalyzer::langIdAnalyzer_->setKnowledge(langIdKnowledge_); analyzer.reset( mana ); } else if( type == "ngram" ) { cout << "NGramAnalyzer Addition Params: min max flag" << endl; int min = 2; int max = 3; if( argc > 2 ) min = atoi( argv[2] ); if( argc > 3 ) max = atoi( argv[3] ); if( min < 1 ) min = 2; if( max < min ) max = min + 1; unsigned int apartFlag = 0; if( argc > 4 ) apartFlag = (unsigned int)atoi( argv[4] ); cout << "[NGramAnalyzer] min = " << min << ", max = " << max << ", apartFlag = " << hex << apartFlag << endl; analyzer.reset( new NGramAnalyzer( 2, 3, 1024000, apartFlag ) ); } else if( type == "matrix" ) { analyzer.reset( new MatrixAnalyzer( true, true) ); } else if( type == "token" ) { analyzer.reset( new TokenAnalyzer ); } else if( type == "none" ) { // do nothing } else { cerr << "Unknown analyzer type: " << type << endl; exit(1); } bool toHalfWidthString = false; for( int i = 2; i < argc; ++i ) { string arg = argv[i]; if (arg == "half-width") { toHalfWidthString = true; } } la.setAnalyzer( analyzer ); string input; do { cout << "Input ('x' to exit): "; getline( cin, input ); if( input == "x" || input == "X" ) break; UString ustr( input, IO_ENCODING ); if ( toHalfWidthString ) { la::convertFull2HalfWidth(ustr); string str; ustr.convertString(str, UString::UTF_8); cout << "Input (full-with chars are converted to half-with): " << str << endl; } { TermList termList; cout << "-------------- process( query, termList ) ---------------" << endl; la.process( ustr, termList ); printTermList( termList ); cout << "-------------- toExpandedString ---------------" << endl; UString exp = toExpandedString(termList); exp.displayStringInfo(UString::UTF_8, cout); cout << endl; if (extractSynonym) { cout << "============== process with synonym =====================" << endl; termList.clear(); la.processSynonym( ustr, termList); printTermList( termList ); cout << "============== toExpandedString ================" << endl; UString exp = toExpandedString(termList); exp.displayStringInfo(UString::UTF_8, cout); cout << endl; } } } while( true ); return 0; } <|endoftext|>
<commit_before>// Copyright (C) 2016 Elviss Strazdins // This file is part of the Ouzel engine. #include <cstdarg> #include <random> #include "core/CompileConfig.h" #if OUZEL_PLATFORM_IOS || OUZEL_PLATFORM_TVOS #include <sys/syslog.h> #endif #if OUZEL_PLATFORM_WINDOWS #define NOMINMAX #include <windows.h> #include <strsafe.h> #endif #if OUZEL_PLATFORM_ANDROID #include <android/log.h> #endif #include "Utils.h" namespace ouzel { #if OUZEL_PLATFORM_ANDROID && OUZEL_SUPPORTS_NEON_CHECK AnrdoidNEONChecker anrdoidNEONChecker; #endif static char TEMP_BUFFER[1024]; #ifdef DEBUG static LogLevel logLevel = LOG_LEVEL_VERBOSE; #else static LogLevel logLevel = LOG_LEVEL_INFO; #endif void setLogLevel(LogLevel level) { logLevel = level; } void log(LogLevel level, const char* format, ...) { if (level <= logLevel) { va_list list; va_start(list, format); vsprintf(TEMP_BUFFER, format, list); va_end(list); #if OUZEL_PLATFORM_MACOS || OUZEL_PLATFORM_LINUX || OUZEL_PLATFORM_RASPBIAN || OUZEL_PLATFORM_EMSCRIPTEN printf("%s\n", TEMP_BUFFER); #elif OUZEL_PLATFORM_IOS || OUZEL_PLATFORM_TVOS syslog(LOG_WARNING, "%s", TEMP_BUFFER); printf("%s\n", TEMP_BUFFER); #elif OUZEL_PLATFORM_WINDOWS wchar_t szBuffer[MAX_PATH]; MultiByteToWideChar(CP_UTF8, 0, TEMP_BUFFER, -1, szBuffer, MAX_PATH); StringCchCat(szBuffer, sizeof(szBuffer), L"\n"); OutputDebugString(szBuffer); #elif OUZEL_PLATFORM_ANDROID __android_log_print(ANDROID_LOG_DEBUG, "Ouzel", "%s", TEMP_BUFFER); #endif } } static std::mt19937 engine(std::random_device{}()); uint32_t random(uint32_t min, uint32_t max) { return std::uniform_int_distribution<uint32_t>{min, max}(engine); } float randomf(float min, float max) { float diff = max - min; float rand = static_cast<float>(engine()) / engine.max(); return rand * diff + min; } } <commit_msg>Implement logging for Emscripten<commit_after>// Copyright (C) 2016 Elviss Strazdins // This file is part of the Ouzel engine. #include <cstdarg> #include <random> #include "core/CompileConfig.h" #if OUZEL_PLATFORM_IOS || OUZEL_PLATFORM_TVOS #include <sys/syslog.h> #endif #if OUZEL_PLATFORM_WINDOWS #define NOMINMAX #include <windows.h> #include <strsafe.h> #endif #if OUZEL_PLATFORM_ANDROID #include <android/log.h> #endif #if OUZEL_PLATFORM_EMSCRIPTEN #include <emscripten.h> #endif #include "Utils.h" namespace ouzel { #if OUZEL_PLATFORM_ANDROID && OUZEL_SUPPORTS_NEON_CHECK AnrdoidNEONChecker anrdoidNEONChecker; #endif static char TEMP_BUFFER[1024]; #ifdef DEBUG static LogLevel logLevel = LOG_LEVEL_VERBOSE; #else static LogLevel logLevel = LOG_LEVEL_INFO; #endif void setLogLevel(LogLevel level) { logLevel = level; } void log(LogLevel level, const char* format, ...) { if (level <= logLevel) { va_list list; va_start(list, format); vsprintf(TEMP_BUFFER, format, list); va_end(list); #if OUZEL_PLATFORM_MACOS || OUZEL_PLATFORM_LINUX || OUZEL_PLATFORM_RASPBIAN printf("%s\n", TEMP_BUFFER); #elif OUZEL_PLATFORM_IOS || OUZEL_PLATFORM_TVOS syslog(LOG_WARNING, "%s", TEMP_BUFFER); printf("%s\n", TEMP_BUFFER); #elif OUZEL_PLATFORM_WINDOWS wchar_t szBuffer[MAX_PATH]; MultiByteToWideChar(CP_UTF8, 0, TEMP_BUFFER, -1, szBuffer, MAX_PATH); StringCchCat(szBuffer, sizeof(szBuffer), L"\n"); OutputDebugString(szBuffer); #elif OUZEL_PLATFORM_ANDROID __android_log_print(ANDROID_LOG_DEBUG, "Ouzel", "%s", TEMP_BUFFER); #elif OUZEL_PLATFORM_EMSCRIPTEN int flags = EM_LOG_CONSOLE; if (level == LOG_LEVEL_ERROR) flags |= EM_LOG_ERROR; else if (level == LOG_LEVEL_WARNING) flags |= EM_LOG_WARN; emscripten_log(level, "%s", TEMP_BUFFER); #endif } } static std::mt19937 engine(std::random_device{}()); uint32_t random(uint32_t min, uint32_t max) { return std::uniform_int_distribution<uint32_t>{min, max}(engine); } float randomf(float min, float max) { float diff = max - min; float rand = static_cast<float>(engine()) / engine.max(); return rand * diff + min; } } <|endoftext|>
<commit_before>/* * Copyright (c) 2015 Cryptonomex, Inc., and contributors. * * The MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <graphene/chain/transfer_evaluator.hpp> #include <graphene/chain/account_object.hpp> #include <graphene/chain/exceptions.hpp> #include <graphene/chain/hardfork.hpp> #include <graphene/chain/is_authorized_asset.hpp> namespace graphene { namespace chain { void_result transfer_evaluator::do_evaluate( const transfer_operation& op ) { try { const database& d = db(); const account_object& from_account = op.from(d); const account_object& to_account = op.to(d); const asset_object& asset_type = op.amount.asset_id(d); const asset_object& fee_asset_type = op.fee.asset_id(d); try { GRAPHENE_ASSERT( is_authorized_asset( d, from_account, asset_type ), transfer_from_account_not_whitelisted, "'from' account ${from} is not whitelisted for asset ${asset}", ("from",op.from) ("asset",op.amount.asset_id) ); GRAPHENE_ASSERT( is_authorized_asset( d, to_account, asset_type ), transfer_to_account_not_whitelisted, "'to' account ${to} is not whitelisted for asset ${asset}", ("to",op.to) ("asset",op.amount.asset_id) ); if( d.head_block_time() <= HARDFORK_419_TIME ) { FC_ASSERT( is_authorized_asset( d, from_account, asset_type ) ); } // the above becomes no-op after hardfork because this check will then be performed in evaluator if( asset_type.is_transfer_restricted() ) { GRAPHENE_ASSERT( from_account.id == asset_type.issuer || to_account.id == asset_type.issuer, transfer_restricted_transfer_asset, "Asset {asset} has transfer_restricted flag enabled", ("asset", op.amount.asset_id) ); } bool insufficient_balance = d.get_balance( from_account, asset_type ).amount >= op.amount.amount; FC_ASSERT( insufficient_balance, "Insufficient Balance: ${balance}, unable to transfer '${total_transfer}' from account '${a}' to '${t}'", ("a",from_account.name)("t",to_account.name)("total_transfer",d.to_pretty_string(op.amount))("balance",d.to_pretty_string(d.get_balance(from_account, asset_type))) ); return void_result(); } FC_RETHROW_EXCEPTIONS( error, "Unable to transfer ${a} from ${f} to ${t}", ("a",d.to_pretty_string(op.amount))("f",op.from(d).name)("t",op.to(d).name) ); } FC_CAPTURE_AND_RETHROW( (op) ) } void_result transfer_evaluator::do_apply( const transfer_operation& o ) { try { db().adjust_balance( o.from, -o.amount ); db().adjust_balance( o.to, o.amount ); return void_result(); } FC_CAPTURE_AND_RETHROW( (o) ) } void_result override_transfer_evaluator::do_evaluate( const override_transfer_operation& op ) { try { const database& d = db(); const asset_object& asset_type = op.amount.asset_id(d); GRAPHENE_ASSERT( asset_type.can_override(), override_transfer_not_permitted, "override_transfer not permitted for asset ${asset}", ("asset", op.amount.asset_id) ); FC_ASSERT( asset_type.issuer == op.issuer ); const account_object& from_account = op.from(d); const account_object& to_account = op.to(d); const asset_object& fee_asset_type = op.fee.asset_id(d); FC_ASSERT( is_authorized_asset( d, to_account, asset_type ) ); FC_ASSERT( is_authorized_asset( d, from_account, asset_type ) ); if( d.head_block_time() <= HARDFORK_419_TIME ) { FC_ASSERT( is_authorized_asset( d, from_account, asset_type ) ); } // the above becomes no-op after hardfork because this check will then be performed in evaluator FC_ASSERT( d.get_balance( from_account, asset_type ).amount >= op.amount.amount, "", ("total_transfer",op.amount)("balance",d.get_balance(from_account, asset_type).amount) ); return void_result(); } FC_CAPTURE_AND_RETHROW( (op) ) } void_result override_transfer_evaluator::do_apply( const override_transfer_operation& o ) { try { db().adjust_balance( o.from, -o.amount ); db().adjust_balance( o.to, o.amount ); return void_result(); } FC_CAPTURE_AND_RETHROW( (o) ) } } } // graphene::chain <commit_msg>transfer_evaluator.cpp: Remove unused variable and redundant check #566<commit_after>/* * Copyright (c) 2015 Cryptonomex, Inc., and contributors. * * The MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <graphene/chain/transfer_evaluator.hpp> #include <graphene/chain/account_object.hpp> #include <graphene/chain/exceptions.hpp> #include <graphene/chain/hardfork.hpp> #include <graphene/chain/is_authorized_asset.hpp> namespace graphene { namespace chain { void_result transfer_evaluator::do_evaluate( const transfer_operation& op ) { try { const database& d = db(); const account_object& from_account = op.from(d); const account_object& to_account = op.to(d); const asset_object& asset_type = op.amount.asset_id(d); try { GRAPHENE_ASSERT( is_authorized_asset( d, from_account, asset_type ), transfer_from_account_not_whitelisted, "'from' account ${from} is not whitelisted for asset ${asset}", ("from",op.from) ("asset",op.amount.asset_id) ); GRAPHENE_ASSERT( is_authorized_asset( d, to_account, asset_type ), transfer_to_account_not_whitelisted, "'to' account ${to} is not whitelisted for asset ${asset}", ("to",op.to) ("asset",op.amount.asset_id) ); if( asset_type.is_transfer_restricted() ) { GRAPHENE_ASSERT( from_account.id == asset_type.issuer || to_account.id == asset_type.issuer, transfer_restricted_transfer_asset, "Asset {asset} has transfer_restricted flag enabled", ("asset", op.amount.asset_id) ); } bool insufficient_balance = d.get_balance( from_account, asset_type ).amount >= op.amount.amount; FC_ASSERT( insufficient_balance, "Insufficient Balance: ${balance}, unable to transfer '${total_transfer}' from account '${a}' to '${t}'", ("a",from_account.name)("t",to_account.name)("total_transfer",d.to_pretty_string(op.amount))("balance",d.to_pretty_string(d.get_balance(from_account, asset_type))) ); return void_result(); } FC_RETHROW_EXCEPTIONS( error, "Unable to transfer ${a} from ${f} to ${t}", ("a",d.to_pretty_string(op.amount))("f",op.from(d).name)("t",op.to(d).name) ); } FC_CAPTURE_AND_RETHROW( (op) ) } void_result transfer_evaluator::do_apply( const transfer_operation& o ) { try { db().adjust_balance( o.from, -o.amount ); db().adjust_balance( o.to, o.amount ); return void_result(); } FC_CAPTURE_AND_RETHROW( (o) ) } void_result override_transfer_evaluator::do_evaluate( const override_transfer_operation& op ) { try { const database& d = db(); const asset_object& asset_type = op.amount.asset_id(d); GRAPHENE_ASSERT( asset_type.can_override(), override_transfer_not_permitted, "override_transfer not permitted for asset ${asset}", ("asset", op.amount.asset_id) ); FC_ASSERT( asset_type.issuer == op.issuer ); const account_object& from_account = op.from(d); const account_object& to_account = op.to(d); FC_ASSERT( is_authorized_asset( d, to_account, asset_type ) ); FC_ASSERT( is_authorized_asset( d, from_account, asset_type ) ); if( d.head_block_time() <= HARDFORK_419_TIME ) { FC_ASSERT( is_authorized_asset( d, from_account, asset_type ) ); } // the above becomes no-op after hardfork because this check will then be performed in evaluator FC_ASSERT( d.get_balance( from_account, asset_type ).amount >= op.amount.amount, "", ("total_transfer",op.amount)("balance",d.get_balance(from_account, asset_type).amount) ); return void_result(); } FC_CAPTURE_AND_RETHROW( (op) ) } void_result override_transfer_evaluator::do_apply( const override_transfer_operation& o ) { try { db().adjust_balance( o.from, -o.amount ); db().adjust_balance( o.to, o.amount ); return void_result(); } FC_CAPTURE_AND_RETHROW( (o) ) } } } // graphene::chain <|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // voice.cc //------------------------------------------------------------------------------ #include "Pre.h" #include "voice.h" #include "Core/Assert.h" #include "Synth/Core/synth.h" #include <cmath> #include <cstdlib> namespace Oryol { namespace Synth { //------------------------------------------------------------------------------ voice::voice() : isValid(false) { for (int i = 0; i < synth::NumTracks; i++) { this->trackOpBegin[i] = nullptr; this->trackOpEnd[i] = nullptr; } } //------------------------------------------------------------------------------ voice::~voice() { o_assert_dbg(!this->isValid); } //------------------------------------------------------------------------------ void voice::Setup(const SynthSetup& setupAttrs) { o_assert_dbg(!this->isValid); this->isValid = true; } //------------------------------------------------------------------------------ void voice::Discard() { o_assert_dbg(this->isValid); this->isValid = false; for (auto& track : this->tracks) { track.DiscardAllOps(); } } //------------------------------------------------------------------------------ void voice::AddOp(int32 track, const Op& op) { o_assert_dbg(this->isValid); o_assert_range_dbg(track, synth::NumTracks); this->tracks[track].AddOp(op); } //------------------------------------------------------------------------------ void voice::Synthesize(int32 startTick, void* buffer, int32 bufNumBytes) { o_assert_dbg(this->isValid); o_assert(synth::BufferSize == bufNumBytes); // get all ops overlapping the current buffer range const int32 endTick = startTick + synth::BufferNumSamples; for (int i = 0; i < synth::NumTracks; i++) { this->tracks[i].GatherOps(startTick, endTick, this->trackOpBegin[i], this->trackOpEnd[i]); } // the sample tick range covered by the buffer int16* samplePtr = (int16*) buffer; // for each sample... for (int32 curTick = startTick; curTick < endTick; curTick++) { float32 voiceSample = 1.0f; for (int trackIndex = 0; trackIndex < synth::NumTracks; trackIndex++) { const Op* opBegin = this->trackOpBegin[trackIndex]; const Op* opEnd = this->trackOpEnd[trackIndex]; float32 trackSample = 1.0f; for (const Op* op = opBegin; op < opEnd; op++) { if ((curTick >= op->startTick) && (curTick < op->endTick)) { // compute current sample float32 s = this->sample(curTick, op); // cross-fade with previous sample? if (curTick < (op->startTick + op->FadeInTicks)) { float32 t = float32(curTick - op->startTick) / float32(op->FadeInTicks); trackSample = (s * t) + (trackSample * (1.0f - t)); } else { trackSample = s; } } } voiceSample *= trackSample; } *samplePtr++ = int16(voiceSample * 32767.0f); } } //------------------------------------------------------------------------------ float32 voice::sample(int32 curTick, const Op* op) { // shortcut for const output if (Op::Const == op->Code) { return op->Amplitude + op->Bias; } else if (Op::Nop == op->Code) { return 0.0f; } // generate wave form int32 tick = (curTick - op->startTick) % op->freqLoopTicks; float32 t = float32(tick) / float32(op->freqLoopTicks); // t now 0..1 position in wave form if (Op::Sine == op->Code) { // sine wave #if ORYOL_ANDROID return (std::sin(t * M_PI * 2.0f) * op->Amplitude) + op->Bias; #else return (std::sinf(t * M_PI * 2.0f) * op->Amplitude) + op->Bias; #endif } else if (Op::Square == op->Code) { // square wave with Pulse as pulse with if (t <= op->Pulse) { return op->Amplitude + op->Bias; } else { return -op->Amplitude + op->Bias; } } else if (Op::Triangle == op->Code) { // triangle with shifted triangle top position // Pulse == 0.0: sawtooth // Pulse == 0.5: classic triangle // Pulse == 1.0: inverse sawtooth float32 s; if (t < op->Pulse) { s = t / op->Pulse; } else { s = 1.0f - ((t - op->Pulse) / (1.0f - op->Pulse)); } return (((s * 2.0f) - 1.0f) * op->Amplitude) + op->Bias; } else { // noise // FIXME: replace with perlin or simplex noise // in order to get frequency output return float32((std::rand() & 0xFFFF) - 0x7FFF) / float32(0x8000); } } } // namespace Synth } // namespace Oryol <commit_msg>Linux compile fix<commit_after>//------------------------------------------------------------------------------ // voice.cc //------------------------------------------------------------------------------ #include "Pre.h" #include "voice.h" #include "Core/Assert.h" #include "Synth/Core/synth.h" #include <cmath> #include <cstdlib> namespace Oryol { namespace Synth { //------------------------------------------------------------------------------ voice::voice() : isValid(false) { for (int i = 0; i < synth::NumTracks; i++) { this->trackOpBegin[i] = nullptr; this->trackOpEnd[i] = nullptr; } } //------------------------------------------------------------------------------ voice::~voice() { o_assert_dbg(!this->isValid); } //------------------------------------------------------------------------------ void voice::Setup(const SynthSetup& setupAttrs) { o_assert_dbg(!this->isValid); this->isValid = true; } //------------------------------------------------------------------------------ void voice::Discard() { o_assert_dbg(this->isValid); this->isValid = false; for (auto& track : this->tracks) { track.DiscardAllOps(); } } //------------------------------------------------------------------------------ void voice::AddOp(int32 track, const Op& op) { o_assert_dbg(this->isValid); o_assert_range_dbg(track, synth::NumTracks); this->tracks[track].AddOp(op); } //------------------------------------------------------------------------------ void voice::Synthesize(int32 startTick, void* buffer, int32 bufNumBytes) { o_assert_dbg(this->isValid); o_assert(synth::BufferSize == bufNumBytes); // get all ops overlapping the current buffer range const int32 endTick = startTick + synth::BufferNumSamples; for (int i = 0; i < synth::NumTracks; i++) { this->tracks[i].GatherOps(startTick, endTick, this->trackOpBegin[i], this->trackOpEnd[i]); } // the sample tick range covered by the buffer int16* samplePtr = (int16*) buffer; // for each sample... for (int32 curTick = startTick; curTick < endTick; curTick++) { float32 voiceSample = 1.0f; for (int trackIndex = 0; trackIndex < synth::NumTracks; trackIndex++) { const Op* opBegin = this->trackOpBegin[trackIndex]; const Op* opEnd = this->trackOpEnd[trackIndex]; float32 trackSample = 1.0f; for (const Op* op = opBegin; op < opEnd; op++) { if ((curTick >= op->startTick) && (curTick < op->endTick)) { // compute current sample float32 s = this->sample(curTick, op); // cross-fade with previous sample? if (curTick < (op->startTick + op->FadeInTicks)) { float32 t = float32(curTick - op->startTick) / float32(op->FadeInTicks); trackSample = (s * t) + (trackSample * (1.0f - t)); } else { trackSample = s; } } } voiceSample *= trackSample; } *samplePtr++ = int16(voiceSample * 32767.0f); } } //------------------------------------------------------------------------------ float32 voice::sample(int32 curTick, const Op* op) { // shortcut for const output if (Op::Const == op->Code) { return op->Amplitude + op->Bias; } else if (Op::Nop == op->Code) { return 0.0f; } // generate wave form int32 tick = (curTick - op->startTick) % op->freqLoopTicks; float32 t = float32(tick) / float32(op->freqLoopTicks); // t now 0..1 position in wave form if (Op::Sine == op->Code) { // sine wave #if ORYOL_ANDROID || ORYOL_LINUX return (std::sin(t * M_PI * 2.0f) * op->Amplitude) + op->Bias; #else return (std::sinf(t * M_PI * 2.0f) * op->Amplitude) + op->Bias; #endif } else if (Op::Square == op->Code) { // square wave with Pulse as pulse with if (t <= op->Pulse) { return op->Amplitude + op->Bias; } else { return -op->Amplitude + op->Bias; } } else if (Op::Triangle == op->Code) { // triangle with shifted triangle top position // Pulse == 0.0: sawtooth // Pulse == 0.5: classic triangle // Pulse == 1.0: inverse sawtooth float32 s; if (t < op->Pulse) { s = t / op->Pulse; } else { s = 1.0f - ((t - op->Pulse) / (1.0f - op->Pulse)); } return (((s * 2.0f) - 1.0f) * op->Amplitude) + op->Bias; } else { // noise // FIXME: replace with perlin or simplex noise // in order to get frequency output return float32((std::rand() & 0xFFFF) - 0x7FFF) / float32(0x8000); } } } // namespace Synth } // namespace Oryol <|endoftext|>
<commit_before>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1 * * (c) 2006-2011 MGH, INRIA, USTL, UJF, CNRS * * * * 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. * ******************************************************************************* * SOFA :: Modules * * * * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: contact@sofa-framework.org * ******************************************************************************/ // Author: Hadrien Courtecuisse // // Copyright: See COPYING file that comes with this distribution #include <sofa/component/linearsolver/SparsePARDISOSolver.h> #include <sofa/core/visual/VisualParams.h> #include <sofa/core/ObjectFactory.h> #include <iostream> #include "sofa/helper/system/thread/CTime.h" #include <sofa/core/objectmodel/BaseContext.h> #include <sofa/core/behavior/LinearSolver.h> #include <math.h> #include <sofa/helper/system/thread/CTime.h> #include <sofa/component/linearsolver/MatrixLinearSolver.inl> #include <sofa/component/linearsolver/CompressedRowSparseMatrix.inl> #include <sofa/helper/AdvancedTimer.h> #ifndef WIN32 #include <unistd.h> #else #include <windows.h> #endif #include <stdlib.h> /* Change this if your Fortran compiler does not append underscores. */ /* e.g. the AIX compiler: #define F77_FUNC(func) func */ #ifdef AIX #define F77_FUNC(func) func #else #define F77_FUNC(func) func ## _ #endif extern "C" { /* PARDISO prototype. */ extern int F77_FUNC(pardisoinit) (void *, int *, int *, int *, double *, int *); extern int F77_FUNC(pardiso) (void *, int *, int *, int *, int *, int *, double *, int *, int *, int *, int *, int *, int *, double *, double *, int *, double *); } // "C" namespace sofa { namespace component { namespace linearsolver { template<class TMatrix, class TVector> SparsePARDISOSolver<TMatrix,TVector>::SparsePARDISOSolverInvertData::SparsePARDISOSolverInvertData(int f_symmetric,std::ostream & sout,std::ostream & serr) : solver(NULL) , pardiso_initerr(1) , pardiso_mtype(0) , factorized(false) { factorized = false; pardiso_initerr = 0; std::cout << "FSYM: " << f_symmetric << std::endl; switch(f_symmetric) { case 0: pardiso_mtype = 11; break; // real and nonsymmetric case 1: pardiso_mtype = -2; break; // real and symmetric indefinite case 2: pardiso_mtype = 2; break; // real and symmetric positive definite case -1: pardiso_mtype = 1; break; // real and structurally symmetric default: pardiso_mtype = 11; break; // real and nonsymmetric } pardiso_iparm[0] = 0; int solver = 0; /* use sparse direct solver */ /* Numbers of processors, value of OMP_NUM_THREADS */ const char* var = getenv("OMP_NUM_THREADS"); if(var != NULL) pardiso_iparm[2] = atoi(var); else pardiso_iparm[2] = 1; sout << "Using " << pardiso_iparm[2] << " thread(s), set OMP_NUM_THREADS environment variable to change." << std::endl; F77_FUNC(pardisoinit) (pardiso_pt, &pardiso_mtype, &solver, pardiso_iparm, pardiso_dparm, &pardiso_initerr); switch(pardiso_initerr) { case 0: sout << "PARDISO: License check was successful" << std::endl; break; case -10: serr << "PARDISO: No license file found" << std::endl; break; case -11: serr << "PARDISO: License is expired" << std::endl; break; case -12: serr << "PARDISO: Wrong username or hostname" << std::endl; break; default: serr << "PARDISO: Unknown error " << pardiso_initerr << std::endl; break; } //if (data->pardiso_initerr) return; //if(var != NULL) // data->pardiso_iparm[2] = atoi(var); //else // data->pardiso_iparm[2] = 1; } template<class TMatrix, class TVector> SparsePARDISOSolver<TMatrix,TVector>::SparsePARDISOSolver() : f_symmetric( initData(&f_symmetric,1,"symmetric","0 = nonsymmetric arbitrary matrix, 1 = symmetric matrix, 2 = symmetric positive definite, -1 = structurally symmetric matrix") ) , f_verbose( initData(&f_verbose,false,"verbose","Dump system state at each iteration") ) , f_saveDataToFile( initData(&f_saveDataToFile, "saveDataToFile", "save matrix, RHS and solution vectors to file")) { } template<class TMatrix, class TVector> void SparsePARDISOSolver<TMatrix,TVector>::init() { numStep = 0; numPrevNZ = 0; numActNZ = 0; Inherit::init(); } template<class TMatrix, class TVector> SparsePARDISOSolver<TMatrix,TVector>::~SparsePARDISOSolver() { } template<class TMatrix, class TVector> int SparsePARDISOSolver<TMatrix,TVector>::callPardiso(SparsePARDISOSolverInvertData* data, int phase, Vector* vx, Vector* vb) { int maxfct = 1; // Maximum number of numerical factorizations int mnum = 1; // Which factorization to use int n = data->Mfiltered.rowSize(); double* a = NULL; int* ia = NULL; int* ja = NULL; int* perm = NULL; // User-specified permutation vector int nrhs = 0; // Number of right hand sides int msglvl = (f_verbose.getValue())?1:0; // Print statistical information double* b = NULL; double* x = NULL; int error = 0; if (phase > 0) { ia = (int *) &(data->Mfiltered.getRowBegin()[0]); ja = (int *) &(data->Mfiltered.getColsIndex()[0]); a = (double*) &(data->Mfiltered.getColsValue()[0]); numActNZ = ia[n]-1; if (f_saveDataToFile.getValue()) { std::ofstream f; char name[100]; sprintf(name, "spmatrix_PARD_%04d.txt", numStep); f.open(name); int rw = 0; for (int i = 0; i < ia[n]-1; i++) { if (ia[rw] == i+1) rw++; f << rw << " " << ja[i] << " " << a[i] << std::endl; } f.close(); sprintf(name, "compmatrix_PARD_%04d.txt", numStep); f.open(name); for (int i = 0; i <= n; i++) f << ia[i] << std::endl; for (int i = 0; i < ia[n]-1; i++) f << ja[i] << " " << a[i] << std::endl; f.close(); } if (vx) { nrhs = 1; x = vx->ptr(); b = vb->ptr(); } } sout << "Solver phase " << phase << "..." << sendl; sofa::helper::AdvancedTimer::stepBegin("PardisoRealSolving"); F77_FUNC(pardiso)(data->pardiso_pt, &maxfct, &mnum, &data->pardiso_mtype, &phase, &n, a, ia, ja, perm, &nrhs, data->pardiso_iparm, &msglvl, b, x, &error, data->pardiso_dparm); sofa::helper::AdvancedTimer::stepEnd("PardisoRealSolving"); const char* msg = NULL; switch(error) { case 0: break; case -1: msg="Input inconsistent"; break; case -2: msg="Not enough memory"; break; case -3: msg="Reordering problem"; break; case -4: msg="Zero pivot, numerical fact. or iterative refinement problem"; break; case -5: msg="Unclassified (internal) error"; break; case -6: msg="Preordering failed (matrix types 11, 13 only)"; break; case -7: msg="Diagonal matrix problem"; break; case -8: msg="32-bit integer overflow problem"; break; case -10: msg="No license file pardiso.lic found"; break; case -11: msg="License is expired"; break; case -12: msg="Wrong username or hostname"; break; case -100: msg="Reached maximum number of Krylov-subspace iteration in iterative solver"; break; case -101: msg="No sufficient convergence in Krylov-subspace iteration within 25 iterations"; break; case -102: msg="Error in Krylov-subspace iteration"; break; case -103: msg="Break-Down in Krylov-subspace iteration"; break; default: msg="Unknown error"; break; } if (msg) serr << "Solver phase " << phase << ": ERROR " << error << " : " << msg << sendl; return error; } template<class TMatrix, class TVector> void SparsePARDISOSolver<TMatrix,TVector>::invert(Matrix& M) { sofa::helper::AdvancedTimer::stepBegin("PardisoInvert"); if (f_saveDataToFile.getValue()) { std::cout << this->getName() << ": saving to " << numStep << std::endl; std::ofstream f; char name[100]; sprintf(name, "matrix_PARD_%04d.txt", numStep); f.open(name); f << M; f.close(); } M.compress(); SparsePARDISOSolverInvertData * data = (SparsePARDISOSolverInvertData *) getMatrixInvertData(&M); if (data->pardiso_initerr) return; data->Mfiltered.clear(); if (f_symmetric.getValue() > 0) { data->Mfiltered.copyUpperNonZeros(M); data->Mfiltered.fullDiagonal(); sout << "Filtered upper part of M, nnz = " << data->Mfiltered.getRowBegin().back() << sendl; } else if (f_symmetric.getValue() < 0) { data->Mfiltered.copyNonZeros(M); data->Mfiltered.fullDiagonal(); sout << "Filtered M, nnz = " << data->Mfiltered.getRowBegin().back() << sendl; } else { data->Mfiltered.copyNonZeros(M); data->Mfiltered.fullRows(); sout << "Filtered M, nnz = " << data->Mfiltered.getRowBegin().back() << sendl; } // Convert matrix from 0-based C-notation to Fortran 1-based notation. data->Mfiltered.shiftIndices(1); /* -------------------------------------------------------------------- */ /* .. Reordering and Symbolic Factorization. This step also allocates */ /* all memory that is necessary for the factorization. */ /* -------------------------------------------------------------------- */ //if (!data->factorized || numPrevNZ != numAtNZ || numStep < 10) { sout << "Analyzing the matrix" << std::endl; if (callPardiso(data, 11)) return; data->factorized = true; sout << "Reordering completed ..." << sendl; sout << "Number of nonzeros in factors = " << data->pardiso_iparm[17] << sendl; sout << "Number of factorization MFLOPS = " << data->pardiso_iparm[18] << sendl; numPrevNZ = numActNZ; } /* -------------------------------------------------------------------- */ /* .. Numerical factorization. */ /* -------------------------------------------------------------------- */ if (callPardiso(data, 22)) { data->factorized = false; return; } sout << "Factorization completed ..." << sendl; sofa::helper::AdvancedTimer::stepEnd("PardisoInvert"); } template<class TMatrix, class TVector> void SparsePARDISOSolver<TMatrix,TVector>::solve (Matrix& M, Vector& z, Vector& r) { if (f_saveDataToFile.getValue()){ std::ofstream f; char name[100]; sprintf(name, "rhs_PARD_%04d.txt", numStep); f.open(name); f << r; f.close(); } sofa::helper::AdvancedTimer::stepBegin("PardisoSolve"); SparsePARDISOSolverInvertData * data = (SparsePARDISOSolverInvertData *) getMatrixInvertData(&M); if (data->pardiso_initerr) return; if (!data->factorized) return; /* -------------------------------------------------------------------- */ /* .. Back substitution and iterative refinement. */ /* -------------------------------------------------------------------- */ data->pardiso_iparm[7] = 1; /* Max numbers of iterative refinement steps. */ if (callPardiso(data, 33, &z, &r)) return; sofa::helper::AdvancedTimer::stepEnd("PardisoSolve"); if (f_saveDataToFile.getValue()) { std::ofstream f; char name[100]; sprintf(name, "solution_PARD_%04d.txt", numStep); f.open(name); f << z; f.close(); } numStep++; } SOFA_DECL_CLASS(SparsePARDISOSolver) int SparsePARDISOSolverClass = core::RegisterObject("Direct linear solvers implemented with the PARDISO library") .add< SparsePARDISOSolver< CompressedRowSparseMatrix<double>,FullVector<double> > >() .add< SparsePARDISOSolver< CompressedRowSparseMatrix< defaulttype::Mat<3,3,double> >,FullVector<double> > >(true) .addAlias("PARDISOSolver") ; } // namespace linearsolver } // namespace component } // namespace sofa <commit_msg>r11035/sofa : push d866a2d..98a0918<commit_after>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1 * * (c) 2006-2011 MGH, INRIA, USTL, UJF, CNRS * * * * 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. * ******************************************************************************* * SOFA :: Modules * * * * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: contact@sofa-framework.org * ******************************************************************************/ // Author: Hadrien Courtecuisse // // Copyright: See COPYING file that comes with this distribution #include <sofa/component/linearsolver/SparsePARDISOSolver.h> #include <sofa/core/visual/VisualParams.h> #include <sofa/core/ObjectFactory.h> #include <iostream> #include "sofa/helper/system/thread/CTime.h" #include <sofa/core/objectmodel/BaseContext.h> #include <sofa/core/behavior/LinearSolver.h> #include <math.h> #include <sofa/helper/system/thread/CTime.h> #include <sofa/component/linearsolver/MatrixLinearSolver.inl> #include <sofa/component/linearsolver/CompressedRowSparseMatrix.inl> #include <sofa/helper/AdvancedTimer.h> #ifndef WIN32 #include <unistd.h> #else #include <windows.h> #endif #include <stdlib.h> /* Change this if your Fortran compiler does not append underscores. */ /* e.g. the AIX compiler: #define F77_FUNC(func) func */ #ifdef AIX #define F77_FUNC(func) func #else #define F77_FUNC(func) func ## _ #endif extern "C" { /* PARDISO prototype. */ extern int F77_FUNC(pardisoinit) (void *, int *, int *, int *, double *, int *); extern int F77_FUNC(pardiso) (void *, int *, int *, int *, int *, int *, double *, int *, int *, int *, int *, int *, int *, double *, double *, int *, double *); } // "C" namespace sofa { namespace component { namespace linearsolver { template<class TMatrix, class TVector> SparsePARDISOSolver<TMatrix,TVector>::SparsePARDISOSolverInvertData::SparsePARDISOSolverInvertData(int f_symmetric,std::ostream & sout,std::ostream & serr) : solver(NULL) , pardiso_initerr(1) , pardiso_mtype(0) , factorized(false) { factorized = false; pardiso_initerr = 0; std::cout << "FSYM: " << f_symmetric << std::endl; switch(f_symmetric) { case 0: pardiso_mtype = 11; break; // real and nonsymmetric case 1: pardiso_mtype = -2; break; // real and symmetric indefinite case 2: pardiso_mtype = 2; break; // real and symmetric positive definite case -1: pardiso_mtype = 1; break; // real and structurally symmetric default: pardiso_mtype = 11; break; // real and nonsymmetric } pardiso_iparm[0] = 0; int solver = 0; /* use sparse direct solver */ /* Numbers of processors, value of OMP_NUM_THREADS */ const char* var = getenv("OMP_NUM_THREADS"); if(var != NULL) pardiso_iparm[2] = atoi(var); else pardiso_iparm[2] = 1; sout << "Using " << pardiso_iparm[2] << " thread(s), set OMP_NUM_THREADS environment variable to change." << std::endl; F77_FUNC(pardisoinit) (pardiso_pt, &pardiso_mtype, &solver, pardiso_iparm, pardiso_dparm, &pardiso_initerr); switch(pardiso_initerr) { case 0: sout << "PARDISO: License check was successful" << std::endl; break; case -10: serr << "PARDISO: No license file found" << std::endl; break; case -11: serr << "PARDISO: License is expired" << std::endl; break; case -12: serr << "PARDISO: Wrong username or hostname" << std::endl; break; default: serr << "PARDISO: Unknown error " << pardiso_initerr << std::endl; break; } //if (data->pardiso_initerr) return; //if(var != NULL) // data->pardiso_iparm[2] = atoi(var); //else // data->pardiso_iparm[2] = 1; } template<class TMatrix, class TVector> SparsePARDISOSolver<TMatrix,TVector>::SparsePARDISOSolver() : f_symmetric( initData(&f_symmetric,1,"symmetric","0 = nonsymmetric arbitrary matrix, 1 = symmetric matrix, 2 = symmetric positive definite, -1 = structurally symmetric matrix") ) , f_verbose( initData(&f_verbose,false,"verbose","Dump system state at each iteration") ) , f_saveDataToFile( initData(&f_saveDataToFile, "saveDataToFile", "save matrix, RHS and solution vectors to file")) { } template<class TMatrix, class TVector> void SparsePARDISOSolver<TMatrix,TVector>::init() { numStep = 0; numPrevNZ = 0; numActNZ = 0; Inherit::init(); } template<class TMatrix, class TVector> SparsePARDISOSolver<TMatrix,TVector>::~SparsePARDISOSolver() { } template<class TMatrix, class TVector> int SparsePARDISOSolver<TMatrix,TVector>::callPardiso(SparsePARDISOSolverInvertData* data, int phase, Vector* vx, Vector* vb) { int maxfct = 1; // Maximum number of numerical factorizations int mnum = 1; // Which factorization to use int n = data->Mfiltered.rowSize(); double* a = NULL; int* ia = NULL; int* ja = NULL; int* perm = NULL; // User-specified permutation vector int nrhs = 0; // Number of right hand sides int msglvl = (f_verbose.getValue())?1:0; // Print statistical information double* b = NULL; double* x = NULL; int error = 0; if (phase > 0) { ia = (int *) &(data->Mfiltered.getRowBegin()[0]); ja = (int *) &(data->Mfiltered.getColsIndex()[0]); a = (double*) &(data->Mfiltered.getColsValue()[0]); numActNZ = ia[n]-1; if (f_saveDataToFile.getValue()) { std::ofstream f; char name[100]; sprintf(name, "spmatrix_PARD_%04d.txt", numStep); f.open(name); int rw = 0; for (int i = 0; i < ia[n]-1; i++) { if (ia[rw] == i+1) rw++; f << rw << " " << ja[i] << " " << a[i] << std::endl; } f.close(); sprintf(name, "compmatrix_PARD_%04d.txt", numStep); f.open(name); for (int i = 0; i <= n; i++) f << ia[i] << std::endl; for (int i = 0; i < ia[n]-1; i++) f << ja[i] << " " << a[i] << std::endl; f.close(); } if (vx) { nrhs = 1; x = vx->ptr(); b = vb->ptr(); } } sout << "Solver phase " << phase << "..." << sendl; sofa::helper::AdvancedTimer::stepBegin("PardisoRealSolving"); F77_FUNC(pardiso)(data->pardiso_pt, &maxfct, &mnum, &data->pardiso_mtype, &phase, &n, a, ia, ja, perm, &nrhs, data->pardiso_iparm, &msglvl, b, x, &error, data->pardiso_dparm); sofa::helper::AdvancedTimer::stepEnd("PardisoRealSolving"); const char* msg = NULL; switch(error) { case 0: break; case -1: msg="Input inconsistent"; break; case -2: msg="Not enough memory"; break; case -3: msg="Reordering problem"; break; case -4: msg="Zero pivot, numerical fact. or iterative refinement problem"; break; case -5: msg="Unclassified (internal) error"; break; case -6: msg="Preordering failed (matrix types 11, 13 only)"; break; case -7: msg="Diagonal matrix problem"; break; case -8: msg="32-bit integer overflow problem"; break; case -10: msg="No license file pardiso.lic found"; break; case -11: msg="License is expired"; break; case -12: msg="Wrong username or hostname"; break; case -100: msg="Reached maximum number of Krylov-subspace iteration in iterative solver"; break; case -101: msg="No sufficient convergence in Krylov-subspace iteration within 25 iterations"; break; case -102: msg="Error in Krylov-subspace iteration"; break; case -103: msg="Break-Down in Krylov-subspace iteration"; break; default: msg="Unknown error"; break; } if (msg) serr << "Solver phase " << phase << ": ERROR " << error << " : " << msg << sendl; return error; } template<class TMatrix, class TVector> void SparsePARDISOSolver<TMatrix,TVector>::invert(Matrix& M) { sofa::helper::AdvancedTimer::stepBegin("PardisoInvert"); if (f_saveDataToFile.getValue()) { std::cout << this->getName() << ": saving to " << numStep << std::endl; std::ofstream f; char name[100]; sprintf(name, "matrix_PARD_%04d.txt", numStep); f.open(name); f << M; f.close(); } M.compress(); SparsePARDISOSolverInvertData * data = (SparsePARDISOSolverInvertData *) this->getMatrixInvertData(&M); if (data->pardiso_initerr) return; data->Mfiltered.clear(); if (f_symmetric.getValue() > 0) { data->Mfiltered.copyUpperNonZeros(M); data->Mfiltered.fullDiagonal(); sout << "Filtered upper part of M, nnz = " << data->Mfiltered.getRowBegin().back() << sendl; } else if (f_symmetric.getValue() < 0) { data->Mfiltered.copyNonZeros(M); data->Mfiltered.fullDiagonal(); sout << "Filtered M, nnz = " << data->Mfiltered.getRowBegin().back() << sendl; } else { data->Mfiltered.copyNonZeros(M); data->Mfiltered.fullRows(); sout << "Filtered M, nnz = " << data->Mfiltered.getRowBegin().back() << sendl; } // Convert matrix from 0-based C-notation to Fortran 1-based notation. data->Mfiltered.shiftIndices(1); /* -------------------------------------------------------------------- */ /* .. Reordering and Symbolic Factorization. This step also allocates */ /* all memory that is necessary for the factorization. */ /* -------------------------------------------------------------------- */ //if (!data->factorized || numPrevNZ != numAtNZ || numStep < 10) { sout << "Analyzing the matrix" << std::endl; if (callPardiso(data, 11)) return; data->factorized = true; sout << "Reordering completed ..." << sendl; sout << "Number of nonzeros in factors = " << data->pardiso_iparm[17] << sendl; sout << "Number of factorization MFLOPS = " << data->pardiso_iparm[18] << sendl; numPrevNZ = numActNZ; } /* -------------------------------------------------------------------- */ /* .. Numerical factorization. */ /* -------------------------------------------------------------------- */ if (callPardiso(data, 22)) { data->factorized = false; return; } sout << "Factorization completed ..." << sendl; sofa::helper::AdvancedTimer::stepEnd("PardisoInvert"); } template<class TMatrix, class TVector> void SparsePARDISOSolver<TMatrix,TVector>::solve (Matrix& M, Vector& z, Vector& r) { if (f_saveDataToFile.getValue()){ std::ofstream f; char name[100]; sprintf(name, "rhs_PARD_%04d.txt", numStep); f.open(name); f << r; f.close(); } sofa::helper::AdvancedTimer::stepBegin("PardisoSolve"); SparsePARDISOSolverInvertData * data = (SparsePARDISOSolverInvertData *) this->getMatrixInvertData(&M); if (data->pardiso_initerr) return; if (!data->factorized) return; /* -------------------------------------------------------------------- */ /* .. Back substitution and iterative refinement. */ /* -------------------------------------------------------------------- */ data->pardiso_iparm[7] = 1; /* Max numbers of iterative refinement steps. */ if (callPardiso(data, 33, &z, &r)) return; sofa::helper::AdvancedTimer::stepEnd("PardisoSolve"); if (f_saveDataToFile.getValue()) { std::ofstream f; char name[100]; sprintf(name, "solution_PARD_%04d.txt", numStep); f.open(name); f << z; f.close(); } numStep++; } SOFA_DECL_CLASS(SparsePARDISOSolver) int SparsePARDISOSolverClass = core::RegisterObject("Direct linear solvers implemented with the PARDISO library") .add< SparsePARDISOSolver< CompressedRowSparseMatrix<double>,FullVector<double> > >() .add< SparsePARDISOSolver< CompressedRowSparseMatrix< defaulttype::Mat<3,3,double> >,FullVector<double> > >(true) .addAlias("PARDISOSolver") ; } // namespace linearsolver } // namespace component } // namespace sofa <|endoftext|>
<commit_before>#include <Automaton.h> #include "Atm_command.h" Atm_command & Atm_command::begin( Stream * stream, char buffer[], int size ) { const static state_t state_table[] PROGMEM = { /* ON_ENTER ON_LOOP ON_EXIT EVT_INPUT EVT_EOL ELSE */ /* IDLE */ -1, -1, -1, READCHAR, -1, -1, /* READCHAR */ ACT_READCHAR, -1, -1, READCHAR, SEND, -1, /* SEND */ ACT_SEND, -1, -1, -1, -1, IDLE, }; Machine::begin( state_table, ELSE ); _stream = stream; _buffer = buffer; _bufsize = size; _bufptr = 0; _separator = " "; _eol = '\n'; _lastch = '\0'; return *this; } Atm_command & Atm_command::onCommand(void (*callback)( int idx ), const char * cmds ) { _callback = callback; _commands = cmds; return *this; } Atm_command & Atm_command::separator( const char sep[] ) { _separator = sep; return *this; } char * Atm_command::arg( int id ) { int cnt = 0; int i; if ( id == 0 ) return _buffer; for ( i = 0; i < _bufptr; i++ ) { if ( _buffer[i] == '\0' ) { if ( ++cnt == id ) { i++; break; } } } return &_buffer[i]; } int Atm_command::lookup( int id, const char * cmdlist ) { int cnt = 0; char * arg = this->arg( id ); char * a = arg; while ( cmdlist[0] != '\0' ) { while ( cmdlist[0] != '\0' && toupper( cmdlist[0] ) == toupper( a[0] ) ) { cmdlist++; a++; } if ( a[0] == '\0' ) return cnt; if ( cmdlist[0] == ' ' ) cnt++; cmdlist++; a = arg; } return -1; } int Atm_command::event( int id ) { switch ( id ) { case EVT_INPUT : return _stream->available(); case EVT_EOL : return _buffer[_bufptr-1] == _eol || _bufptr >= _bufsize; } return 0; } void Atm_command::action( int id ) { switch ( id ) { case ACT_READCHAR : if ( _stream->available() ) { char ch = _stream->read(); if ( strchr( _separator, ch ) == NULL ) { _buffer[_bufptr++] = ch; _lastch = ch; } else { if ( _lastch != '\0' ) _buffer[_bufptr++] = '\0'; _lastch = '\0'; } } return; case ACT_SEND : _buffer[--_bufptr] = '\0'; (*_callback)( lookup( 0, _commands ) ); _lastch = '\0'; _bufptr = 0; return; } } Atm_command & Atm_command::onSwitch( swcb_sym_t switch_callback ) { Machine::onSwitch( switch_callback, "IDLE\0READCHAR\0SEND", "EVT_INPUT\0EVT_EOL\0ELSE" ); return *this; } // TinyMachine version Att_command & Att_command::begin( Stream * stream, char buffer[], int size ) { const static tiny_state_t state_table[] PROGMEM = { /* ON_ENTER ON_LOOP ON_EXIT EVT_INPUT EVT_EOL ELSE */ /* IDLE */ -1, -1, -1, READCHAR, -1, -1, /* READCHAR */ ACT_READCHAR, -1, -1, READCHAR, SEND, -1, /* SEND */ ACT_SEND, -1, -1, -1, -1, IDLE, }; TinyMachine::begin( state_table, ELSE ); _stream = stream; _buffer = buffer; _bufsize = size; _bufptr = 0; _separator = " "; _eol = '\n'; _lastch = '\0'; return *this; } Att_command & Att_command::onCommand(void (*callback)( int idx ), const char * cmds ) { _callback = callback; _commands = cmds; return *this; } Att_command & Att_command::separator( const char sep[] ) { _separator = sep; return *this; } char * Att_command::arg( int id ) { int cnt = 0; int i; if ( id == 0 ) return _buffer; for ( i = 0; i < _bufptr; i++ ) { if ( _buffer[i] == '\0' ) { if ( ++cnt == id ) { i++; break; } } } return &_buffer[i]; } int Att_command::lookup( int id, const char * cmdlist ) { int cnt = 0; char * arg = this->arg( id ); char * a = arg; while ( cmdlist[0] != '\0' ) { while ( cmdlist[0] != '\0' && toupper( cmdlist[0] ) == toupper( a[0] ) ) { cmdlist++; a++; } if ( a[0] == '\0' ) return cnt; if ( cmdlist[0] == ' ' ) cnt++; cmdlist++; a = arg; } return -1; } int Att_command::event( int id ) { switch ( id ) { case EVT_INPUT : return _stream->available(); case EVT_EOL : return _buffer[_bufptr-1] == '\r' || _buffer[_bufptr-1] == '\n' || _bufptr >= _bufsize; } return 0; } void Att_command::action( int id ) { switch ( id ) { case ACT_READCHAR : if ( _stream->available() ) { char ch = _stream->read(); if ( strchr( _separator, ch ) == NULL ) { _buffer[_bufptr++] = ch; _lastch = ch; } else { if ( _lastch != '\0' ) _buffer[_bufptr++] = '\0'; _lastch = '\0'; } } return; case ACT_SEND : _buffer[--_bufptr] = '\0'; (*_callback)( lookup( 0, _commands ) ); _lastch = '\0'; _bufptr = 0; return; } } <commit_msg>Changed Atm_command back to just \n for an EOL character<commit_after>#include <Automaton.h> #include "Atm_command.h" Atm_command & Atm_command::begin( Stream * stream, char buffer[], int size ) { const static state_t state_table[] PROGMEM = { /* ON_ENTER ON_LOOP ON_EXIT EVT_INPUT EVT_EOL ELSE */ /* IDLE */ -1, -1, -1, READCHAR, -1, -1, /* READCHAR */ ACT_READCHAR, -1, -1, READCHAR, SEND, -1, /* SEND */ ACT_SEND, -1, -1, -1, -1, IDLE, }; Machine::begin( state_table, ELSE ); _stream = stream; _buffer = buffer; _bufsize = size; _bufptr = 0; _separator = " "; _eol = '\n'; _lastch = '\0'; return *this; } Atm_command & Atm_command::onCommand(void (*callback)( int idx ), const char * cmds ) { _callback = callback; _commands = cmds; return *this; } Atm_command & Atm_command::separator( const char sep[] ) { _separator = sep; return *this; } char * Atm_command::arg( int id ) { int cnt = 0; int i; if ( id == 0 ) return _buffer; for ( i = 0; i < _bufptr; i++ ) { if ( _buffer[i] == '\0' ) { if ( ++cnt == id ) { i++; break; } } } return &_buffer[i]; } int Atm_command::lookup( int id, const char * cmdlist ) { int cnt = 0; char * arg = this->arg( id ); char * a = arg; while ( cmdlist[0] != '\0' ) { while ( cmdlist[0] != '\0' && toupper( cmdlist[0] ) == toupper( a[0] ) ) { cmdlist++; a++; } if ( a[0] == '\0' ) return cnt; if ( cmdlist[0] == ' ' ) cnt++; cmdlist++; a = arg; } return -1; } int Atm_command::event( int id ) { switch ( id ) { case EVT_INPUT : return _stream->available(); case EVT_EOL : return _buffer[_bufptr-1] == _eol || _bufptr >= _bufsize; } return 0; } void Atm_command::action( int id ) { switch ( id ) { case ACT_READCHAR : if ( _stream->available() ) { char ch = _stream->read(); if ( strchr( _separator, ch ) == NULL ) { _buffer[_bufptr++] = ch; _lastch = ch; } else { if ( _lastch != '\0' ) _buffer[_bufptr++] = '\0'; _lastch = '\0'; } } return; case ACT_SEND : _buffer[--_bufptr] = '\0'; (*_callback)( lookup( 0, _commands ) ); _lastch = '\0'; _bufptr = 0; return; } } Atm_command & Atm_command::onSwitch( swcb_sym_t switch_callback ) { Machine::onSwitch( switch_callback, "IDLE\0READCHAR\0SEND", "EVT_INPUT\0EVT_EOL\0ELSE" ); return *this; } // TinyMachine version Att_command & Att_command::begin( Stream * stream, char buffer[], int size ) { const static tiny_state_t state_table[] PROGMEM = { /* ON_ENTER ON_LOOP ON_EXIT EVT_INPUT EVT_EOL ELSE */ /* IDLE */ -1, -1, -1, READCHAR, -1, -1, /* READCHAR */ ACT_READCHAR, -1, -1, READCHAR, SEND, -1, /* SEND */ ACT_SEND, -1, -1, -1, -1, IDLE, }; TinyMachine::begin( state_table, ELSE ); _stream = stream; _buffer = buffer; _bufsize = size; _bufptr = 0; _separator = " "; _eol = '\n'; _lastch = '\0'; return *this; } Att_command & Att_command::onCommand(void (*callback)( int idx ), const char * cmds ) { _callback = callback; _commands = cmds; return *this; } Att_command & Att_command::separator( const char sep[] ) { _separator = sep; return *this; } char * Att_command::arg( int id ) { int cnt = 0; int i; if ( id == 0 ) return _buffer; for ( i = 0; i < _bufptr; i++ ) { if ( _buffer[i] == '\0' ) { if ( ++cnt == id ) { i++; break; } } } return &_buffer[i]; } int Att_command::lookup( int id, const char * cmdlist ) { int cnt = 0; char * arg = this->arg( id ); char * a = arg; while ( cmdlist[0] != '\0' ) { while ( cmdlist[0] != '\0' && toupper( cmdlist[0] ) == toupper( a[0] ) ) { cmdlist++; a++; } if ( a[0] == '\0' ) return cnt; if ( cmdlist[0] == ' ' ) cnt++; cmdlist++; a = arg; } return -1; } int Att_command::event( int id ) { switch ( id ) { case EVT_INPUT : return _stream->available(); case EVT_EOL : return _buffer[_bufptr-1] == _eol || _bufptr >= _bufsize; } return 0; } void Att_command::action( int id ) { switch ( id ) { case ACT_READCHAR : if ( _stream->available() ) { char ch = _stream->read(); if ( strchr( _separator, ch ) == NULL ) { _buffer[_bufptr++] = ch; _lastch = ch; } else { if ( _lastch != '\0' ) _buffer[_bufptr++] = '\0'; _lastch = '\0'; } } return; case ACT_SEND : _buffer[--_bufptr] = '\0'; (*_callback)( lookup( 0, _commands ) ); _lastch = '\0'; _bufptr = 0; return; } } <|endoftext|>
<commit_before>/* * * Copyright 2015 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <node.h> #include "call.h" #include "call_credentials.h" #include "channel_credentials.h" #include "util.h" #include "grpc/grpc.h" #include "grpc/grpc_security.h" #include "grpc/support/log.h" namespace grpc { namespace node { using Nan::Callback; using Nan::EscapableHandleScope; using Nan::HandleScope; using Nan::Maybe; using Nan::MaybeLocal; using Nan::ObjectWrap; using Nan::Persistent; using Nan::Utf8String; using v8::Array; using v8::Context; using v8::Exception; using v8::External; using v8::Function; using v8::FunctionTemplate; using v8::Integer; using v8::Local; using v8::Object; using v8::ObjectTemplate; using v8::Value; Nan::Callback *ChannelCredentials::constructor; Persistent<FunctionTemplate> ChannelCredentials::fun_tpl; ChannelCredentials::ChannelCredentials(grpc_channel_credentials *credentials) : wrapped_credentials(credentials) {} ChannelCredentials::~ChannelCredentials() { grpc_channel_credentials_release(wrapped_credentials); } struct callback_md { Nan::Callback *callback; }; static int verify_peer_callback_wrapper(const char* servername, const char* cert, void* userdata) { Nan::HandleScope scope; Nan::TryCatch try_catch; struct callback_md* md = (struct callback_md*)userdata; const unsigned argc = 2; Local<Value> argv[argc]; if (servername == NULL) { argv[0] = Nan::Null(); } else { argv[0] = Nan::New<v8::String>(servername).ToLocalChecked(); } if (cert == NULL) { argv[1] = Nan::Null(); } else { argv[1] = Nan::New<v8::String>(cert).ToLocalChecked(); } md->callback->Call(argc, argv); if (try_catch.HasCaught()) { return 1; } return 0; } static void verify_peer_callback_destruct(void *userdata) { callback_md *md = (callback_md*)userdata; delete md->callback; delete md; } void ChannelCredentials::Init(Local<Object> exports) { HandleScope scope; Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate>(New); tpl->SetClassName(Nan::New("ChannelCredentials").ToLocalChecked()); tpl->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetPrototypeMethod(tpl, "compose", Compose); fun_tpl.Reset(tpl); Local<Function> ctr = Nan::GetFunction(tpl).ToLocalChecked(); Nan::Set( ctr, Nan::New("createSsl").ToLocalChecked(), Nan::GetFunction(Nan::New<FunctionTemplate>(CreateSsl)).ToLocalChecked()); Nan::Set(ctr, Nan::New("createInsecure").ToLocalChecked(), Nan::GetFunction(Nan::New<FunctionTemplate>(CreateInsecure)) .ToLocalChecked()); Nan::Set(exports, Nan::New("ChannelCredentials").ToLocalChecked(), ctr); constructor = new Nan::Callback(ctr); } bool ChannelCredentials::HasInstance(Local<Value> val) { HandleScope scope; return Nan::New(fun_tpl)->HasInstance(val); } Local<Value> ChannelCredentials::WrapStruct( grpc_channel_credentials *credentials) { EscapableHandleScope scope; const int argc = 1; Local<Value> argv[argc] = { Nan::New<External>(reinterpret_cast<void *>(credentials))}; MaybeLocal<Object> maybe_instance = Nan::NewInstance(constructor->GetFunction(), argc, argv); if (maybe_instance.IsEmpty()) { return scope.Escape(Nan::Null()); } else { return scope.Escape(maybe_instance.ToLocalChecked()); } } grpc_channel_credentials *ChannelCredentials::GetWrappedCredentials() { return wrapped_credentials; } NAN_METHOD(ChannelCredentials::New) { if (info.IsConstructCall()) { if (!info[0]->IsExternal()) { return Nan::ThrowTypeError( "ChannelCredentials can only be created with the provided functions"); } Local<External> ext = info[0].As<External>(); grpc_channel_credentials *creds_value = reinterpret_cast<grpc_channel_credentials *>(ext->Value()); ChannelCredentials *credentials = new ChannelCredentials(creds_value); credentials->Wrap(info.This()); info.GetReturnValue().Set(info.This()); return; } else { // This should never be called directly return Nan::ThrowTypeError( "ChannelCredentials can only be created with the provided functions"); } } NAN_METHOD(ChannelCredentials::CreateSsl) { StringOrNull root_certs; StringOrNull private_key; StringOrNull cert_chain; if (::node::Buffer::HasInstance(info[0])) { root_certs.assign(info[0]); } else if (!(info[0]->IsNull() || info[0]->IsUndefined())) { return Nan::ThrowTypeError("createSsl's first argument must be a Buffer"); } if (::node::Buffer::HasInstance(info[1])) { private_key.assign(info[1]); } else if (!(info[1]->IsNull() || info[1]->IsUndefined())) { return Nan::ThrowTypeError( "createSSl's second argument must be a Buffer if provided"); } if (::node::Buffer::HasInstance(info[2])) { cert_chain.assign(info[2]); } else if (!(info[2]->IsNull() || info[2]->IsUndefined())) { return Nan::ThrowTypeError( "createSSl's third argument must be a Buffer if provided"); } grpc_ssl_pem_key_cert_pair key_cert_pair = {private_key.get(), cert_chain.get()}; if (private_key.isAssigned() != cert_chain.isAssigned()) { return Nan::ThrowError( "createSsl's second and third arguments must be" " provided or omitted together"); } verify_peer_options verify_options = {NULL, NULL, NULL}; if (!info[3]->IsUndefined()) { if (!info[3]->IsObject()) { return Nan::ThrowTypeError("createSsl's fourth argument must be an " "object"); } Local<Context> context = Nan::New<Context>(); Local<Object> object = info[3]->ToObject(); MaybeLocal<Array> maybe_props = object->GetOwnPropertyNames(context); if (!maybe_props.IsEmpty()) { Local<Array> props = maybe_props.ToLocalChecked(); for(uint32_t i=0; i < props->Length(); i++) { Local<Value> key = props->Get(i); Local<Value> value = object->Get(key); if (key->IsString()) { Nan::Utf8String keyStr(key->ToString()); if (strcmp("checkServerIdentity", (const char*)(*keyStr)) == 0) { if (!value->IsFunction()) { return Nan::ThrowError("Value of checkServerIdentity must be a function."); } struct callback_md *md = new struct callback_md; md->callback = new Callback(Local<Function>::Cast(value)); verify_options.verify_peer_callback = verify_peer_callback_wrapper; verify_options.verify_peer_callback_userdata = (void*)md; verify_options.verify_peer_destruct = verify_peer_callback_destruct; } } // do stuff with key / value } } } grpc_channel_credentials *creds = grpc_ssl_credentials_create( root_certs.get(), private_key.isAssigned() ? &key_cert_pair : NULL, &verify_options, NULL); if (creds == NULL) { info.GetReturnValue().SetNull(); } else { info.GetReturnValue().Set(WrapStruct(creds)); } } NAN_METHOD(ChannelCredentials::Compose) { if (!ChannelCredentials::HasInstance(info.This())) { return Nan::ThrowTypeError( "compose can only be called on ChannelCredentials objects"); } if (!CallCredentials::HasInstance(info[0])) { return Nan::ThrowTypeError( "compose's first argument must be a CallCredentials object"); } ChannelCredentials *self = ObjectWrap::Unwrap<ChannelCredentials>(info.This()); if (self->wrapped_credentials == NULL) { return Nan::ThrowTypeError("Cannot compose insecure credential"); } CallCredentials *other = ObjectWrap::Unwrap<CallCredentials>( Nan::To<Object>(info[0]).ToLocalChecked()); grpc_channel_credentials *creds = grpc_composite_channel_credentials_create( self->wrapped_credentials, other->GetWrappedCredentials(), NULL); if (creds == NULL) { info.GetReturnValue().SetNull(); } else { info.GetReturnValue().Set(WrapStruct(creds)); } } NAN_METHOD(ChannelCredentials::CreateInsecure) { info.GetReturnValue().Set(WrapStruct(NULL)); } } // namespace node } // namespace grpc <commit_msg>Simplify userdata being passed to checkServerIdentity callback.<commit_after>/* * * Copyright 2015 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <node.h> #include "call.h" #include "call_credentials.h" #include "channel_credentials.h" #include "util.h" #include "grpc/grpc.h" #include "grpc/grpc_security.h" #include "grpc/support/log.h" namespace grpc { namespace node { using Nan::Callback; using Nan::EscapableHandleScope; using Nan::HandleScope; using Nan::Maybe; using Nan::MaybeLocal; using Nan::ObjectWrap; using Nan::Persistent; using Nan::Utf8String; using v8::Array; using v8::Context; using v8::Exception; using v8::External; using v8::Function; using v8::FunctionTemplate; using v8::Integer; using v8::Local; using v8::Object; using v8::ObjectTemplate; using v8::Value; Nan::Callback *ChannelCredentials::constructor; Persistent<FunctionTemplate> ChannelCredentials::fun_tpl; ChannelCredentials::ChannelCredentials(grpc_channel_credentials *credentials) : wrapped_credentials(credentials) {} ChannelCredentials::~ChannelCredentials() { grpc_channel_credentials_release(wrapped_credentials); } static int verify_peer_callback_wrapper(const char* servername, const char* cert, void* userdata) { Nan::HandleScope scope; Nan::TryCatch try_catch; Nan::Callback *callback = (Nan::Callback*)userdata; const unsigned argc = 2; Local<Value> argv[argc]; if (servername == NULL) { argv[0] = Nan::Null(); } else { argv[0] = Nan::New<v8::String>(servername).ToLocalChecked(); } if (cert == NULL) { argv[1] = Nan::Null(); } else { argv[1] = Nan::New<v8::String>(cert).ToLocalChecked(); } callback->Call(argc, argv); if (try_catch.HasCaught()) { return 1; } return 0; } static void verify_peer_callback_destruct(void *userdata) { Nan::Callback *callback = (Nan::Callback*)userdata; delete callback; } void ChannelCredentials::Init(Local<Object> exports) { HandleScope scope; Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate>(New); tpl->SetClassName(Nan::New("ChannelCredentials").ToLocalChecked()); tpl->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetPrototypeMethod(tpl, "compose", Compose); fun_tpl.Reset(tpl); Local<Function> ctr = Nan::GetFunction(tpl).ToLocalChecked(); Nan::Set( ctr, Nan::New("createSsl").ToLocalChecked(), Nan::GetFunction(Nan::New<FunctionTemplate>(CreateSsl)).ToLocalChecked()); Nan::Set(ctr, Nan::New("createInsecure").ToLocalChecked(), Nan::GetFunction(Nan::New<FunctionTemplate>(CreateInsecure)) .ToLocalChecked()); Nan::Set(exports, Nan::New("ChannelCredentials").ToLocalChecked(), ctr); constructor = new Nan::Callback(ctr); } bool ChannelCredentials::HasInstance(Local<Value> val) { HandleScope scope; return Nan::New(fun_tpl)->HasInstance(val); } Local<Value> ChannelCredentials::WrapStruct( grpc_channel_credentials *credentials) { EscapableHandleScope scope; const int argc = 1; Local<Value> argv[argc] = { Nan::New<External>(reinterpret_cast<void *>(credentials))}; MaybeLocal<Object> maybe_instance = Nan::NewInstance(constructor->GetFunction(), argc, argv); if (maybe_instance.IsEmpty()) { return scope.Escape(Nan::Null()); } else { return scope.Escape(maybe_instance.ToLocalChecked()); } } grpc_channel_credentials *ChannelCredentials::GetWrappedCredentials() { return wrapped_credentials; } NAN_METHOD(ChannelCredentials::New) { if (info.IsConstructCall()) { if (!info[0]->IsExternal()) { return Nan::ThrowTypeError( "ChannelCredentials can only be created with the provided functions"); } Local<External> ext = info[0].As<External>(); grpc_channel_credentials *creds_value = reinterpret_cast<grpc_channel_credentials *>(ext->Value()); ChannelCredentials *credentials = new ChannelCredentials(creds_value); credentials->Wrap(info.This()); info.GetReturnValue().Set(info.This()); return; } else { // This should never be called directly return Nan::ThrowTypeError( "ChannelCredentials can only be created with the provided functions"); } } NAN_METHOD(ChannelCredentials::CreateSsl) { StringOrNull root_certs; StringOrNull private_key; StringOrNull cert_chain; if (::node::Buffer::HasInstance(info[0])) { root_certs.assign(info[0]); } else if (!(info[0]->IsNull() || info[0]->IsUndefined())) { return Nan::ThrowTypeError("createSsl's first argument must be a Buffer"); } if (::node::Buffer::HasInstance(info[1])) { private_key.assign(info[1]); } else if (!(info[1]->IsNull() || info[1]->IsUndefined())) { return Nan::ThrowTypeError( "createSSl's second argument must be a Buffer if provided"); } if (::node::Buffer::HasInstance(info[2])) { cert_chain.assign(info[2]); } else if (!(info[2]->IsNull() || info[2]->IsUndefined())) { return Nan::ThrowTypeError( "createSSl's third argument must be a Buffer if provided"); } grpc_ssl_pem_key_cert_pair key_cert_pair = {private_key.get(), cert_chain.get()}; if (private_key.isAssigned() != cert_chain.isAssigned()) { return Nan::ThrowError( "createSsl's second and third arguments must be" " provided or omitted together"); } verify_peer_options verify_options = {NULL, NULL, NULL}; if (!info[3]->IsUndefined()) { if (!info[3]->IsObject()) { return Nan::ThrowTypeError("createSsl's fourth argument must be an " "object"); } Local<Context> context = Nan::New<Context>(); Local<Object> object = info[3]->ToObject(); MaybeLocal<Array> maybe_props = object->GetOwnPropertyNames(context); if (!maybe_props.IsEmpty()) { Local<Array> props = maybe_props.ToLocalChecked(); for(uint32_t i=0; i < props->Length(); i++) { Local<Value> key = props->Get(i); Local<Value> value = object->Get(key); if (key->IsString()) { Nan::Utf8String keyStr(key->ToString()); if (strcmp("checkServerIdentity", (const char*)(*keyStr)) == 0) { if (!value->IsFunction()) { return Nan::ThrowError("Value of checkServerIdentity must be a function."); } Nan::Callback *callback = new Callback(Local<Function>::Cast(value)); verify_options.verify_peer_callback = verify_peer_callback_wrapper; verify_options.verify_peer_callback_userdata = (void*)callback; verify_options.verify_peer_destruct = verify_peer_callback_destruct; } } // do stuff with key / value } } } grpc_channel_credentials *creds = grpc_ssl_credentials_create( root_certs.get(), private_key.isAssigned() ? &key_cert_pair : NULL, &verify_options, NULL); if (creds == NULL) { info.GetReturnValue().SetNull(); } else { info.GetReturnValue().Set(WrapStruct(creds)); } } NAN_METHOD(ChannelCredentials::Compose) { if (!ChannelCredentials::HasInstance(info.This())) { return Nan::ThrowTypeError( "compose can only be called on ChannelCredentials objects"); } if (!CallCredentials::HasInstance(info[0])) { return Nan::ThrowTypeError( "compose's first argument must be a CallCredentials object"); } ChannelCredentials *self = ObjectWrap::Unwrap<ChannelCredentials>(info.This()); if (self->wrapped_credentials == NULL) { return Nan::ThrowTypeError("Cannot compose insecure credential"); } CallCredentials *other = ObjectWrap::Unwrap<CallCredentials>( Nan::To<Object>(info[0]).ToLocalChecked()); grpc_channel_credentials *creds = grpc_composite_channel_credentials_create( self->wrapped_credentials, other->GetWrappedCredentials(), NULL); if (creds == NULL) { info.GetReturnValue().SetNull(); } else { info.GetReturnValue().Set(WrapStruct(creds)); } } NAN_METHOD(ChannelCredentials::CreateInsecure) { info.GetReturnValue().Set(WrapStruct(NULL)); } } // namespace node } // namespace grpc <|endoftext|>
<commit_before>//===--------------------------------------------------------------------------------*- C++ -*-===// // _ // | | // __| | __ ___ ___ ___ // / _` |/ _` \ \ /\ / / '_ | // | (_| | (_| |\ V V /| | | | // \__,_|\__,_| \_/\_/ |_| |_| - Compiler Toolchain // // // This file is distributed under the MIT License (MIT). // See LICENSE.txt for details. // //===------------------------------------------------------------------------------------------===// #include "dawn/Support/Logger.h" #include "dawn/Support/Assert.h" #include "dawn/Support/FileSystem.h" #include "dawn/Support/Format.h" #include <chrono> #include <sstream> namespace dawn { Logger::MessageFormatter makeMessageFormatter(const std::string type) { return [type](const std::string& msg, const std::string& file, int line) { std::stringstream ss; ss << "[" << file << ":" << line << "] "; if(type != "") ss << type << ": "; ss << msg; return ss.str(); }; } Logger::DiagnosticFormatter makeDiagnosticFormatter(const std::string type) { return [type](const std::string& msg, const std::string& file, int line, const std::string& source, SourceLocation loc) { std::stringstream ss; ss << "[" << file << ":" << line << "]"; if(source != "") ss << " " << source; if(loc.Line >= 0) { ss << ":" << loc.Line; } if(loc.Column >= 0) { ss << ":" << loc.Column; } if(type != "") ss << ": " << type; ss << ": " << msg; return ss.str(); }; } MessageProxy::MessageProxy(const MessageProxy& other) : logger_(other.logger_), ss_(other.ss_.str()), file_(other.file_), line_(other.line_) {} MessageProxy::MessageProxy(Logger& logger, const std::string& file, int line) : logger_(logger), file_(file), line_(line) {} MessageProxy::~MessageProxy() { logger_.enqueue(ss_.str(), file_, line_); } DiagnosticProxy::DiagnosticProxy(const DiagnosticProxy& other) : logger_(other.logger_), ss_(other.ss_.str()), file_(other.file_), line_(other.line_), source_(other.source_), loc_(other.loc_) {} DiagnosticProxy::DiagnosticProxy(Logger& logger, const std::string& file, int line, const std::string& source, SourceLocation loc) : logger_(logger), file_(file), line_(line), source_(source), loc_(loc) {} DiagnosticProxy::~DiagnosticProxy() { logger_.enqueue(ss_.str(), file_, line_, source_, loc_); } Logger::Logger(MessageFormatter msgFmt, DiagnosticFormatter diagFmt, std::ostream& os, bool show) : msgFmt_(msgFmt), diagFmt_(diagFmt), os_(&os), data_(), show_(show) {} MessageProxy Logger::operator()(const std::string& file, int line) { return MessageProxy(*this, file, line); } DiagnosticProxy Logger::operator()(const std::string& file, int line, const std::string& source, SourceLocation loc) { return DiagnosticProxy(*this, file, line, source, loc); } void Logger::doEnqueue(const std::string& message) { data_.push_back(message); if(show_) { *os_ << data_.back(); if(data_.back().back() != '\n') *os_ << '\n'; } } void Logger::enqueue(std::string msg, const std::string& file, int line) { doEnqueue(msgFmt_(msg, file, line)); } void Logger::enqueue(std::string msg, const std::string& file, int line, const std::string& source, SourceLocation loc) { doEnqueue(diagFmt_(msg, file, line, source, loc)); } std::ostream& Logger::stream() const { return *os_; } void Logger::stream(std::ostream& os) { os_ = &os; } Logger::MessageFormatter Logger::messageFormatter() const { return msgFmt_; } void Logger::messageFormatter(const MessageFormatter& msgFmt) { msgFmt_ = msgFmt; } Logger::DiagnosticFormatter Logger::diagnosticFormatter() const { return diagFmt_; } void Logger::diagnosticFormatter(const DiagnosticFormatter& diagFmt) { diagFmt_ = diagFmt; } void Logger::clear() { data_.clear(); } void Logger::show() { show_ = true; } void Logger::hide() { show_ = false; } // Expose container of messages Logger::iterator Logger::begin() { return std::begin(data_); } Logger::iterator Logger::end() { return std::end(data_); } Logger::const_iterator Logger::begin() const { return std::begin(data_); } Logger::const_iterator Logger::end() const { return std::end(data_); } Logger::Container::size_type Logger::size() const { return std::size(data_); } std::string createDiagnosticStackTrace(const std::string& prefix, const DiagnosticStack& inputStack) { auto stack = inputStack; std::stringstream ss; while(!stack.empty()) { ss << prefix; const auto& [call, loc] = stack.top(); ss << call; if(loc.isValid()) ss << " at " << loc.Line << ":" << loc.Column; ss << '\n'; stack.pop(); } return ss.str(); } namespace log { Logger info(makeMessageFormatter("INFO"), makeDiagnosticFormatter("INFO"), std::cout, false); Logger warn(makeMessageFormatter("WARNING"), makeDiagnosticFormatter("WARNING"), std::cout, true); Logger error(makeMessageFormatter("ERROR"), makeDiagnosticFormatter("ERROR"), std::cerr, true); void setVerbosity(Level level) { switch(level) { case Level::All: info.show(); warn.show(); error.show(); break; case Level::Warnings: info.hide(); warn.show(); error.show(); break; case Level::Errors: info.hide(); warn.hide(); error.show(); break; case Level::None: info.hide(); warn.hide(); error.hide(); break; } } } // namespace log } // namespace dawn <commit_msg>Switch warnings to stderr #1047<commit_after>//===--------------------------------------------------------------------------------*- C++ -*-===// // _ // | | // __| | __ ___ ___ ___ // / _` |/ _` \ \ /\ / / '_ | // | (_| | (_| |\ V V /| | | | // \__,_|\__,_| \_/\_/ |_| |_| - Compiler Toolchain // // // This file is distributed under the MIT License (MIT). // See LICENSE.txt for details. // //===------------------------------------------------------------------------------------------===// #include "dawn/Support/Logger.h" #include "dawn/Support/Assert.h" #include "dawn/Support/FileSystem.h" #include "dawn/Support/Format.h" #include <chrono> #include <sstream> namespace dawn { Logger::MessageFormatter makeMessageFormatter(const std::string type) { return [type](const std::string& msg, const std::string& file, int line) { std::stringstream ss; ss << "[" << file << ":" << line << "] "; if(type != "") ss << type << ": "; ss << msg; return ss.str(); }; } Logger::DiagnosticFormatter makeDiagnosticFormatter(const std::string type) { return [type](const std::string& msg, const std::string& file, int line, const std::string& source, SourceLocation loc) { std::stringstream ss; ss << "[" << file << ":" << line << "]"; if(source != "") ss << " " << source; if(loc.Line >= 0) { ss << ":" << loc.Line; } if(loc.Column >= 0) { ss << ":" << loc.Column; } if(type != "") ss << ": " << type; ss << ": " << msg; return ss.str(); }; } MessageProxy::MessageProxy(const MessageProxy& other) : logger_(other.logger_), ss_(other.ss_.str()), file_(other.file_), line_(other.line_) {} MessageProxy::MessageProxy(Logger& logger, const std::string& file, int line) : logger_(logger), file_(file), line_(line) {} MessageProxy::~MessageProxy() { logger_.enqueue(ss_.str(), file_, line_); } DiagnosticProxy::DiagnosticProxy(const DiagnosticProxy& other) : logger_(other.logger_), ss_(other.ss_.str()), file_(other.file_), line_(other.line_), source_(other.source_), loc_(other.loc_) {} DiagnosticProxy::DiagnosticProxy(Logger& logger, const std::string& file, int line, const std::string& source, SourceLocation loc) : logger_(logger), file_(file), line_(line), source_(source), loc_(loc) {} DiagnosticProxy::~DiagnosticProxy() { logger_.enqueue(ss_.str(), file_, line_, source_, loc_); } Logger::Logger(MessageFormatter msgFmt, DiagnosticFormatter diagFmt, std::ostream& os, bool show) : msgFmt_(msgFmt), diagFmt_(diagFmt), os_(&os), data_(), show_(show) {} MessageProxy Logger::operator()(const std::string& file, int line) { return MessageProxy(*this, file, line); } DiagnosticProxy Logger::operator()(const std::string& file, int line, const std::string& source, SourceLocation loc) { return DiagnosticProxy(*this, file, line, source, loc); } void Logger::doEnqueue(const std::string& message) { data_.push_back(message); if(show_) { *os_ << data_.back(); if(data_.back().back() != '\n') *os_ << '\n'; } } void Logger::enqueue(std::string msg, const std::string& file, int line) { doEnqueue(msgFmt_(msg, file, line)); } void Logger::enqueue(std::string msg, const std::string& file, int line, const std::string& source, SourceLocation loc) { doEnqueue(diagFmt_(msg, file, line, source, loc)); } std::ostream& Logger::stream() const { return *os_; } void Logger::stream(std::ostream& os) { os_ = &os; } Logger::MessageFormatter Logger::messageFormatter() const { return msgFmt_; } void Logger::messageFormatter(const MessageFormatter& msgFmt) { msgFmt_ = msgFmt; } Logger::DiagnosticFormatter Logger::diagnosticFormatter() const { return diagFmt_; } void Logger::diagnosticFormatter(const DiagnosticFormatter& diagFmt) { diagFmt_ = diagFmt; } void Logger::clear() { data_.clear(); } void Logger::show() { show_ = true; } void Logger::hide() { show_ = false; } // Expose container of messages Logger::iterator Logger::begin() { return std::begin(data_); } Logger::iterator Logger::end() { return std::end(data_); } Logger::const_iterator Logger::begin() const { return std::begin(data_); } Logger::const_iterator Logger::end() const { return std::end(data_); } Logger::Container::size_type Logger::size() const { return std::size(data_); } std::string createDiagnosticStackTrace(const std::string& prefix, const DiagnosticStack& inputStack) { auto stack = inputStack; std::stringstream ss; while(!stack.empty()) { ss << prefix; const auto& [call, loc] = stack.top(); ss << call; if(loc.isValid()) ss << " at " << loc.Line << ":" << loc.Column; ss << '\n'; stack.pop(); } return ss.str(); } namespace log { Logger info(makeMessageFormatter("INFO"), makeDiagnosticFormatter("INFO"), std::cout, false); Logger warn(makeMessageFormatter("WARNING"), makeDiagnosticFormatter("WARNING"), std::cerr, true); Logger error(makeMessageFormatter("ERROR"), makeDiagnosticFormatter("ERROR"), std::cerr, true); void setVerbosity(Level level) { switch(level) { case Level::All: info.show(); warn.show(); error.show(); break; case Level::Warnings: info.hide(); warn.show(); error.show(); break; case Level::Errors: info.hide(); warn.hide(); error.show(); break; case Level::None: info.hide(); warn.hide(); error.hide(); break; } } } // namespace log } // namespace dawn <|endoftext|>
<commit_before>//----------------------------------------------------------------------------- // Copyright (c) 2013 GarageGames, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. //----------------------------------------------------------------------------- #include <pthread.h> #include "platform/threads/thread.h" #include "platform/platformSemaphore.h" #include "platform/threads/mutex.h" #include "platform/platformTLS.h" #include "memory/safeDelete.h" #include <stdlib.h> struct PlatformThreadData { ThreadRunFunction mRunFunc; void* mRunArg; Thread* mThread; Semaphore mGateway; // default count is 1 U32 mThreadID; }; //----------------------------------------------------------------------------- // Function: ThreadRunHandler // Summary: Calls Thread::run() with the thread's specified run argument. // Neccesary because Thread::run() is provided as a non-threaded // way to execute the thread's run function. So we have to keep // track of the thread's lock here. static void *ThreadRunHandler(void * arg) { PlatformThreadData *mData = reinterpret_cast<PlatformThreadData*>(arg); Thread *thread = mData->mThread; mData->mThreadID = ThreadManager::getCurrentThreadId(); ThreadManager::addThread(thread); thread->run(mData->mRunArg); mData->mGateway.release(); // we could delete the Thread here, if it wants to be auto-deleted... if(thread->autoDelete) { ThreadManager::removeThread(thread); delete thread; } // return value for pthread lib's benefit return NULL; // the end of this function is where the created pthread will die. } //----------------------------------------------------------------------------- Thread::Thread(ThreadRunFunction func, void* arg, bool start_thread, bool autodelete) { mData = new PlatformThreadData; mData->mRunFunc = func; mData->mRunArg = arg; mData->mThread = this; mData->mThreadID = 0; autoDelete = autodelete; if(start_thread) start(); } Thread::~Thread() { stop(); join(); SAFE_DELETE(mData); } void Thread::start() { if(isAlive()) return; // cause start to block out other pthreads from using this Thread, // at least until ThreadRunHandler exits. mData->mGateway.acquire(); // reset the shouldStop flag, so we'll know when someone asks us to stop. shouldStop = false; pthread_create((pthread_t*)(&mData->mThreadID), NULL, ThreadRunHandler, mData); } bool Thread::join() { if(!isAlive()) return true; // not using pthread_join here because pthread_join cannot deal // with multiple simultaneous calls. mData->mGateway.acquire(); mData->mGateway.release(); return true; } void Thread::run(void* arg) { if(mData->mRunFunc) mData->mRunFunc(arg); } bool Thread::isAlive() { if(mData->mThreadID == 0) return false; if( mData->mGateway.acquire(false) ) { mData->mGateway.release(); return false; // we got the lock, it aint alive. } else return true; // we could not get the lock, it must be alive. } ThreadIdent Thread::getId() { return mData->mThreadID; } ThreadIdent ThreadManager::getCurrentThreadId() { return (U32)pthread_self(); } bool ThreadManager::compare(U32 threadId_1, U32 threadId_2) { return (bool)pthread_equal((pthread_t)threadId_1, (pthread_t)threadId_2); } class PlatformThreadStorage { public: pthread_key_t mThreadKey; }; ThreadStorage::ThreadStorage() { mThreadStorage = (PlatformThreadStorage *) mStorage; constructInPlace(mThreadStorage); pthread_key_create(&mThreadStorage->mThreadKey, NULL); } ThreadStorage::~ThreadStorage() { pthread_key_delete(mThreadStorage->mThreadKey); } void *ThreadStorage::get() { return pthread_getspecific(mThreadStorage->mThreadKey); } void ThreadStorage::set(void *value) { pthread_setspecific(mThreadStorage->mThreadKey, value); } <commit_msg>fix ThreadIdent issues<commit_after>//----------------------------------------------------------------------------- // Copyright (c) 2013 GarageGames, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. //----------------------------------------------------------------------------- #include <pthread.h> #include "platform/threads/thread.h" #include "platform/platformSemaphore.h" #include "platform/threads/mutex.h" #include "platform/platformTLS.h" #include "memory/safeDelete.h" #include <stdlib.h> struct PlatformThreadData { ThreadRunFunction mRunFunc; void* mRunArg; Thread* mThread; Semaphore mGateway; // default count is 1 U32 mThreadID; }; //----------------------------------------------------------------------------- // Function: ThreadRunHandler // Summary: Calls Thread::run() with the thread's specified run argument. // Neccesary because Thread::run() is provided as a non-threaded // way to execute the thread's run function. So we have to keep // track of the thread's lock here. static void *ThreadRunHandler(void * arg) { PlatformThreadData *mData = reinterpret_cast<PlatformThreadData*>(arg); Thread *thread = mData->mThread; mData->mThreadID = ThreadManager::getCurrentThreadId(); ThreadManager::addThread(thread); thread->run(mData->mRunArg); mData->mGateway.release(); // we could delete the Thread here, if it wants to be auto-deleted... if(thread->autoDelete) { ThreadManager::removeThread(thread); delete thread; } // return value for pthread lib's benefit return NULL; // the end of this function is where the created pthread will die. } //----------------------------------------------------------------------------- Thread::Thread(ThreadRunFunction func, void* arg, bool start_thread, bool autodelete) { mData = new PlatformThreadData; mData->mRunFunc = func; mData->mRunArg = arg; mData->mThread = this; mData->mThreadID = 0; autoDelete = autodelete; if(start_thread) start(); } Thread::~Thread() { stop(); join(); SAFE_DELETE(mData); } void Thread::start() { if(isAlive()) return; // cause start to block out other pthreads from using this Thread, // at least until ThreadRunHandler exits. mData->mGateway.acquire(); // reset the shouldStop flag, so we'll know when someone asks us to stop. shouldStop = false; pthread_create((pthread_t*)(&mData->mThreadID), NULL, ThreadRunHandler, mData); } bool Thread::join() { if(!isAlive()) return true; // not using pthread_join here because pthread_join cannot deal // with multiple simultaneous calls. mData->mGateway.acquire(); mData->mGateway.release(); return true; } void Thread::run(void* arg) { if(mData->mRunFunc) mData->mRunFunc(arg); } bool Thread::isAlive() { if(mData->mThreadID == 0) return false; if( mData->mGateway.acquire(false) ) { mData->mGateway.release(); return false; // we got the lock, it aint alive. } else return true; // we could not get the lock, it must be alive. } ThreadIdent Thread::getId() { return mData->mThreadID; } ThreadIdent ThreadManager::getCurrentThreadId() { return (U32)pthread_self(); } bool ThreadManager::compare(ThreadIdent threadId_1, ThreadIdent threadId_2) { return (bool)pthread_equal((pthread_t)threadId_1, (pthread_t)threadId_2); } class PlatformThreadStorage { public: pthread_key_t mThreadKey; }; ThreadStorage::ThreadStorage() { mThreadStorage = (PlatformThreadStorage *) mStorage; constructInPlace(mThreadStorage); pthread_key_create(&mThreadStorage->mThreadKey, NULL); } ThreadStorage::~ThreadStorage() { pthread_key_delete(mThreadStorage->mThreadKey); } void *ThreadStorage::get() { return pthread_getspecific(mThreadStorage->mThreadKey); } void ThreadStorage::set(void *value) { pthread_setspecific(mThreadStorage->mThreadKey, value); } <|endoftext|>
<commit_before>#include "gtest/gtest.h" #include <Managers/GameAgent.h> #include <Managers/GameInterface.h> #include <Tasks/BasicTasks/Draw.h> #include <Tasks/BasicTasks/PlayCard.h> #include <future> using namespace Hearthstonepp; TEST(BasicCard, EX1_066) { GameAgent agent( Player(new Account("Player 1", ""), new Deck("", CardClass::WARRIOR)), Player(new Account("Player 2", ""), new Deck("", CardClass::MAGE))); TaskAgent& taskAgent = agent.GetTaskAgent(); Player& player1 = agent.GetPlayer1(); Player& player2 = agent.GetPlayer2(); player1.totalMana = player1.existMana = 10; player2.totalMana = player2.existMana = 10; Card* FieryWarAxe = Cards::GetInstance()->FindCardByName("Fiery War Axe"); Card* AcidicSwampOoze = Cards::GetInstance()->FindCardByName("Acidic Swamp Ooze"); // Run DrawCardTask Directly (without TaskAgent or GameAgent) agent.RunTask(BasicTasks::DrawCardTask(FieryWarAxe), player1, player2); EXPECT_EQ(agent.GetPlayer1().hand.size(), static_cast<size_t>(1)); EXPECT_EQ(agent.GetPlayer1().hand[0]->card->name, "Fiery War Axe"); agent.RunTask(BasicTasks::DrawCardTask(AcidicSwampOoze), player2, player1); EXPECT_EQ(agent.GetPlayer2().hand.size(), static_cast<size_t>(1)); EXPECT_EQ(agent.GetPlayer2().hand[0]->card->name, "Acidic Swamp Ooze"); // Temporal GameInterface, Return Response Data to PlayCardTask std::future<void> response1 = std::async(std::launch::async, [&agent]() { TaskMeta meta; agent.GetTaskMeta(meta); // Select Card Requirement Verification auto required = flatbuffers::GetRoot<FlatData::RequireTaskMeta>( meta.GetConstBuffer().get()); EXPECT_EQ(TaskID::_from_integral(required->required()), +TaskID::SELECT_CARD); meta = Serializer::CreateResponsePlayCard(0); agent.WriteSyncBuffer(std::move(meta)); }); MetaData result = agent.RunTask(BasicTasks::PlayCardTask(taskAgent), player1, player2); EXPECT_EQ(result, MetaData::PLAY_WEAPON_SUCCESS); EXPECT_NE(agent.GetPlayer1().hero->weapon, nullptr); // Return Response Data to PlayCardTask And PlayMinionTask std::future<void> response2 = std::async(std::launch::async, [&agent]() { TaskMeta meta; agent.GetTaskMeta(meta); // Select Card Requirement Verification auto selectCard = flatbuffers::GetRoot<FlatData::RequireTaskMeta>( meta.GetConstBuffer().get()); EXPECT_EQ(TaskID::_from_integral(selectCard->required()), +TaskID::SELECT_CARD); TaskMeta card = Serializer::CreateResponsePlayCard(0); agent.WriteSyncBuffer(std::move(card)); agent.GetTaskMeta(meta); // Select Position Requirement Verification auto selectPosition = flatbuffers::GetRoot<FlatData::RequireTaskMeta>( meta.GetConstBuffer().get()); EXPECT_EQ(TaskID::_from_integral(selectPosition->required()), +TaskID::SELECT_POSITION); TaskMeta position = Serializer::CreateResponsePlayMinion(0); agent.WriteSyncBuffer(std::move(position)); }); result = agent.RunTask(BasicTasks::PlayCardTask(taskAgent), player2, player1); EXPECT_EQ(result, MetaData::PLAY_MINION_SUCCESS); EXPECT_EQ(agent.GetPlayer1().hero->weapon, nullptr); } TEST(BasicCard, CS2_041) { GameAgent agent( Player(new Account("Player 1", ""), new Deck("", CardClass::SHAMAN)), Player(new Account("Player 2", ""), new Deck("", CardClass::MAGE))); Player& player1 = agent.GetPlayer1(); Player& player2 = agent.GetPlayer2(); player1.totalMana = agent.GetPlayer1().existMana = 10; player2.totalMana = agent.GetPlayer2().existMana = 10; Card* AcidicSwampOoze = Cards::GetInstance()->FindCardByName("Acidic Swamp Ooze"); Card* AncestralHealing = Cards::GetInstance()->FindCardByName("Ancestral Healing"); agent.RunTask(BasicTasks::DrawCardTask(AcidicSwampOoze), player1, player2); agent.RunTask(BasicTasks::DrawCardTask(AncestralHealing), player1, player2); EXPECT_EQ(agent.GetPlayer1().hand.size(), static_cast<size_t>(2)); // agent.Process(agent.GetPlayer1(), BasicTask::PlayCardTask(0, 0)); // auto minion = // dynamic_cast<Character*>(agent.GetPlayer1().field.at(0)); // minion->health -= 1; // EXPECT_EQ(minion->health, 1u); // // agent.Process(agent.GetPlayer1(), // BasicTask::PlayCardTask(0, -1, TargetType::MY_FIELD, // 1)); // EXPECT_EQ(static_cast<bool>(minion->gameTags[GameTag::TAUNT]), true); // EXPECT_EQ(minion->health, 2); }<commit_msg>Format codes by clang-format<commit_after>#include "gtest/gtest.h" #include <Managers/GameAgent.h> #include <Managers/GameInterface.h> #include <Tasks/BasicTasks/Draw.h> #include <Tasks/BasicTasks/PlayCard.h> #include <future> using namespace Hearthstonepp; TEST(BasicCard, EX1_066) { GameAgent agent( Player(new Account("Player 1", ""), new Deck("", CardClass::WARRIOR)), Player(new Account("Player 2", ""), new Deck("", CardClass::MAGE))); TaskAgent& taskAgent = agent.GetTaskAgent(); Player& player1 = agent.GetPlayer1(); Player& player2 = agent.GetPlayer2(); player1.totalMana = player1.existMana = 10; player2.totalMana = player2.existMana = 10; Card* FieryWarAxe = Cards::GetInstance()->FindCardByName("Fiery War Axe"); Card* AcidicSwampOoze = Cards::GetInstance()->FindCardByName("Acidic Swamp Ooze"); // Run DrawCardTask Directly (without TaskAgent or GameAgent) agent.RunTask(BasicTasks::DrawCardTask(FieryWarAxe), player1, player2); EXPECT_EQ(agent.GetPlayer1().hand.size(), static_cast<size_t>(1)); EXPECT_EQ(agent.GetPlayer1().hand[0]->card->name, "Fiery War Axe"); agent.RunTask(BasicTasks::DrawCardTask(AcidicSwampOoze), player2, player1); EXPECT_EQ(agent.GetPlayer2().hand.size(), static_cast<size_t>(1)); EXPECT_EQ(agent.GetPlayer2().hand[0]->card->name, "Acidic Swamp Ooze"); // Temporal GameInterface, Return Response Data to PlayCardTask std::future<void> response1 = std::async(std::launch::async, [&agent]() { TaskMeta meta; agent.GetTaskMeta(meta); // Select Card Requirement Verification auto required = flatbuffers::GetRoot<FlatData::RequireTaskMeta>( meta.GetConstBuffer().get()); EXPECT_EQ(TaskID::_from_integral(required->required()), +TaskID::SELECT_CARD); meta = Serializer::CreateResponsePlayCard(0); agent.WriteSyncBuffer(std::move(meta)); }); MetaData result = agent.RunTask(BasicTasks::PlayCardTask(taskAgent), player1, player2); EXPECT_EQ(result, MetaData::PLAY_WEAPON_SUCCESS); EXPECT_NE(agent.GetPlayer1().hero->weapon, nullptr); // Return Response Data to PlayCardTask And PlayMinionTask std::future<void> response2 = std::async(std::launch::async, [&agent]() { TaskMeta meta; agent.GetTaskMeta(meta); // Select Card Requirement Verification auto selectCard = flatbuffers::GetRoot<FlatData::RequireTaskMeta>( meta.GetConstBuffer().get()); EXPECT_EQ(TaskID::_from_integral(selectCard->required()), +TaskID::SELECT_CARD); TaskMeta card = Serializer::CreateResponsePlayCard(0); agent.WriteSyncBuffer(std::move(card)); agent.GetTaskMeta(meta); // Select Position Requirement Verification auto selectPosition = flatbuffers::GetRoot<FlatData::RequireTaskMeta>( meta.GetConstBuffer().get()); EXPECT_EQ(TaskID::_from_integral(selectPosition->required()), +TaskID::SELECT_POSITION); TaskMeta position = Serializer::CreateResponsePlayMinion(0); agent.WriteSyncBuffer(std::move(position)); }); result = agent.RunTask(BasicTasks::PlayCardTask(taskAgent), player2, player1); EXPECT_EQ(result, MetaData::PLAY_MINION_SUCCESS); EXPECT_EQ(agent.GetPlayer1().hero->weapon, nullptr); } TEST(BasicCard, CS2_041) { GameAgent agent( Player(new Account("Player 1", ""), new Deck("", CardClass::SHAMAN)), Player(new Account("Player 2", ""), new Deck("", CardClass::MAGE))); Player& player1 = agent.GetPlayer1(); Player& player2 = agent.GetPlayer2(); player1.totalMana = agent.GetPlayer1().existMana = 10; player2.totalMana = agent.GetPlayer2().existMana = 10; Card* AcidicSwampOoze = Cards::GetInstance()->FindCardByName("Acidic Swamp Ooze"); Card* AncestralHealing = Cards::GetInstance()->FindCardByName("Ancestral Healing"); agent.RunTask(BasicTasks::DrawCardTask(AcidicSwampOoze), player1, player2); agent.RunTask(BasicTasks::DrawCardTask(AncestralHealing), player1, player2); EXPECT_EQ(agent.GetPlayer1().hand.size(), static_cast<size_t>(2)); // agent.Process(agent.GetPlayer1(), BasicTask::PlayCardTask(0, 0)); // auto minion = // dynamic_cast<Character*>(agent.GetPlayer1().field.at(0)); // minion->health -= 1; // EXPECT_EQ(minion->health, 1u); // // agent.Process(agent.GetPlayer1(), // BasicTask::PlayCardTask(0, -1, TargetType::MY_FIELD, // 1)); // EXPECT_EQ(static_cast<bool>(minion->gameTags[GameTag::TAUNT]), true); // EXPECT_EQ(minion->health, 2); }<|endoftext|>
<commit_before>/* * Motors_Controller.cpp * * Created on: 18. 7. 2017 * Author: michp */ #include "Motors_Controller.h" namespace flyhero { Motors_Controller &Motors_Controller::Instance() { static Motors_Controller instance; return instance; } Motors_Controller::Motors_Controller() : pwm(PWM_Generator::Instance()) { this->motor_FR = 0; this->motor_FL = 0; this->motor_BR = 0; this->motor_BL = 0; this->roll_PID.Set_I_Max(50); this->pitch_PID.Set_I_Max(50); this->yaw_PID.Set_I_Max(50); this->invert_yaw = false; this->throttle = 0; this->roll_PID_semaphore = xSemaphoreCreateBinary(); this->pitch_PID_semaphore = xSemaphoreCreateBinary(); this->yaw_PID_semaphore = xSemaphoreCreateBinary(); this->throttle_semaphore = xSemaphoreCreateBinary(); this->invert_yaw_semaphore = xSemaphoreCreateBinary(); } void Motors_Controller::Init() { xSemaphoreGive(this->roll_PID_semaphore); xSemaphoreGive(this->pitch_PID_semaphore); xSemaphoreGive(this->yaw_PID_semaphore); xSemaphoreGive(this->throttle_semaphore); xSemaphoreGive(this->invert_yaw_semaphore); this->pwm.Init(); this->pwm.Arm(); } void Motors_Controller::Set_PID_Constants(Axis axis, float Kp, float Ki, float Kd) { switch (axis) { case Roll: while (xSemaphoreTake(this->roll_PID_semaphore, 0) != pdTRUE); this->roll_PID.Set_Kp(Kp); this->roll_PID.Set_Ki(Ki); this->roll_PID.Set_Kd(Kd); xSemaphoreGive(this->roll_PID_semaphore); break; case Pitch: while (xSemaphoreTake(this->pitch_PID_semaphore, 0) != pdTRUE); this->pitch_PID.Set_Kp(Kp); this->pitch_PID.Set_Ki(Ki); this->pitch_PID.Set_Kd(Kd); xSemaphoreGive(this->pitch_PID_semaphore); break; case Yaw: while (xSemaphoreTake(this->yaw_PID_semaphore, 0) != pdTRUE); this->yaw_PID.Set_Kp(Kp); this->yaw_PID.Set_Ki(Ki); this->yaw_PID.Set_Kd(Kd); xSemaphoreGive(this->yaw_PID_semaphore); break; } } void Motors_Controller::Set_Throttle(uint16_t throttle) { while (xSemaphoreTake(this->throttle_semaphore, 0) != pdTRUE); this->throttle = throttle; xSemaphoreGive(this->throttle_semaphore); } void Motors_Controller::Set_Invert_Yaw(bool invert) { // TODO semaphore might not be needed since boolean should be atomic while (xSemaphoreTake(this->invert_yaw_semaphore, 0) != pdTRUE); this->invert_yaw = invert; xSemaphoreGive(this->invert_yaw_semaphore); } void Motors_Controller::Update_Motors(IMU::Euler_Angles euler) { while (xSemaphoreTake(this->throttle_semaphore, 0) != pdTRUE); uint16_t throttle = this->throttle; xSemaphoreGive(this->throttle_semaphore); if (throttle > 0) { float pitch_correction, roll_correction, yaw_correction; while (xSemaphoreTake(this->roll_PID_semaphore, 0) != pdTRUE); roll_correction = this->roll_PID.Get_PID(0 - euler.roll); xSemaphoreGive(this->roll_PID_semaphore); while (xSemaphoreTake(this->pitch_PID_semaphore, 0) != pdTRUE); pitch_correction = this->pitch_PID.Get_PID(0 - euler.pitch); xSemaphoreGive(this->pitch_PID_semaphore); while (xSemaphoreTake(this->yaw_PID_semaphore, 0) != pdTRUE); yaw_correction = this->yaw_PID.Get_PID(0 - euler.yaw); xSemaphoreGive(this->yaw_PID_semaphore); while (xSemaphoreTake(this->invert_yaw_semaphore, 0) != pdTRUE); // not sure about yaw signs if (!this->invert_yaw) { xSemaphoreGive(this->invert_yaw_semaphore); this->motor_FL = throttle - roll_correction - pitch_correction - yaw_correction; // PB2 this->motor_BL = throttle - roll_correction + pitch_correction + yaw_correction; // PA15 this->motor_FR = throttle + roll_correction - pitch_correction + yaw_correction; // PB10 this->motor_BR = throttle + roll_correction + pitch_correction - yaw_correction; // PA1 } else { xSemaphoreGive(this->invert_yaw_semaphore); this->motor_FL = throttle - roll_correction - pitch_correction + yaw_correction; // PB2 this->motor_BL = throttle - roll_correction + pitch_correction - yaw_correction; // PA15 this->motor_FR = throttle + roll_correction - pitch_correction - yaw_correction; // PB10 this->motor_BR = throttle + roll_correction + pitch_correction + yaw_correction; // PA1 } if (this->motor_FL > 1000) this->motor_FL = 1000; else if (this->motor_FL < 0) this->motor_FL = 0; if (this->motor_BL > 1000) this->motor_BL = 1000; else if (this->motor_BL < 0) this->motor_BL = 0; if (this->motor_FR > 1000) this->motor_FR = 1000; else if (this->motor_FR < 0) this->motor_FR = 0; if (this->motor_BR > 1000) this->motor_BR = 1000; else if (this->motor_BR < 0) this->motor_BR = 0; this->pwm.Set_Pulse(PWM_Generator::MOTOR_FL, this->motor_FL); this->pwm.Set_Pulse(PWM_Generator::MOTOR_BL, this->motor_BL); this->pwm.Set_Pulse(PWM_Generator::MOTOR_FR, this->motor_FR); this->pwm.Set_Pulse(PWM_Generator::MOTOR_BR, this->motor_BR); } else { // TODO //MPU6050::Instance().Reset_Integrators(); this->pwm.Set_Pulse(PWM_Generator::MOTOR_FL, 0); this->pwm.Set_Pulse(PWM_Generator::MOTOR_BL, 0); this->pwm.Set_Pulse(PWM_Generator::MOTOR_FR, 0); this->pwm.Set_Pulse(PWM_Generator::MOTOR_BR, 0); } } } /* namespace flyhero */ <commit_msg>(Motors controller): check correctness of throttle value that is being set<commit_after>/* * Motors_Controller.cpp * * Created on: 18. 7. 2017 * Author: michp */ #include "Motors_Controller.h" namespace flyhero { Motors_Controller &Motors_Controller::Instance() { static Motors_Controller instance; return instance; } Motors_Controller::Motors_Controller() : pwm(PWM_Generator::Instance()) { this->motor_FR = 0; this->motor_FL = 0; this->motor_BR = 0; this->motor_BL = 0; this->roll_PID.Set_I_Max(50); this->pitch_PID.Set_I_Max(50); this->yaw_PID.Set_I_Max(50); this->invert_yaw = false; this->throttle = 0; this->roll_PID_semaphore = xSemaphoreCreateBinary(); this->pitch_PID_semaphore = xSemaphoreCreateBinary(); this->yaw_PID_semaphore = xSemaphoreCreateBinary(); this->throttle_semaphore = xSemaphoreCreateBinary(); this->invert_yaw_semaphore = xSemaphoreCreateBinary(); } void Motors_Controller::Init() { xSemaphoreGive(this->roll_PID_semaphore); xSemaphoreGive(this->pitch_PID_semaphore); xSemaphoreGive(this->yaw_PID_semaphore); xSemaphoreGive(this->throttle_semaphore); xSemaphoreGive(this->invert_yaw_semaphore); this->pwm.Init(); this->pwm.Arm(); } void Motors_Controller::Set_PID_Constants(Axis axis, float Kp, float Ki, float Kd) { switch (axis) { case Roll: while (xSemaphoreTake(this->roll_PID_semaphore, 0) != pdTRUE); this->roll_PID.Set_Kp(Kp); this->roll_PID.Set_Ki(Ki); this->roll_PID.Set_Kd(Kd); xSemaphoreGive(this->roll_PID_semaphore); break; case Pitch: while (xSemaphoreTake(this->pitch_PID_semaphore, 0) != pdTRUE); this->pitch_PID.Set_Kp(Kp); this->pitch_PID.Set_Ki(Ki); this->pitch_PID.Set_Kd(Kd); xSemaphoreGive(this->pitch_PID_semaphore); break; case Yaw: while (xSemaphoreTake(this->yaw_PID_semaphore, 0) != pdTRUE); this->yaw_PID.Set_Kp(Kp); this->yaw_PID.Set_Ki(Ki); this->yaw_PID.Set_Kd(Kd); xSemaphoreGive(this->yaw_PID_semaphore); break; } } void Motors_Controller::Set_Throttle(uint16_t throttle) { if (throttle > 1000) return; while (xSemaphoreTake(this->throttle_semaphore, 0) != pdTRUE); this->throttle = throttle; xSemaphoreGive(this->throttle_semaphore); } void Motors_Controller::Set_Invert_Yaw(bool invert) { // TODO semaphore might not be needed since boolean should be atomic while (xSemaphoreTake(this->invert_yaw_semaphore, 0) != pdTRUE); this->invert_yaw = invert; xSemaphoreGive(this->invert_yaw_semaphore); } void Motors_Controller::Update_Motors(IMU::Euler_Angles euler) { while (xSemaphoreTake(this->throttle_semaphore, 0) != pdTRUE); uint16_t throttle = this->throttle; xSemaphoreGive(this->throttle_semaphore); if (throttle > 0) { float pitch_correction, roll_correction, yaw_correction; while (xSemaphoreTake(this->roll_PID_semaphore, 0) != pdTRUE); roll_correction = this->roll_PID.Get_PID(0 - euler.roll); xSemaphoreGive(this->roll_PID_semaphore); while (xSemaphoreTake(this->pitch_PID_semaphore, 0) != pdTRUE); pitch_correction = this->pitch_PID.Get_PID(0 - euler.pitch); xSemaphoreGive(this->pitch_PID_semaphore); while (xSemaphoreTake(this->yaw_PID_semaphore, 0) != pdTRUE); yaw_correction = this->yaw_PID.Get_PID(0 - euler.yaw); xSemaphoreGive(this->yaw_PID_semaphore); while (xSemaphoreTake(this->invert_yaw_semaphore, 0) != pdTRUE); // not sure about yaw signs if (!this->invert_yaw) { xSemaphoreGive(this->invert_yaw_semaphore); this->motor_FL = throttle - roll_correction - pitch_correction - yaw_correction; // PB2 this->motor_BL = throttle - roll_correction + pitch_correction + yaw_correction; // PA15 this->motor_FR = throttle + roll_correction - pitch_correction + yaw_correction; // PB10 this->motor_BR = throttle + roll_correction + pitch_correction - yaw_correction; // PA1 } else { xSemaphoreGive(this->invert_yaw_semaphore); this->motor_FL = throttle - roll_correction - pitch_correction + yaw_correction; // PB2 this->motor_BL = throttle - roll_correction + pitch_correction - yaw_correction; // PA15 this->motor_FR = throttle + roll_correction - pitch_correction - yaw_correction; // PB10 this->motor_BR = throttle + roll_correction + pitch_correction + yaw_correction; // PA1 } if (this->motor_FL > 1000) this->motor_FL = 1000; else if (this->motor_FL < 0) this->motor_FL = 0; if (this->motor_BL > 1000) this->motor_BL = 1000; else if (this->motor_BL < 0) this->motor_BL = 0; if (this->motor_FR > 1000) this->motor_FR = 1000; else if (this->motor_FR < 0) this->motor_FR = 0; if (this->motor_BR > 1000) this->motor_BR = 1000; else if (this->motor_BR < 0) this->motor_BR = 0; this->pwm.Set_Pulse(PWM_Generator::MOTOR_FL, this->motor_FL); this->pwm.Set_Pulse(PWM_Generator::MOTOR_BL, this->motor_BL); this->pwm.Set_Pulse(PWM_Generator::MOTOR_FR, this->motor_FR); this->pwm.Set_Pulse(PWM_Generator::MOTOR_BR, this->motor_BR); } else { // TODO //MPU6050::Instance().Reset_Integrators(); this->pwm.Set_Pulse(PWM_Generator::MOTOR_FL, 0); this->pwm.Set_Pulse(PWM_Generator::MOTOR_BL, 0); this->pwm.Set_Pulse(PWM_Generator::MOTOR_FR, 0); this->pwm.Set_Pulse(PWM_Generator::MOTOR_BR, 0); } } } /* namespace flyhero */ <|endoftext|>
<commit_before>#include <list> #include "network.h" #include "Connection.h" #include <sys/time.h> #include <sys/types.h> #include <unistd.h> #include <stdio.h> extern UServer * THESERVER; namespace Network { class TCPServerPipe: public Pipe { public: TCPServerPipe(): fd(-1), port(-1) {} bool init(int port); virtual int readFD() {return fd;} virtual int writeFD() {return -1;} virtual void notifyWrite() {} virtual void notifyRead(); private: int fd; int port; }; bool TCPServerPipe::init(int port) { this->port = port; int rc; struct ::sockaddr_in address; #ifdef WIN32 /* initialize the socket api */ WSADATA info; rc = WSAStartup(MAKEWORD(1,1),&info); /* Winsock 1.1 */ if (rc!=0) { return false; } #endif /* create the socket */ fd = socket(AF_INET,SOCK_STREAM,0); if (fd==-1) { return false; } /* set the REUSEADDR option to 1 to allow imediate reuse of the port */ int yes = 1; if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *) &yes, sizeof (yes)) < 0) { return false; } /* fill in socket address */ memset(&address,0,sizeof(struct sockaddr_in)); address.sin_family = AF_INET; address.sin_port = htons((unsigned short)port); address.sin_addr.s_addr = INADDR_ANY; /* bind to port */ rc = bind(fd,(struct sockaddr *)&address,sizeof(struct sockaddr)); if (rc==-1) { return false; } /* listen for connections */ if (listen(fd,1)==-1) { return false; } registerNetworkPipe(this); return true; } void TCPServerPipe::notifyRead() { int cfd; struct sockaddr_in client; struct hostent* client_info; socklen_t asize = sizeof(struct sockaddr_in); cfd = accept(fd, (struct sockaddr *)&client, &asize); if (cfd==-1) { return ; } client_info = gethostbyname((char *)inet_ntoa(client.sin_addr)); Connection *c = new Connection(cfd); THESERVER->addConnection(c); registerNetworkPipe(c); } using std::list; list<Pipe *> pList; bool createTCPServer(int port) { TCPServerPipe * tsp = new TCPServerPipe(); if (!tsp->init(port)) { delete tsp; return false; } return true; } int buildFD(fd_set &rd, fd_set &wr) { FD_ZERO(&rd); FD_ZERO(&wr); int maxfd=0; for (list<Pipe *>::iterator i = pList.begin(); i != pList.end(); i++) { int f= (*i)->readFD(); if (f>0) FD_SET(f,&rd); if (f>maxfd) maxfd = f; int g= (*i)->writeFD(); if (g>0) FD_SET(g,&wr); if (g>maxfd) maxfd = g; } return maxfd+1; } void notify(fd_set &rd, fd_set &wr) { list<Pipe *>::iterator in; for (list<Pipe *>::iterator i = pList.begin(); i != pList.end(); i=in) { in=i; in++; int f= (*i)->readFD(); if (f>=0 && FD_ISSET(f,&rd)) (*i)->notifyRead(); f= (*i)->writeFD(); if (f>=0 && FD_ISSET(f,&wr)) (*i)->notifyWrite(); } } bool selectAndProcess(int usDelay) { fd_set rd; fd_set wr; int mx = buildFD(rd, wr ); struct timeval tv; tv.tv_sec=0; tv.tv_usec = usDelay; int r = select(mx, &rd, &wr, 0, &tv); if (r==0) return false; if (r>0) notify(rd, wr); if (r<0) { //XXX this is baad, we should realy do something fprintf(stderr, "SELECT ERROR\n"); } return (r>0); } void registerNetworkPipe(Pipe *p) { pList.push_back(p); } void unregisterNetworkPipe(Pipe *p) { list<Pipe *>::iterator i = find(pList.begin(), pList.end(), p); if (i != pList.end()) pList.erase(i); } void * processNetwork(void * useless) { while (true) { selectAndProcess(1000000); } } void startNetworkProcessingThread() { #ifdef WIN32 #error "write this" #else pthread_t * pt = new pthread_t; pthread_create(pt, 0, &processNetwork, 0); #endif } }; <commit_msg>fixed a glitch around select that fails under macosx (tv_usec >= 1000000 in time struct)<commit_after>#include <list> #include "network.h" #include "Connection.h" #include <sys/time.h> #include <sys/types.h> #include <unistd.h> #include <stdio.h> extern UServer * THESERVER; namespace Network { class TCPServerPipe: public Pipe { public: TCPServerPipe(): fd(-1), port(-1) {} bool init(int port); virtual int readFD() {return fd;} virtual int writeFD() {return -1;} virtual void notifyWrite() {} virtual void notifyRead(); private: int fd; int port; }; bool TCPServerPipe::init(int port) { this->port = port; int rc; struct ::sockaddr_in address; #ifdef WIN32 /* initialize the socket api */ WSADATA info; rc = WSAStartup(MAKEWORD(1,1),&info); /* Winsock 1.1 */ if (rc!=0) { return false; } #endif /* create the socket */ fd = socket(AF_INET,SOCK_STREAM,0); if (fd==-1) { return false; } /* set the REUSEADDR option to 1 to allow imediate reuse of the port */ int yes = 1; if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *) &yes, sizeof (yes)) < 0) { return false; } /* fill in socket address */ memset(&address,0,sizeof(struct sockaddr_in)); address.sin_family = AF_INET; address.sin_port = htons((unsigned short)port); address.sin_addr.s_addr = INADDR_ANY; /* bind to port */ rc = bind(fd,(struct sockaddr *)&address,sizeof(struct sockaddr)); if (rc==-1) { return false; } /* listen for connections */ if (listen(fd,1)==-1) { return false; } registerNetworkPipe(this); return true; } void TCPServerPipe::notifyRead() { int cfd; struct sockaddr_in client; struct hostent* client_info; socklen_t asize = sizeof(struct sockaddr_in); cfd = accept(fd, (struct sockaddr *)&client, &asize); if (cfd==-1) { return ; } client_info = gethostbyname((char *)inet_ntoa(client.sin_addr)); Connection *c = new Connection(cfd); THESERVER->addConnection(c); registerNetworkPipe(c); } using std::list; list<Pipe *> pList; bool createTCPServer(int port) { TCPServerPipe * tsp = new TCPServerPipe(); if (!tsp->init(port)) { delete tsp; return false; } return true; } int buildFD(fd_set &rd, fd_set &wr) { FD_ZERO(&rd); FD_ZERO(&wr); int maxfd=0; for (list<Pipe *>::iterator i = pList.begin(); i != pList.end(); i++) { int f= (*i)->readFD(); if (f>0) FD_SET(f,&rd); if (f>maxfd) maxfd = f; int g= (*i)->writeFD(); if (g>0) FD_SET(g,&wr); if (g>maxfd) maxfd = g; } return maxfd+1; } void notify(fd_set &rd, fd_set &wr) { list<Pipe *>::iterator in; for (list<Pipe *>::iterator i = pList.begin(); i != pList.end(); i=in) { in=i; in++; int f= (*i)->readFD(); if (f>=0 && FD_ISSET(f,&rd)) (*i)->notifyRead(); f= (*i)->writeFD(); if (f>=0 && FD_ISSET(f,&wr)) (*i)->notifyWrite(); } } bool selectAndProcess(int usDelay) { fd_set rd; fd_set wr; int mx = buildFD(rd, wr ); struct timeval tv; tv.tv_sec=usDelay/1000000; tv.tv_usec = usDelay-((usDelay/1000000)*1000000); int r = select(mx, &rd, &wr, 0, &tv); if (r==0) return false; if (r>0) notify(rd, wr); if (r<0) { //XXX this is baad, we should realy do something perror("SELECT ERROR:"); } return (r>0); } void registerNetworkPipe(Pipe *p) { pList.push_back(p); } void unregisterNetworkPipe(Pipe *p) { list<Pipe *>::iterator i = find(pList.begin(), pList.end(), p); if (i != pList.end()) pList.erase(i); } void * processNetwork(void * useless) { while (true) { selectAndProcess(1000000); } } void startNetworkProcessingThread() { #ifdef WIN32 #error "write this" #else pthread_t * pt = new pthread_t; pthread_create(pt, 0, &processNetwork, 0); #endif } }; <|endoftext|>
<commit_before>// Copyright (c) 2015 // Author: Chrono Law #ifndef _NDG_TEST_INIT_HPP #define _NDG_TEST_INIT_HPP #include "NdgTestConf.hpp" #include "NdgTestHandler.hpp" class NdgTestInit final { public: typedef NdgTestConf conf_type; typedef NdgTestHandler handler_type; typedef NdgTestInit this_type; public: static ngx_command_t* cmds() { static ngx_command_t n[] = { NgxCommand( ngx_string("ndg_test"), //NgxCmdString("ndg_test"), NgxTake(NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_CONF_FLAG, 1), ngx_conf_set_flag_slot, NGX_HTTP_LOC_CONF_OFFSET, offsetof(conf_type, enabled) ), NgxCommand() }; return n; } public: static ngx_http_module_t* ctx() { static ngx_http_module_t c = { NGX_MODULE_NULL(1), &handler_type::init, NGX_MODULE_NULL(4), &conf_type::create, &conf_type::merge, }; return &c; } public: static const ngx_module_t& module() { static ngx_module_t m = { NGX_MODULE_V1, ctx(), cmds(), NGX_HTTP_MODULE, NGX_MODULE_NULL(7), NGX_MODULE_V1_PADDING }; return m; } }; #endif //_NDG_TEST_INIT_HPP <commit_msg>update test module<commit_after>// Copyright (c) 2015 // Author: Chrono Law #ifndef _NDG_TEST_INIT_HPP #define _NDG_TEST_INIT_HPP #include "NdgTestConf.hpp" #include "NdgTestHandler.hpp" class NdgTestInit final { public: typedef NdgTestConf conf_type; typedef NdgTestHandler handler_type; typedef NdgTestInit this_type; public: static ngx_command_t* cmds() { static ngx_command_t n[] = { { ngx_string("ndg_test"), NgxTake(NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_CONF_FLAG, 1), ngx_conf_set_flag_slot, NGX_HTTP_LOC_CONF_OFFSET, offsetof(conf_type, enabled), 0 }, ngx_null_command }; return n; } public: static ngx_http_module_t* ctx() { static ngx_http_module_t c = { NGX_MODULE_NULL(1), &handler_type::init, NGX_MODULE_NULL(4), &conf_type::create, &conf_type::merge, }; return &c; } public: static const ngx_module_t& module() { static ngx_module_t m = { NGX_MODULE_V1, ctx(), cmds(), NGX_HTTP_MODULE, NGX_MODULE_NULL(7), NGX_MODULE_V1_PADDING }; return m; } }; #endif //_NDG_TEST_INIT_HPP <|endoftext|>
<commit_before>/******************************************************************************\ * File: test.cpp * Purpose: Implementation for wxextension cpp unit testing * Author: Anton van Wezenbeek * RCS-ID: $Id: test.cpp 450 2009-03-11 20:02:41Z antonvw $ * Created: za 17 jan 2009 11:51:20 CET * * Copyright (c) 2009 Anton van Wezenbeek * All rights are reserved. Reproduction in whole or part is prohibited * without the written consent of the copyright owner. \******************************************************************************/ #include <TestCaller.h> #include "test.h" void wxExTestFixture::setUp() { m_Config = new wxExConfig("test.cfg", wxCONFIG_USE_LOCAL_FILE); m_File = new wxExFile("test.h"); m_FileName = new wxExFileName("test.h"); m_FileNameStatistics = new wxExFileNameStatistics("test.h"); m_Lexer = new wxExLexer(); m_Lexers = new wxExLexers(wxExFileName("../../data/lexers.xml")); m_RCS = new wxExRCS(); m_Stat = new wxExStat("test.h"); m_Statistics = new wxExStatistics<long>(); } void wxExTestFixture::testConstructors() { CPPUNIT_ASSERT(m_File != NULL); } void wxExTestFixture::testMethods() { // test wxExConfig CPPUNIT_ASSERT(m_Config->Get("keystring", "val") == "val"); CPPUNIT_ASSERT(m_Config->Get("keylong", 12) == 12); CPPUNIT_ASSERT(m_Config->GetBool("keybool", true)); CPPUNIT_ASSERT(m_Config->GetFindReplaceData() != NULL); m_Config->Set("keystring", "val2"); CPPUNIT_ASSERT(m_Config->Get("keystring", "val") == "val2"); m_Config->Set("keylong", 15); CPPUNIT_ASSERT(m_Config->Get("keylong", 7) == 15); m_Config->SetBool("keybool", false); CPPUNIT_ASSERT(m_Config->GetBool("keybool", true) == false); m_Config->Toggle("keybool"); CPPUNIT_ASSERT(m_Config->GetBool("keybool", false)); m_Config->Set("Author", "myauthor"); CPPUNIT_ASSERT(m_Config->Get("Author", "yourauthor") == "myauthor"); // test wxExFile CPPUNIT_ASSERT(m_File->GetStat().IsOk()); CPPUNIT_ASSERT(m_File->GetStat().GetFullPath() == m_File->GetFileName().GetFullPath()); // The fullpath should be normalized, test it. CPPUNIT_ASSERT(m_File->GetFileName().GetFullPath() != "test.h"); CPPUNIT_ASSERT(!m_File->GetStat().IsReadOnly()); CPPUNIT_ASSERT(!m_File->CheckSyncNeeded()); CPPUNIT_ASSERT(!m_File->GetStat().IsReadOnly()); CPPUNIT_ASSERT(m_File->FileOpen(wxExFileName("test.bin"))); wxCharBuffer buffer = m_File->Read(); CPPUNIT_ASSERT(buffer.length() == 40); // test wxExFileName CPPUNIT_ASSERT(m_FileName->GetLexer().GetScintillaLexer().empty()); CPPUNIT_ASSERT(m_FileName->GetStat().IsOk()); m_FileName->Assign("xxx"); m_FileName->GetStat().Update("xxx"); CPPUNIT_ASSERT(!m_FileName->GetStat().IsOk()); // test wxExFileNameStatistics CPPUNIT_ASSERT(m_FileNameStatistics->Get().empty()); CPPUNIT_ASSERT(m_FileNameStatistics->Get("xx") == 0); // test wxExLexer *m_Lexer = m_Lexers->FindByText("// this is a cpp comment text"); CPPUNIT_ASSERT(m_Lexer->GetScintillaLexer().empty()); // we have no lexers // now read lexers CPPUNIT_ASSERT(m_Lexers->Read()); *m_Lexer = m_Lexers->FindByText("// this is a cpp comment text"); CPPUNIT_ASSERT(!m_Lexer->GetAssociations().empty()); CPPUNIT_ASSERT(!m_Lexer->GetColourings().empty()); CPPUNIT_ASSERT(!m_Lexer->GetCommentBegin().empty()); CPPUNIT_ASSERT(!m_Lexer->GetCommentBegin2().empty()); CPPUNIT_ASSERT(!m_Lexer->GetCommentEnd().empty()); CPPUNIT_ASSERT(m_Lexer->GetCommentEnd2().empty()); CPPUNIT_ASSERT(!m_Lexer->GetKeywords().empty()); CPPUNIT_ASSERT(!m_Lexer->GetKeywordsSet().empty()); CPPUNIT_ASSERT(!m_Lexer->GetKeywordsString().empty()); CPPUNIT_ASSERT(!m_Lexer->GetProperties().empty()); CPPUNIT_ASSERT(m_Lexer->IsKeyword("class")); CPPUNIT_ASSERT(m_Lexer->IsKeyword("const")); CPPUNIT_ASSERT(m_Lexer->KeywordStartsWith("cla")); CPPUNIT_ASSERT(!m_Lexer->KeywordStartsWith("xxx")); CPPUNIT_ASSERT(!m_Lexer->MakeComment("test", true).empty()); CPPUNIT_ASSERT(!m_Lexer->MakeComment("test", "test").empty()); CPPUNIT_ASSERT(m_Lexer->SetKeywords("hello:1")); CPPUNIT_ASSERT(m_Lexer->SetKeywords("test11 test21:1 test31:1 test12:2 test22:2")); CPPUNIT_ASSERT(!m_Lexer->IsKeyword("class")); // now overwritten CPPUNIT_ASSERT(m_Lexer->IsKeyword("test11")); CPPUNIT_ASSERT(m_Lexer->IsKeyword("test21")); CPPUNIT_ASSERT(m_Lexer->IsKeyword("test12")); CPPUNIT_ASSERT(m_Lexer->IsKeyword("test22")); CPPUNIT_ASSERT(m_Lexer->KeywordStartsWith("te")); CPPUNIT_ASSERT(!m_Lexer->KeywordStartsWith("xx")); CPPUNIT_ASSERT(!m_Lexer->GetKeywords().empty()); CPPUNIT_ASSERT(!m_Lexer->GetKeywordsSet().empty()); // test wxExLexers CPPUNIT_ASSERT(!m_Lexers->BuildComboBox(wxFileName("test.h")).empty()); CPPUNIT_ASSERT(!m_Lexers->BuildWildCards(wxFileName("test.h")).empty()); CPPUNIT_ASSERT(m_Lexers->Count() > 0); CPPUNIT_ASSERT(m_Lexers->FindByFileName(wxFileName("test.h")).GetScintillaLexer() == "cpp"); CPPUNIT_ASSERT(m_Lexers->FindByName("cpp").GetScintillaLexer() == "cpp"); CPPUNIT_ASSERT(m_Lexers->FindByText("// this is a cpp comment text").GetScintillaLexer() == "cpp"); CPPUNIT_ASSERT(!m_Lexers->GetIndicators().empty()); CPPUNIT_ASSERT(!m_Lexers->GetMarkers().empty()); CPPUNIT_ASSERT(!m_Lexers->GetStyles().empty()); CPPUNIT_ASSERT(!m_Lexers->GetStylesHex().empty()); // test wxExRCS CPPUNIT_ASSERT(m_RCS->GetDescription().empty()); CPPUNIT_ASSERT(m_RCS->GetUser().empty()); // test wxExStat CPPUNIT_ASSERT(!m_Stat->IsLink()); CPPUNIT_ASSERT(m_Stat->IsOk()); CPPUNIT_ASSERT(!m_Stat->IsReadOnly()); CPPUNIT_ASSERT(m_Stat->Update("testlink")); // CPPUNIT_ASSERT(m_Stat->IsLink()); // test wxExStatistics m_Statistics->Inc("test"); CPPUNIT_ASSERT(m_Statistics->Get("test") == 1); m_Statistics->Inc("test"); CPPUNIT_ASSERT(m_Statistics->Get("test") == 2); m_Statistics->Set("test", 13); CPPUNIT_ASSERT(m_Statistics->Get("test") == 13); m_Statistics->Dec("test"); CPPUNIT_ASSERT(m_Statistics->Get("test") == 12); m_Statistics->Inc("test2"); CPPUNIT_ASSERT(m_Statistics->Get("test2") == 1); m_Statistics->Clear(); CPPUNIT_ASSERT(m_Statistics->GetItems().empty()); // test wxExTextFile wxExTextFile textFile(wxExFileName("test.h"), ID_TOOL_REPORT_COUNT, m_Config, m_Lexers); CPPUNIT_ASSERT(textFile.RunTool()); CPPUNIT_ASSERT(!textFile.GetStatistics().GetElements().GetItems().empty()); CPPUNIT_ASSERT(!textFile.IsOpened()); // file should be closed after running tool CPPUNIT_ASSERT(textFile.RunTool()); // do the same test CPPUNIT_ASSERT(!textFile.GetStatistics().GetElements().GetItems().empty()); CPPUNIT_ASSERT(!textFile.IsOpened()); // file should be closed after running tool wxExTextFile textFile2(wxExFileName("test.h"), ID_TOOL_REPORT_KEYWORD, m_Config, m_Lexers); CPPUNIT_ASSERT(textFile2.RunTool()); // CPPUNIT_ASSERT(!m_TextFile->GetStatistics().GetKeywords().GetItems().empty()); // test wxExTool CPPUNIT_ASSERT(wxExTool(ID_TOOL_REPORT_COUNT).IsCount()); CPPUNIT_ASSERT(wxExTool(ID_TOOL_REPORT_FIND).IsFindType()); CPPUNIT_ASSERT(wxExTool(ID_TOOL_REPORT_REPLACE).IsFindType()); CPPUNIT_ASSERT(wxExTool(ID_TOOL_REPORT_COUNT).IsStatisticsType()); CPPUNIT_ASSERT(wxExTool(ID_TOOL_REPORT_COUNT).IsReportType()); CPPUNIT_ASSERT(wxExTool::GetToolInfo().empty()); // initialized by wxExApp, so not here // test various wxExMethods const wxString header = wxExHeader(textFile.GetFileName(), m_Config, "test"); CPPUNIT_ASSERT(header.Contains("test")); } void wxExTestFixture::testTiming() { wxExFile file("test.h"); CPPUNIT_ASSERT(file.IsOpened()); wxStopWatch sw; const int max = 10000; for (int i = 0; i < max; i++) { CPPUNIT_ASSERT(file.Read().length() > 0); } const long exfile_read = sw.Time(); sw.Start(); wxFile wxfile("test.h"); for (int j = 0; j < max; j++) { char* charbuffer = new char[wxfile.Length()]; wxfile.Read(charbuffer, wxfile.Length()); wxString* buffer = new wxString(charbuffer, wxfile.Length()); CPPUNIT_ASSERT(buffer->length() > 0); delete charbuffer; delete buffer; } const long file_read = sw.Time(); printf( "wxExFile::Read:%ld wxFile::Read:%ld\n", exfile_read, file_read); } void wxExTestFixture::testTimingAttrib() { const int max = 1000; wxStopWatch sw; const wxExFileName exfile("test.h"); int checked = 0; for (int i = 0; i < max; i++) { checked += exfile.GetStat().IsReadOnly(); } const long exfile_time = sw.Time(); sw.Start(); const wxFileName file("test.h"); for (int j = 0; j < max; j++) { checked += file.IsFileWritable(); } const long file_time = sw.Time(); printf( "wxExFileName::IsReadOnly:%ld wxFileName::IsFileWritable:%ld\n", exfile_time, file_time); } void wxExTestFixture::testTimingConfig() { const int max = 100000; wxStopWatch sw; for (int i = 0; i < max; i++) { m_Config->Get("test", 0); } const long exconfig = sw.Time(); sw.Start(); for (int j = 0; j < max; j++) { m_Config->Read("test", 0l); } const long config = sw.Time(); printf( "wxExConfig::Get:%ld wxConfig::Read:%ld\n", exconfig, config); } void wxExTestFixture::tearDown() { } wxExTestSuite::wxExTestSuite() : CppUnit::TestSuite("wxextension test suite") { // Add the tests. addTest(new CppUnit::TestCaller<wxExTestFixture>( "testConstructors", &wxExTestFixture::testConstructors)); addTest(new CppUnit::TestCaller<wxExTestFixture>( "testMethods", &wxExTestFixture::testMethods)); addTest(new CppUnit::TestCaller<wxExTestFixture>( "testTiming", &wxExTestFixture::testTiming)); addTest(new CppUnit::TestCaller<wxExTestFixture>( "testTimingAttrib", &wxExTestFixture::testTimingAttrib)); addTest(new CppUnit::TestCaller<wxExTestFixture>( "testTimingConfig", &wxExTestFixture::testTimingConfig)); } <commit_msg>fixed test for Ubuntu<commit_after>/******************************************************************************\ * File: test.cpp * Purpose: Implementation for wxextension cpp unit testing * Author: Anton van Wezenbeek * RCS-ID: $Id: test.cpp 450 2009-03-11 20:02:41Z antonvw $ * Created: za 17 jan 2009 11:51:20 CET * * Copyright (c) 2009 Anton van Wezenbeek * All rights are reserved. Reproduction in whole or part is prohibited * without the written consent of the copyright owner. \******************************************************************************/ #include <TestCaller.h> #include "test.h" void wxExTestFixture::setUp() { m_Config = new wxExConfig("test.cfg", wxCONFIG_USE_LOCAL_FILE); m_File = new wxExFile("test.h"); m_FileName = new wxExFileName("test.h"); m_FileNameStatistics = new wxExFileNameStatistics("test.h"); m_Lexer = new wxExLexer(); m_Lexers = new wxExLexers(wxExFileName("../../data/lexers.xml")); m_RCS = new wxExRCS(); m_Stat = new wxExStat("test.h"); m_Statistics = new wxExStatistics<long>(); } void wxExTestFixture::testConstructors() { CPPUNIT_ASSERT(m_File != NULL); } void wxExTestFixture::testMethods() { // test wxExConfig CPPUNIT_ASSERT(m_Config->Get("keystring", "val") == "val"); CPPUNIT_ASSERT(m_Config->Get("keylong", 12) == 12); CPPUNIT_ASSERT(m_Config->GetBool("keybool", true)); CPPUNIT_ASSERT(m_Config->GetFindReplaceData() != NULL); m_Config->Set("keystring", "val2"); CPPUNIT_ASSERT(m_Config->Get("keystring", "val") == "val2"); m_Config->Set("keylong", 15); CPPUNIT_ASSERT(m_Config->Get("keylong", 7) == 15); m_Config->SetBool("keybool", false); CPPUNIT_ASSERT(m_Config->GetBool("keybool", true) == false); m_Config->Toggle("keybool"); CPPUNIT_ASSERT(m_Config->GetBool("keybool", false)); m_Config->Set("Author", "myauthor"); CPPUNIT_ASSERT(m_Config->Get("Author", "yourauthor") == "myauthor"); // test wxExFile CPPUNIT_ASSERT(m_File->GetStat().IsOk()); CPPUNIT_ASSERT(m_File->GetStat().GetFullPath() == m_File->GetFileName().GetFullPath()); // The fullpath should be normalized, test it. CPPUNIT_ASSERT(m_File->GetFileName().GetFullPath() != "test.h"); CPPUNIT_ASSERT(!m_File->GetStat().IsReadOnly()); CPPUNIT_ASSERT(!m_File->CheckSyncNeeded()); CPPUNIT_ASSERT(!m_File->GetStat().IsReadOnly()); CPPUNIT_ASSERT(m_File->FileOpen(wxExFileName("test.bin"))); wxCharBuffer buffer = m_File->Read(); CPPUNIT_ASSERT(buffer.length() == 40); // test wxExFileName CPPUNIT_ASSERT(m_FileName->GetLexer().GetScintillaLexer().empty()); CPPUNIT_ASSERT(m_FileName->GetStat().IsOk()); m_FileName->Assign("xxx"); m_FileName->GetStat().Update("xxx"); CPPUNIT_ASSERT(!m_FileName->GetStat().IsOk()); // test wxExFileNameStatistics CPPUNIT_ASSERT(m_FileNameStatistics->Get().empty()); CPPUNIT_ASSERT(m_FileNameStatistics->Get("xx") == 0); // test wxExLexer *m_Lexer = m_Lexers->FindByText("// this is a cpp comment text"); CPPUNIT_ASSERT(m_Lexer->GetScintillaLexer().empty()); // we have no lexers // now read lexers CPPUNIT_ASSERT(m_Lexers->Read()); *m_Lexer = m_Lexers->FindByText("// this is a cpp comment text"); CPPUNIT_ASSERT(!m_Lexer->GetAssociations().empty()); CPPUNIT_ASSERT(!m_Lexer->GetColourings().empty()); CPPUNIT_ASSERT(!m_Lexer->GetCommentBegin().empty()); CPPUNIT_ASSERT(!m_Lexer->GetCommentBegin2().empty()); CPPUNIT_ASSERT(!m_Lexer->GetCommentEnd().empty()); CPPUNIT_ASSERT(m_Lexer->GetCommentEnd2().empty()); CPPUNIT_ASSERT(!m_Lexer->GetKeywords().empty()); CPPUNIT_ASSERT(!m_Lexer->GetKeywordsSet().empty()); CPPUNIT_ASSERT(!m_Lexer->GetKeywordsString().empty()); CPPUNIT_ASSERT(!m_Lexer->GetProperties().empty()); CPPUNIT_ASSERT(m_Lexer->IsKeyword("class")); CPPUNIT_ASSERT(m_Lexer->IsKeyword("const")); CPPUNIT_ASSERT(m_Lexer->KeywordStartsWith("cla")); CPPUNIT_ASSERT(!m_Lexer->KeywordStartsWith("xxx")); CPPUNIT_ASSERT(!m_Lexer->MakeComment("test", true).empty()); CPPUNIT_ASSERT(!m_Lexer->MakeComment("test", "test").empty()); CPPUNIT_ASSERT(m_Lexer->SetKeywords("hello:1")); CPPUNIT_ASSERT(m_Lexer->SetKeywords("test11 test21:1 test31:1 test12:2 test22:2")); CPPUNIT_ASSERT(!m_Lexer->IsKeyword("class")); // now overwritten CPPUNIT_ASSERT(m_Lexer->IsKeyword("test11")); CPPUNIT_ASSERT(m_Lexer->IsKeyword("test21")); CPPUNIT_ASSERT(m_Lexer->IsKeyword("test12")); CPPUNIT_ASSERT(m_Lexer->IsKeyword("test22")); CPPUNIT_ASSERT(m_Lexer->KeywordStartsWith("te")); CPPUNIT_ASSERT(!m_Lexer->KeywordStartsWith("xx")); CPPUNIT_ASSERT(!m_Lexer->GetKeywords().empty()); CPPUNIT_ASSERT(!m_Lexer->GetKeywordsSet().empty()); // test wxExLexers CPPUNIT_ASSERT(!m_Lexers->BuildComboBox().empty()); CPPUNIT_ASSERT(!m_Lexers->BuildWildCards(wxFileName("test.h")).empty()); CPPUNIT_ASSERT(m_Lexers->Count() > 0); CPPUNIT_ASSERT(m_Lexers->FindByFileName(wxFileName("test.h")).GetScintillaLexer() == "cpp"); CPPUNIT_ASSERT(m_Lexers->FindByName("cpp").GetScintillaLexer() == "cpp"); CPPUNIT_ASSERT(m_Lexers->FindByText("// this is a cpp comment text").GetScintillaLexer() == "cpp"); CPPUNIT_ASSERT(!m_Lexers->GetIndicators().empty()); CPPUNIT_ASSERT(!m_Lexers->GetMarkers().empty()); CPPUNIT_ASSERT(!m_Lexers->GetStyles().empty()); CPPUNIT_ASSERT(!m_Lexers->GetStylesHex().empty()); // test wxExRCS CPPUNIT_ASSERT(m_RCS->GetDescription().empty()); CPPUNIT_ASSERT(m_RCS->GetUser().empty()); // test wxExStat CPPUNIT_ASSERT(!m_Stat->IsLink()); CPPUNIT_ASSERT(m_Stat->IsOk()); CPPUNIT_ASSERT(!m_Stat->IsReadOnly()); CPPUNIT_ASSERT(m_Stat->Update("testlink")); // CPPUNIT_ASSERT(m_Stat->IsLink()); // test wxExStatistics m_Statistics->Inc("test"); CPPUNIT_ASSERT(m_Statistics->Get("test") == 1); m_Statistics->Inc("test"); CPPUNIT_ASSERT(m_Statistics->Get("test") == 2); m_Statistics->Set("test", 13); CPPUNIT_ASSERT(m_Statistics->Get("test") == 13); m_Statistics->Dec("test"); CPPUNIT_ASSERT(m_Statistics->Get("test") == 12); m_Statistics->Inc("test2"); CPPUNIT_ASSERT(m_Statistics->Get("test2") == 1); m_Statistics->Clear(); CPPUNIT_ASSERT(m_Statistics->GetItems().empty()); // test wxExTextFile wxExTextFile textFile(wxExFileName("test.h"), ID_TOOL_REPORT_COUNT, m_Config, m_Lexers); CPPUNIT_ASSERT(textFile.RunTool()); CPPUNIT_ASSERT(!textFile.GetStatistics().GetElements().GetItems().empty()); CPPUNIT_ASSERT(!textFile.IsOpened()); // file should be closed after running tool CPPUNIT_ASSERT(textFile.RunTool()); // do the same test CPPUNIT_ASSERT(!textFile.GetStatistics().GetElements().GetItems().empty()); CPPUNIT_ASSERT(!textFile.IsOpened()); // file should be closed after running tool wxExTextFile textFile2(wxExFileName("test.h"), ID_TOOL_REPORT_KEYWORD, m_Config, m_Lexers); CPPUNIT_ASSERT(textFile2.RunTool()); // CPPUNIT_ASSERT(!m_TextFile->GetStatistics().GetKeywords().GetItems().empty()); // test wxExTool CPPUNIT_ASSERT(wxExTool(ID_TOOL_REPORT_COUNT).IsCount()); CPPUNIT_ASSERT(wxExTool(ID_TOOL_REPORT_FIND).IsFindType()); CPPUNIT_ASSERT(wxExTool(ID_TOOL_REPORT_REPLACE).IsFindType()); CPPUNIT_ASSERT(wxExTool(ID_TOOL_REPORT_COUNT).IsStatisticsType()); CPPUNIT_ASSERT(wxExTool(ID_TOOL_REPORT_COUNT).IsReportType()); CPPUNIT_ASSERT(wxExTool::GetToolInfo().empty()); // initialized by wxExApp, so not here // test various wxExMethods const wxString header = wxExHeader(textFile.GetFileName(), m_Config, "test"); CPPUNIT_ASSERT(header.Contains("test")); } void wxExTestFixture::testTiming() { wxExFile file("test.h"); CPPUNIT_ASSERT(file.IsOpened()); wxStopWatch sw; const int max = 10000; for (int i = 0; i < max; i++) { CPPUNIT_ASSERT(file.Read().length() > 0); } const long exfile_read = sw.Time(); sw.Start(); wxFile wxfile("test.h"); for (int j = 0; j < max; j++) { char* charbuffer = new char[wxfile.Length()]; wxfile.Read(charbuffer, wxfile.Length()); wxString* buffer = new wxString(charbuffer, wxfile.Length()); CPPUNIT_ASSERT(buffer->length() > 0); delete charbuffer; delete buffer; } const long file_read = sw.Time(); printf( "wxExFile::Read:%ld wxFile::Read:%ld\n", exfile_read, file_read); } void wxExTestFixture::testTimingAttrib() { const int max = 1000; wxStopWatch sw; const wxExFileName exfile("test.h"); int checked = 0; for (int i = 0; i < max; i++) { checked += exfile.GetStat().IsReadOnly(); } const long exfile_time = sw.Time(); sw.Start(); const wxFileName file("test.h"); for (int j = 0; j < max; j++) { checked += file.IsFileWritable(); } const long file_time = sw.Time(); printf( "wxExFileName::IsReadOnly:%ld wxFileName::IsFileWritable:%ld\n", exfile_time, file_time); } void wxExTestFixture::testTimingConfig() { const int max = 100000; wxStopWatch sw; for (int i = 0; i < max; i++) { m_Config->Get("test", 0); } const long exconfig = sw.Time(); sw.Start(); for (int j = 0; j < max; j++) { m_Config->Read("test", 0l); } const long config = sw.Time(); printf( "wxExConfig::Get:%ld wxConfig::Read:%ld\n", exconfig, config); } void wxExTestFixture::tearDown() { } wxExTestSuite::wxExTestSuite() : CppUnit::TestSuite("wxextension test suite") { // Add the tests. addTest(new CppUnit::TestCaller<wxExTestFixture>( "testConstructors", &wxExTestFixture::testConstructors)); addTest(new CppUnit::TestCaller<wxExTestFixture>( "testMethods", &wxExTestFixture::testMethods)); addTest(new CppUnit::TestCaller<wxExTestFixture>( "testTiming", &wxExTestFixture::testTiming)); addTest(new CppUnit::TestCaller<wxExTestFixture>( "testTimingAttrib", &wxExTestFixture::testTimingAttrib)); addTest(new CppUnit::TestCaller<wxExTestFixture>( "testTimingConfig", &wxExTestFixture::testTimingConfig)); } <|endoftext|>
<commit_before>///////////////////////////////////////////////////////////////////////////// // // BSD 3-Clause License // // Copyright (c) 2019, The Regents of the University of California // 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. // // * 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. // // * Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // 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 "MakeWireParasitics.h" #include "db_sta/dbNetwork.hh" #include "db_sta/dbSta.hh" #include "sta/ArcDelayCalc.hh" #include "sta/Corner.hh" #include "sta/Parasitics.hh" #include "sta/ParasiticsClass.hh" #include "sta/Sdc.hh" #include "sta/StaState.hh" #include "sta/Units.hh" #include "utl/Logger.h" namespace grt { using utl::GRT; using std::abs; using std::min; MakeWireParasitics::MakeWireParasitics(ord::OpenRoad* openroad, GlobalRouter* grouter) { grouter_ = grouter; logger_ = openroad->getLogger(); sta_ = openroad->getSta(); tech_ = openroad->getDb()->getTech(); parasitics_ = sta_->parasitics(); corner_ = sta_->cmdCorner(); min_max_ = sta::MinMax::max(); analysis_point_ = corner_->findParasiticAnalysisPt(min_max_); network_ = openroad->getDbNetwork(); sta_net_ = nullptr; parasitic_ = nullptr; node_id_ = 0; } void MakeWireParasitics::estimateParasitcs(odb::dbNet* net, std::vector<Pin>& pins, std::vector<GSegment>& routes) { debugPrint(logger_, GRT, "est_rc", 1, "net {}", net->getConstName()); sta_net_ = network_->dbToSta(net); node_id_ = 0; node_map_.clear(); parasitic_ = parasitics_->makeParasiticNetwork(sta_net_, false, analysis_point_); makePinRoutePts(pins); makeRouteParasitics(net, routes); makeParasiticsToGrid(pins); reduceParasiticNetwork(); } void MakeWireParasitics::makePinRoutePts(std::vector<Pin>& pins) { for (Pin& pin : pins) { sta::Pin* sta_pin = staPin(pin); sta::ParasiticNode* pin_node = parasitics_->ensureParasiticNode(parasitic_, sta_pin); RoutePt route_pt = routePt(pin); node_map_[route_pt] = pin_node; } } RoutePt MakeWireParasitics::routePt(Pin& pin) { const odb::Point& pt = pin.getPosition(); int layer = pin.getTopLayer(); return RoutePt(pt.getX(), pt.getY(), layer); } sta::Pin* MakeWireParasitics::staPin(Pin& pin) { if (pin.isPort()) return network_->dbToSta(pin.getBTerm()); else return network_->dbToSta(pin.getITerm()); } void MakeWireParasitics::makeRouteParasitics(odb::dbNet* net, std::vector<GSegment>& routes) { for (GSegment& route : routes) { sta::ParasiticNode* n1 = ensureParasiticNode(route.init_x, route.init_y, route.init_layer); sta::ParasiticNode* n2 = ensureParasiticNode(route.final_x, route.final_y, route.final_layer); int wire_length_dbu = abs(route.init_x - route.final_x) + abs(route.init_y - route.final_y); sta::Units* units = sta_->units(); float res = 0.0; float cap = 0.0; if (wire_length_dbu == 0) { // via int lower_layer = min(route.init_layer, route.final_layer); odb::dbTechLayer* cut_layer = tech_->findRoutingLayer(lower_layer)->getUpperLayer(); res = cut_layer->getResistance(); // assumes single cut cap = 0.0; debugPrint(logger_, GRT, "est_rc", 1, "{} -> {} via r={}", parasitics_->name(n1), parasitics_->name(n2), units->resistanceUnit()->asString(res)); } else if (route.init_layer == route.final_layer) { layerRC(wire_length_dbu, route.init_layer, res, cap); debugPrint(logger_, GRT, "est_rc", 1, "{} -> {} {}u layer={} r={} c={}", parasitics_->name(n1), parasitics_->name(n2), static_cast<int>(dbuToMeters(wire_length_dbu) * 1e+6), route.init_layer, units->resistanceUnit()->asString(res), units->capacitanceUnit()->asString(cap)); } else logger_->warn(GRT, 25, "Non wire or via route found on net {}.", net->getConstName()); parasitics_->incrCap(n1, cap / 2.0, analysis_point_); parasitics_->makeResistor(nullptr, n1, n2, res, analysis_point_); parasitics_->incrCap(n2, cap / 2.0, analysis_point_); } } void MakeWireParasitics::makeParasiticsToGrid(std::vector<Pin>& pins) { for (Pin& pin : pins) { RoutePt route_pt = routePt(pin); sta::ParasiticNode* pin_node = node_map_[route_pt]; makeParasiticsToGrid(pin, pin_node); } } // Make parasitics for the wire from the pin to the grid location of the pin. void MakeWireParasitics::makeParasiticsToGrid(Pin& pin, sta::ParasiticNode* pin_node) { const odb::Point& grid_pt = pin.getOnGridPosition(); int layer = pin.getTopLayer(); RoutePt route_pt(grid_pt.getX(), grid_pt.getY(), layer); sta::ParasiticNode* grid_node = node_map_[route_pt]; if (grid_node) { const odb::Point& pt = pin.getPosition(); int wire_length_dbu = abs(pt.getX() - grid_pt.getX()) + abs(pt.getY() - grid_pt.getY()); float res, cap; layerRC(wire_length_dbu, layer, res, cap); parasitics_->incrCap(pin_node, cap / 2.0, analysis_point_); parasitics_->makeResistor( nullptr, pin_node, grid_node, res, analysis_point_); parasitics_->incrCap(grid_node, cap / 2.0, analysis_point_); } else { logger_->warn(GRT, 26, "Missing route to pin {}.", pin.getName()); } } void MakeWireParasitics::layerRC(int wire_length_dbu, int layer_id, // Return values. float& res, float& cap) { odb::dbTechLayer* layer = tech_->findRoutingLayer(layer_id); float layer_width = grouter_->dbuToMicrons(layer->getWidth()); float res_ohm_per_micron = layer->getResistance() / layer_width; float cap_pf_per_micron = layer_width * layer->getCapacitance() + 2 * layer->getEdgeCapacitance(); float r_per_meter = 1E+6 * res_ohm_per_micron; // ohm/meter float cap_per_meter = 1E+6 * 1E-12 * cap_pf_per_micron; // F/meter float wire_length = dbuToMeters(wire_length_dbu); res = r_per_meter * wire_length; cap = cap_per_meter * wire_length; } double MakeWireParasitics::dbuToMeters(int dbu) { return (double) dbu / (tech_->getDbUnitsPerMicron() * 1E+6); } sta::ParasiticNode* MakeWireParasitics::ensureParasiticNode(int x, int y, int layer) { RoutePt pin_loc(x, y, layer); sta::ParasiticNode* node = node_map_[pin_loc]; if (node == nullptr) { node = parasitics_->ensureParasiticNode(parasitic_, sta_net_, node_id_++); node_map_[pin_loc] = node; } return node; } void MakeWireParasitics::reduceParasiticNetwork() { sta::Sdc* sdc = sta_->sdc(); sta::OperatingConditions* op_cond = sdc->operatingConditions(min_max_); sta::ReducedParasiticType reduce_to = sta_->arcDelayCalc()->reducedParasiticType(); parasitics_->reduceTo(parasitic_, sta_net_, reduce_to, op_cond, corner_, min_max_, analysis_point_); parasitics_->deleteParasiticNetwork(sta_net_, analysis_point_); } } // namespace grt <commit_msg>[GRT] Change RC debug precision; Add debug print<commit_after>///////////////////////////////////////////////////////////////////////////// // // BSD 3-Clause License // // Copyright (c) 2019, The Regents of the University of California // 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. // // * 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. // // * Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // 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 "MakeWireParasitics.h" #include "db_sta/dbNetwork.hh" #include "db_sta/dbSta.hh" #include "sta/ArcDelayCalc.hh" #include "sta/Corner.hh" #include "sta/Parasitics.hh" #include "sta/ParasiticsClass.hh" #include "sta/Sdc.hh" #include "sta/StaState.hh" #include "sta/Units.hh" #include "utl/Logger.h" namespace grt { using utl::GRT; using std::abs; using std::min; MakeWireParasitics::MakeWireParasitics(ord::OpenRoad* openroad, GlobalRouter* grouter) { grouter_ = grouter; logger_ = openroad->getLogger(); sta_ = openroad->getSta(); tech_ = openroad->getDb()->getTech(); parasitics_ = sta_->parasitics(); corner_ = sta_->cmdCorner(); min_max_ = sta::MinMax::max(); analysis_point_ = corner_->findParasiticAnalysisPt(min_max_); network_ = openroad->getDbNetwork(); sta_net_ = nullptr; parasitic_ = nullptr; node_id_ = 0; } void MakeWireParasitics::estimateParasitcs(odb::dbNet* net, std::vector<Pin>& pins, std::vector<GSegment>& routes) { debugPrint(logger_, GRT, "est_rc", 1, "net {}", net->getConstName()); sta_net_ = network_->dbToSta(net); node_id_ = 0; node_map_.clear(); parasitic_ = parasitics_->makeParasiticNetwork(sta_net_, false, analysis_point_); makePinRoutePts(pins); makeRouteParasitics(net, routes); makeParasiticsToGrid(pins); reduceParasiticNetwork(); } void MakeWireParasitics::makePinRoutePts(std::vector<Pin>& pins) { for (Pin& pin : pins) { sta::Pin* sta_pin = staPin(pin); sta::ParasiticNode* pin_node = parasitics_->ensureParasiticNode(parasitic_, sta_pin); RoutePt route_pt = routePt(pin); node_map_[route_pt] = pin_node; } } RoutePt MakeWireParasitics::routePt(Pin& pin) { const odb::Point& pt = pin.getPosition(); int layer = pin.getTopLayer(); return RoutePt(pt.getX(), pt.getY(), layer); } sta::Pin* MakeWireParasitics::staPin(Pin& pin) { if (pin.isPort()) return network_->dbToSta(pin.getBTerm()); else return network_->dbToSta(pin.getITerm()); } void MakeWireParasitics::makeRouteParasitics(odb::dbNet* net, std::vector<GSegment>& routes) { for (GSegment& route : routes) { sta::ParasiticNode* n1 = ensureParasiticNode(route.init_x, route.init_y, route.init_layer); sta::ParasiticNode* n2 = ensureParasiticNode(route.final_x, route.final_y, route.final_layer); int wire_length_dbu = abs(route.init_x - route.final_x) + abs(route.init_y - route.final_y); sta::Units* units = sta_->units(); float res = 0.0; float cap = 0.0; if (wire_length_dbu == 0) { // via int lower_layer = min(route.init_layer, route.final_layer); odb::dbTechLayer* cut_layer = tech_->findRoutingLayer(lower_layer)->getUpperLayer(); res = cut_layer->getResistance(); // assumes single cut cap = 0.0; debugPrint(logger_, GRT, "est_rc", 1, "{} -> {} via r={}", parasitics_->name(n1), parasitics_->name(n2), units->resistanceUnit()->asString(res)); } else if (route.init_layer == route.final_layer) { layerRC(wire_length_dbu, route.init_layer, res, cap); debugPrint(logger_, GRT, "est_rc", 1, "{} -> {} {}u layer={} r={} c={}", parasitics_->name(n1), parasitics_->name(n2), dbuToMeters(wire_length_dbu) * 1e+6, route.init_layer, units->resistanceUnit()->asString(res), units->capacitanceUnit()->asString(cap)); } else logger_->warn(GRT, 25, "Non wire or via route found on net {}.", net->getConstName()); parasitics_->incrCap(n1, cap / 2.0, analysis_point_); parasitics_->makeResistor(nullptr, n1, n2, res, analysis_point_); parasitics_->incrCap(n2, cap / 2.0, analysis_point_); } } void MakeWireParasitics::makeParasiticsToGrid(std::vector<Pin>& pins) { for (Pin& pin : pins) { RoutePt route_pt = routePt(pin); sta::ParasiticNode* pin_node = node_map_[route_pt]; makeParasiticsToGrid(pin, pin_node); } } // Make parasitics for the wire from the pin to the grid location of the pin. void MakeWireParasitics::makeParasiticsToGrid(Pin& pin, sta::ParasiticNode* pin_node) { const odb::Point& grid_pt = pin.getOnGridPosition(); int layer = pin.getTopLayer(); RoutePt route_pt(grid_pt.getX(), grid_pt.getY(), layer); sta::ParasiticNode* grid_node = node_map_[route_pt]; if (grid_node) { const odb::Point& pt = pin.getPosition(); int wire_length_dbu = abs(pt.getX() - grid_pt.getX()) + abs(pt.getY() - grid_pt.getY()); float res, cap; layerRC(wire_length_dbu, layer, res, cap); sta::Units* units = sta_->units(); debugPrint(logger_, GRT, "est_rc", 1, "{} -> {} {}u layer={} r={} c={}", parasitics_->name(grid_node), parasitics_->name(pin_node), dbuToMeters(wire_length_dbu) * 1e+6, layer, units->resistanceUnit()->asString(res), units->capacitanceUnit()->asString(cap)); parasitics_->incrCap(pin_node, cap / 2.0, analysis_point_); parasitics_->makeResistor( nullptr, pin_node, grid_node, res, analysis_point_); parasitics_->incrCap(grid_node, cap / 2.0, analysis_point_); } else { logger_->warn(GRT, 26, "Missing route to pin {}.", pin.getName()); } } void MakeWireParasitics::layerRC(int wire_length_dbu, int layer_id, // Return values. float& res, float& cap) { odb::dbTechLayer* layer = tech_->findRoutingLayer(layer_id); float layer_width = grouter_->dbuToMicrons(layer->getWidth()); float res_ohm_per_micron = layer->getResistance() / layer_width; float cap_pf_per_micron = layer_width * layer->getCapacitance() + 2 * layer->getEdgeCapacitance(); float r_per_meter = 1E+6 * res_ohm_per_micron; // ohm/meter float cap_per_meter = 1E+6 * 1E-12 * cap_pf_per_micron; // F/meter float wire_length = dbuToMeters(wire_length_dbu); res = r_per_meter * wire_length; cap = cap_per_meter * wire_length; } double MakeWireParasitics::dbuToMeters(int dbu) { return (double) dbu / (tech_->getDbUnitsPerMicron() * 1E+6); } sta::ParasiticNode* MakeWireParasitics::ensureParasiticNode(int x, int y, int layer) { RoutePt pin_loc(x, y, layer); sta::ParasiticNode* node = node_map_[pin_loc]; if (node == nullptr) { node = parasitics_->ensureParasiticNode(parasitic_, sta_net_, node_id_++); node_map_[pin_loc] = node; } return node; } void MakeWireParasitics::reduceParasiticNetwork() { sta::Sdc* sdc = sta_->sdc(); sta::OperatingConditions* op_cond = sdc->operatingConditions(min_max_); sta::ReducedParasiticType reduce_to = sta_->arcDelayCalc()->reducedParasiticType(); parasitics_->reduceTo(parasitic_, sta_net_, reduce_to, op_cond, corner_, min_max_, analysis_point_); parasitics_->deleteParasiticNetwork(sta_net_, analysis_point_); } } // namespace grt <|endoftext|>
<commit_before>// Copyright (c) 2013, German Neuroinformatics Node (G-Node) // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted under the terms of the BSD License. See // LICENSE file in the root of the Project. #include <nix/hdf5/EntityWithSourcesHDF5.hpp> #include <nix/util/util.hpp> #include <nix/Block.hpp> #include <algorithm> #include <functional> using namespace nix::base; namespace nix { namespace hdf5 { EntityWithSourcesHDF5::EntityWithSourcesHDF5(const std::shared_ptr<IFile> &file, const std::shared_ptr<IBlock> &block, const H5Group &group) : EntityWithMetadataHDF5(file, group), entity_block(block) { sources_refs = this->group().openOptGroup("sources"); } EntityWithSourcesHDF5::EntityWithSourcesHDF5(const std::shared_ptr<IFile> &file, const std::shared_ptr<IBlock> &block, const H5Group &group, const std::string &id, const std::string &type, const std::string &name) : EntityWithSourcesHDF5(file, block, group, id, type, name, util::getTime()) { } EntityWithSourcesHDF5::EntityWithSourcesHDF5 (const std::shared_ptr<IFile> &file, const std::shared_ptr<IBlock> &block, const H5Group &group, const std::string &id, const std::string &type, const std::string &name, time_t time) : EntityWithMetadataHDF5(file, group, id, type, name, time), entity_block(block) { sources_refs = this->group().openOptGroup("sources"); } ndsize_t EntityWithSourcesHDF5::sourceCount() const { boost::optional<H5Group> g = sources_refs(false); return g ? g->objectCount() : size_t(0); } bool EntityWithSourcesHDF5::hasSource(const std::string &id) const { return sources_refs(false) ? sources_refs(false)->hasGroup(id) : false; } std::shared_ptr<ISource> EntityWithSourcesHDF5::getSource(const std::string &name_or_id) const { std::shared_ptr<SourceHDF5> source; boost::optional<H5Group> g = sources_refs(false); std::string id = name_or_id; if (!util::looksLikeUUID(name_or_id)) { Block tmp(entity_block); auto found = tmp.findSources(util::NameFilter<Source>(name_or_id)); if (!found.empty()) id = found.front().id(); } if (g && hasSource(id)) { H5Group group = g->openGroup(id); source = std::make_shared<SourceHDF5>(file(), group); } return source; } std::shared_ptr<ISource> EntityWithSourcesHDF5::getSource(const size_t index) const { boost::optional<H5Group> g = sources_refs(false); std::string id = g ? g->objectName(index) : ""; return getSource(id); } void EntityWithSourcesHDF5::sources(const std::vector<Source> &sources) { // extract vectors of ids from vectors of new & old sources std::vector<std::string> ids_new(sources.size()); std::transform(sources.begin(), sources.end(), ids_new.begin(), util::toId<Source>); std::vector<Source> sources_old(static_cast<size_t>(sourceCount())); for (size_t i = 0; i < sources_old.size(); i++) sources_old[i] = getSource(i); std::vector<std::string> ids_old(sources_old.size()); std::transform(sources_old.begin(), sources_old.end(), ids_old.begin(), util::toId<Source>); // sort them std::sort(ids_new.begin(), ids_new.end()); std::sort(ids_old.begin(), ids_old.end()); // get ids only in ids_new (add), ids only in ids_old (remove) & ignore rest std::vector<std::string> ids_add; std::vector<std::string> ids_rem; std::set_difference(ids_new.begin(), ids_new.end(), ids_old.begin(), ids_old.end(), std::inserter(ids_add, ids_add.begin())); std::set_difference(ids_old.begin(), ids_old.end(), ids_new.begin(), ids_new.end(), std::inserter(ids_rem, ids_rem.begin())); // check if all new sources exist Block tmp(entity_block); auto found = tmp.findSources(util::IdsFilter<Source>(ids_add)); if (ids_add.size() != found.size()) throw std::runtime_error("One or more sources do not exist in this block!"); // add sources for (auto id : ids_add) { addSource(id); } // remove sources for (auto id : ids_rem) { removeSource(id); } } void EntityWithSourcesHDF5::addSource(const std::string &id) { if (id.empty()) throw EmptyString("addSource"); boost::optional<H5Group> g = sources_refs(true); Block tmp(entity_block); auto found = tmp.findSources(util::IdFilter<Source>(id)); if (found.empty()) throw std::runtime_error("EntityWithSourcesHDF5::addSource: Given source does not exist in this block!"); auto target = std::dynamic_pointer_cast<SourceHDF5>(found.front().impl()); g->createLink(target->group(), id); } bool EntityWithSourcesHDF5::removeSource(const std::string &id) { boost::optional<H5Group> g = sources_refs(false); bool removed = false; if (g) { g->removeGroup(id); removed = true; } return removed; } std::shared_ptr<base::IBlock> EntityWithSourcesHDF5::block() const { return entity_block; } EntityWithSourcesHDF5::~EntityWithSourcesHDF5() {} } // ns nix::hdf5 } // ns nix<commit_msg>fix fixme 473 in EntityWithSources<commit_after>// Copyright (c) 2013, German Neuroinformatics Node (G-Node) // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted under the terms of the BSD License. See // LICENSE file in the root of the Project. #include <nix/hdf5/EntityWithSourcesHDF5.hpp> #include <nix/util/util.hpp> #include <nix/Block.hpp> #include <algorithm> #include <functional> using namespace nix::base; namespace nix { namespace hdf5 { EntityWithSourcesHDF5::EntityWithSourcesHDF5(const std::shared_ptr<IFile> &file, const std::shared_ptr<IBlock> &block, const H5Group &group) : EntityWithMetadataHDF5(file, group), entity_block(block) { sources_refs = this->group().openOptGroup("sources"); } EntityWithSourcesHDF5::EntityWithSourcesHDF5(const std::shared_ptr<IFile> &file, const std::shared_ptr<IBlock> &block, const H5Group &group, const std::string &id, const std::string &type, const std::string &name) : EntityWithSourcesHDF5(file, block, group, id, type, name, util::getTime()) { } EntityWithSourcesHDF5::EntityWithSourcesHDF5 (const std::shared_ptr<IFile> &file, const std::shared_ptr<IBlock> &block, const H5Group &group, const std::string &id, const std::string &type, const std::string &name, time_t time) : EntityWithMetadataHDF5(file, group, id, type, name, time), entity_block(block) { sources_refs = this->group().openOptGroup("sources"); } ndsize_t EntityWithSourcesHDF5::sourceCount() const { boost::optional<H5Group> g = sources_refs(false); return g ? g->objectCount() : size_t(0); } bool EntityWithSourcesHDF5::hasSource(const std::string &id) const { return sources_refs(false) ? sources_refs(false)->hasGroup(id) : false; } std::shared_ptr<ISource> EntityWithSourcesHDF5::getSource(const std::string &name_or_id) const { std::shared_ptr<SourceHDF5> source; boost::optional<H5Group> g = sources_refs(false); std::string id = name_or_id; if (!util::looksLikeUUID(name_or_id)) { Block tmp(entity_block); auto found = tmp.findSources(util::NameFilter<Source>(name_or_id)); if (!found.empty()) id = found.front().id(); } if (g && hasSource(id)) { H5Group group = g->openGroup(id); source = std::make_shared<SourceHDF5>(file(), group); } return source; } std::shared_ptr<ISource> EntityWithSourcesHDF5::getSource(const size_t index) const { boost::optional<H5Group> g = sources_refs(false); std::string id = g ? g->objectName(index) : ""; return getSource(id); } void EntityWithSourcesHDF5::sources(const std::vector<Source> &sources) { // extract vectors of ids from vectors of new & old sources std::vector<std::string> ids_new(sources.size()); std::transform(sources.begin(), sources.end(), ids_new.begin(), util::toId<Source>); size_t src_count = nix::check::fits_in_size_t(sourceCount(), "sourceCount() failed, count > size_t!"); std::vector<Source> sources_old(src_count); for (size_t i = 0; i < sources_old.size(); i++) sources_old[i] = getSource(i); std::vector<std::string> ids_old(sources_old.size()); std::transform(sources_old.begin(), sources_old.end(), ids_old.begin(), util::toId<Source>); // sort them std::sort(ids_new.begin(), ids_new.end()); std::sort(ids_old.begin(), ids_old.end()); // get ids only in ids_new (add), ids only in ids_old (remove) & ignore rest std::vector<std::string> ids_add; std::vector<std::string> ids_rem; std::set_difference(ids_new.begin(), ids_new.end(), ids_old.begin(), ids_old.end(), std::inserter(ids_add, ids_add.begin())); std::set_difference(ids_old.begin(), ids_old.end(), ids_new.begin(), ids_new.end(), std::inserter(ids_rem, ids_rem.begin())); // check if all new sources exist Block tmp(entity_block); auto found = tmp.findSources(util::IdsFilter<Source>(ids_add)); if (ids_add.size() != found.size()) throw std::runtime_error("One or more sources do not exist in this block!"); // add sources for (auto id : ids_add) { addSource(id); } // remove sources for (auto id : ids_rem) { removeSource(id); } } void EntityWithSourcesHDF5::addSource(const std::string &id) { if (id.empty()) throw EmptyString("addSource"); boost::optional<H5Group> g = sources_refs(true); Block tmp(entity_block); auto found = tmp.findSources(util::IdFilter<Source>(id)); if (found.empty()) throw std::runtime_error("EntityWithSourcesHDF5::addSource: Given source does not exist in this block!"); auto target = std::dynamic_pointer_cast<SourceHDF5>(found.front().impl()); g->createLink(target->group(), id); } bool EntityWithSourcesHDF5::removeSource(const std::string &id) { boost::optional<H5Group> g = sources_refs(false); bool removed = false; if (g) { g->removeGroup(id); removed = true; } return removed; } std::shared_ptr<base::IBlock> EntityWithSourcesHDF5::block() const { return entity_block; } EntityWithSourcesHDF5::~EntityWithSourcesHDF5() {} } // ns nix::hdf5 } // ns nix<|endoftext|>
<commit_before>// Copyright 2016-2019 Jean-Francois Poilpret // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /* * This is a skeleton program to help connect, debug and understand how a given * I2C device (not already supported by FastArduino) works. * That helps creating a new specific support API for that device for reuse in * other programs and potential integration to FastArduino project. * To ease wiring and debugging, I suggest using a real Arduino board (I typically * use UNO) and a small breadboard for connecting the I2C device. * * Wiring: * NB: you should add pullup resistors (10K-22K typically) on both SDA and SCL lines. * - on ATmega328P based boards (including Arduino UNO): * - A4 (PC4, SDA): connected to DS1307 SDA pin * - A5 (PC5, SCL): connected to DS1307 SCL pin * - direct USB access (traces output) * - on Arduino LEONARDO: * - D2 (PD1, SDA): connected to DS1307 SDA pin * - D3 (PD0, SCL): connected to DS1307 SDA pin * - direct USB access (traces output) * - on Arduino MEGA: * - D20 (PD1, SDA): connected to DS1307 SDA pin * - D21 (PD0, SCL): connected to DS1307 SDA pin * - direct USB access (traces output) */ #include <fastarduino/time.h> #include <fastarduino/i2c_device.h> #include <fastarduino/utilities.h> #include <fastarduino/uart.h> #include <math.h> static constexpr const uint8_t OUTPUT_BUFFER_SIZE = 64; // Define vectors we need in the example REGISTER_UATX_ISR(0) // UART for traces static char output_buffer[OUTPUT_BUFFER_SIZE]; static serial::hard::UATX<board::USART::USART0> uart{output_buffer}; static streams::ostream out = uart.out(); // I2C Device specific stuff goes here //===================================== static constexpr const i2c::I2CMode MODE = i2c::I2CMode::FAST; static constexpr const uint8_t DEVICE_ADDRESS = 0x68 << 1; // Subclass I2CDevice to make protected methods available class PublicDevice: public i2c::I2CDevice<MODE> { public: PublicDevice(MANAGER& manager): I2CDevice(manager) {} friend int main(); }; using streams::endl; using streams::dec; using streams::hex; void trace_i2c_status(uint8_t expected_status, uint8_t actual_status) { if (expected_status != actual_status) out << F("status expected = ") << expected_status << F(", actual = ") << actual_status << endl; } int main() __attribute__((OS_main)); int main() { board::init(); sei(); uart.begin(115200); out.width(2); // Start TWI interface //==================== PublicDevice::MANAGER manager{trace_i2c_status}; manager.begin(); out << F("I2C interface started") << endl; PublicDevice device{manager}; // Init I2C device if needed // Loop to show measures while (true) { // Read measures and display them to UART time::delay_ms(1000); } // Stop TWI interface //=================== manager.end(); out << F("End") << endl; } <commit_msg>Simplify I2C device proto example.<commit_after>// Copyright 2016-2019 Jean-Francois Poilpret // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /* * This is a skeleton program to help connect, debug and understand how a given * I2C device (not already supported by FastArduino) works. * That helps creating a new specific support API for that device for reuse in * other programs and potential integration to FastArduino project. * To ease wiring and debugging, I suggest using a real Arduino board (I typically * use UNO) and a small breadboard for connecting the I2C device. * * Wiring: * NB: you should add pullup resistors (10K-22K typically) on both SDA and SCL lines. * - on Arduino UNO: * - A4 (PC4, SDA): connected to DS1307 SDA pin * - A5 (PC5, SCL): connected to DS1307 SCL pin * - direct USB access (traces output) */ #include <fastarduino/time.h> #include <fastarduino/i2c_device.h> #include <fastarduino/utilities.h> #include <fastarduino/uart.h> // Define vectors we need in the example REGISTER_UATX_ISR(0) // UART for traces static constexpr const uint8_t OUTPUT_BUFFER_SIZE = 64; static char output_buffer[OUTPUT_BUFFER_SIZE]; static serial::hard::UATX<board::USART::USART0> uart{output_buffer}; static streams::ostream out = uart.out(); // I2C Device specific stuff goes here //===================================== static constexpr const i2c::I2CMode MODE = i2c::I2CMode::FAST; static constexpr const uint8_t DEVICE_ADDRESS = 0x68 << 1; // Subclass I2CDevice to make protected methods available class PublicDevice: public i2c::I2CDevice<MODE> { public: PublicDevice(MANAGER& manager): I2CDevice(manager) {} friend int main(); }; using streams::endl; using streams::dec; using streams::hex; void trace_i2c_status(uint8_t expected_status, uint8_t actual_status) { if (expected_status != actual_status) out << F("status expected = ") << expected_status << F(", actual = ") << actual_status << endl; } int main() { board::init(); sei(); uart.begin(115200); out.width(2); // Start TWI interface //==================== PublicDevice::MANAGER manager{trace_i2c_status}; manager.begin(); out << F("I2C interface started") << endl; PublicDevice device{manager}; // Init I2C device if needed // Loop to show measures while (true) { // Read measures and display them to UART time::delay_ms(1000); } // Stop TWI interface //=================== manager.end(); out << F("End") << endl; } <|endoftext|>
<commit_before>/* Source File : PDFModifiedPage.cpp Copyright 2013 Gal Kahana PDFWriter Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "PDFModifiedPage.h" #include "AbstractContentContext.h" #include "PDFFormXObject.h" #include "XObjectContentContext.h" #include "PDFWriter.h" #include "PDFParser.h" #include "PDFPageInput.h" #include "PDFDictionary.h" #include "PDFDocumentCopyingContext.h" #include "PDFObjectCast.h" #include "RefCountPtr.h" #include "DictionaryContext.h" #include "PDFIndirectObjectReference.h" #include "PDFArray.h" #include "BoxingBase.h" #include "PDFStream.h" #include "PDFObject.h" #include <string> using namespace std; PDFModifiedPage::PDFModifiedPage(PDFWriter* inWriter,unsigned long inPageIndex,bool inEnsureContentEncapsulation) { mWriter = inWriter; mPageIndex = inPageIndex; mCurrentContext = NULL; mEnsureContentEncapsulation = inEnsureContentEncapsulation; } PDFModifiedPage::~PDFModifiedPage(void) { } AbstractContentContext* PDFModifiedPage::StartContentContext() { if(!mCurrentContext) { PDFRectangle mediaBox = PDFPageInput(&mWriter->GetModifiedFileParser(),mWriter->GetModifiedFileParser().ParsePage(mPageIndex)).GetMediaBox(); mCurrentContext = mWriter->StartFormXObject(mediaBox); } return mCurrentContext->GetContentContext(); } PDFHummus::EStatusCode PDFModifiedPage::PauseContentContext() { // does the same return EndContentContext(); } PDFHummus::EStatusCode PDFModifiedPage::EndContentContext() { EStatusCode status = mWriter->EndFormXObject(mCurrentContext); mContenxts.push_back(mCurrentContext); mCurrentContext = NULL; return status; } AbstractContentContext* PDFModifiedPage::GetContentContext() { return mCurrentContext ? mCurrentContext->GetContentContext():NULL; } PDFHummus::EStatusCode PDFModifiedPage::AttachURLLinktoCurrentPage(const std::string& inURL, const PDFRectangle& inLinkClickArea) { return mWriter->GetDocumentContext().AttachURLLinktoCurrentPage(inURL, inLinkClickArea); } PDFHummus::EStatusCode PDFModifiedPage::WritePage() { // allocate an object ID for the new contents stream (for placing the form) // we first create the modified page object, so that we can define a name for the new form xobject // that is unique ObjectsContext& objectContext = mWriter->GetObjectsContext(); ObjectIDType newContentObjectID = objectContext.GetInDirectObjectsRegistry().AllocateNewObjectID(); ObjectIDType newEncapsulatingObjectID = 0; // create a copying context, so we can copy the page dictionary, and modify its contents + resources dict PDFDocumentCopyingContext* copyingContext = mWriter->CreatePDFCopyingContextForModifiedFile(); // get the page object ObjectIDType pageObjectID = copyingContext->GetSourceDocumentParser()->GetPageObjectID(mPageIndex); PDFObjectCastPtr<PDFDictionary> pageDictionaryObject = copyingContext->GetSourceDocumentParser()->ParsePage(mPageIndex); MapIterator<PDFNameToPDFObjectMap> pageDictionaryObjectIt = pageDictionaryObject->GetIterator(); // create modified page object objectContext.StartModifiedIndirectObject(pageObjectID); DictionaryContext* modifiedPageObject = mWriter->GetObjectsContext().StartDictionary(); // copy all elements of the page to the new page object, but the "Contents", "Resources" and "Annots" elements while(pageDictionaryObjectIt.MoveNext()) { if(pageDictionaryObjectIt.GetKey()->GetValue() != "Resources" && pageDictionaryObjectIt.GetKey()->GetValue() != "Contents" && pageDictionaryObjectIt.GetKey()->GetValue() != "Annots" ) { modifiedPageObject->WriteKey(pageDictionaryObjectIt.GetKey()->GetValue()); copyingContext->CopyDirectObjectAsIs(pageDictionaryObjectIt.GetValue()); } } // Write new annotations entry, joining existing annotations, and new ones (from links attaching or what not) if (!!pageDictionaryObject->Exists("Annots") || mWriter->GetDocumentContext().GetAnnotations().size() > 0) { modifiedPageObject->WriteKey("Annots"); objectContext.StartArray(); // write old annots, if any exist PDFObjectCastPtr<PDFArray> anArray(copyingContext->GetSourceDocumentParser()->QueryDictionaryObject(pageDictionaryObject.GetPtr(),"Annots")); SingleValueContainerIterator<PDFObjectVector> refs = anArray->GetIterator(); PDFObjectCastPtr<PDFIndirectObjectReference> ref; while (refs.MoveNext()) { ref = refs.GetItem(); objectContext.WriteIndirectObjectReference(ref->mObjectID, ref->mVersion); } // write new annots from links ObjectIDTypeSet& annotations = mWriter->GetDocumentContext().GetAnnotations(); if (annotations.size() > 0) { ObjectIDTypeSet::iterator it = annotations.begin(); for (; it != annotations.end(); ++it) objectContext.WriteNewIndirectObjectReference(*it); } annotations.clear(); objectContext.EndArray(eTokenSeparatorEndLine); } // Write new contents entry, joining the existing contents with the new one. take care of various scenarios of the existing Contents modifiedPageObject->WriteKey("Contents"); if(!pageDictionaryObject->Exists("Contents")) { // no contents objectContext.WriteIndirectObjectReference(newContentObjectID); } else { objectContext.StartArray(); if (mEnsureContentEncapsulation) { newEncapsulatingObjectID = objectContext.GetInDirectObjectsRegistry().AllocateNewObjectID(); objectContext.WriteNewIndirectObjectReference(newEncapsulatingObjectID); } RefCountPtr<PDFObject> pageContent(copyingContext->GetSourceDocumentParser()->QueryDictionaryObject(pageDictionaryObject.GetPtr(), "Contents")); if (pageContent->GetType() == PDFObject::ePDFObjectStream) { // single content stream. must be a refrence which points to it PDFObjectCastPtr<PDFIndirectObjectReference> ref(pageDictionaryObject->QueryDirectObject("Contents")); objectContext.WriteIndirectObjectReference(ref->mObjectID, ref->mVersion); } else if (pageContent->GetType() == PDFObject::ePDFObjectArray) { PDFArray* anArray = (PDFArray*)pageContent.GetPtr(); // multiple content streams SingleValueContainerIterator<PDFObjectVector> refs = anArray->GetIterator(); PDFObjectCastPtr<PDFIndirectObjectReference> ref; while (refs.MoveNext()) { ref = refs.GetItem(); objectContext.WriteIndirectObjectReference(ref->mObjectID, ref->mVersion); } } else { // this basically means no content...or whatever. just ignore. } objectContext.WriteNewIndirectObjectReference(newContentObjectID); objectContext.EndArray(); objectContext.EndLine(); } // Write a new resource entry. copy all but the "XObject" entry, which needs to be modified. Just for kicks i'm keeping the original // form (either direct dictionary, or indirect object) ObjectIDType resourcesIndirect = 0; ObjectIDType newResourcesIndirect = 0; vector<string> formResourcesNames; modifiedPageObject->WriteKey("Resources"); if(!pageDictionaryObject->Exists("Resources")) { // no existing resource dictionary, so write a new one DictionaryContext* dict = objectContext.StartDictionary(); dict->WriteKey("XObject"); DictionaryContext* xobjectDict = objectContext.StartDictionary(); for(unsigned long i=0;i<mContenxts.size();++i) { string formObjectName = string("myForm_") + Int(i).ToString(); dict->WriteKey(formObjectName); dict->WriteObjectReferenceValue(mContenxts[i]->GetObjectID()); formResourcesNames.push_back(formObjectName); } objectContext.EndDictionary(xobjectDict); objectContext.EndDictionary(dict); } else { // resources may be direct, or indirect. if direct, write as is, adding the new form xobject, otherwise wait till page object ends and write then PDFObjectCastPtr<PDFIndirectObjectReference> resourceDictRef(pageDictionaryObject->QueryDirectObject("Resources")); if(!resourceDictRef) { PDFObjectCastPtr<PDFDictionary> resourceDict(pageDictionaryObject->QueryDirectObject("Resources")); formResourcesNames = WriteModifiedResourcesDict(copyingContext->GetSourceDocumentParser(),resourceDict.GetPtr(),objectContext,copyingContext); } else { resourcesIndirect = resourceDictRef->mObjectID; // later will write a modified version of the resources dictionary, with the new form. // only modify the resources dict object if wasn't already modified (can happen when sharing resources dict between multiple pages). // in the case where it was alrady modified, create a new resources dictionary that's a copy, and use it instead, to avoid overwriting // the previous modification GetObjectWriteInformationResult res = objectContext.GetInDirectObjectsRegistry().GetObjectWriteInformation(resourcesIndirect); if(res.first && res.second.mIsDirty) { newResourcesIndirect = objectContext.GetInDirectObjectsRegistry().AllocateNewObjectID(); modifiedPageObject->WriteObjectReferenceValue(newResourcesIndirect); } else modifiedPageObject->WriteObjectReferenceValue(resourcesIndirect); } } objectContext.EndDictionary(modifiedPageObject); objectContext.EndIndirectObject(); if(resourcesIndirect!=0) { if(newResourcesIndirect != 0) objectContext.StartNewIndirectObject(newResourcesIndirect); else objectContext.StartModifiedIndirectObject(resourcesIndirect); PDFObjectCastPtr<PDFDictionary> resourceDict(copyingContext->GetSourceDocumentParser()->ParseNewObject(resourcesIndirect)); formResourcesNames = WriteModifiedResourcesDict(copyingContext->GetSourceDocumentParser(),resourceDict.GetPtr(),objectContext,copyingContext); objectContext.EndIndirectObject(); } // if required write encapsulation code, so that new stream is independent of graphic context of original PDFStream* newStream; PrimitiveObjectsWriter primitivesWriter; if (newEncapsulatingObjectID != 0) { objectContext.StartNewIndirectObject(newEncapsulatingObjectID); newStream = objectContext.StartPDFStream(); primitivesWriter.SetStreamForWriting(newStream->GetWriteStream()); primitivesWriter.WriteKeyword("q"); objectContext.EndPDFStream(newStream); } // last but not least, create the actual content stream object, placing the form objectContext.StartNewIndirectObject(newContentObjectID); newStream = objectContext.StartPDFStream(); primitivesWriter.SetStreamForWriting(newStream->GetWriteStream()); if (newEncapsulatingObjectID != 0) { primitivesWriter.WriteKeyword("Q"); } vector<string>::iterator it = formResourcesNames.begin(); for(;it!=formResourcesNames.end();++it) { primitivesWriter.WriteKeyword("q"); primitivesWriter.WriteInteger(1); primitivesWriter.WriteInteger(0); primitivesWriter.WriteInteger(0); primitivesWriter.WriteInteger(1); primitivesWriter.WriteInteger(0); primitivesWriter.WriteInteger(0); primitivesWriter.WriteKeyword("cm"); primitivesWriter.WriteName(*it); primitivesWriter.WriteKeyword("Do"); primitivesWriter.WriteKeyword("Q"); } objectContext.EndPDFStream(newStream); return eSuccess; } vector<string> PDFModifiedPage::WriteModifiedResourcesDict(PDFParser* inParser,PDFDictionary* inResourcesDictionary,ObjectsContext& inObjectContext,PDFDocumentCopyingContext* inCopyingContext) { vector<string> formResourcesNames; MapIterator<PDFNameToPDFObjectMap> resourcesDictionaryIt = inResourcesDictionary->GetIterator(); // create modified page object DictionaryContext* dict = mWriter->GetObjectsContext().StartDictionary(); // copy all elements of the page to the new page object, but the "Contents" and "Resources" elements while(resourcesDictionaryIt.MoveNext()) { if(resourcesDictionaryIt.GetKey()->GetValue() != "XObject") { dict->WriteKey(resourcesDictionaryIt.GetKey()->GetValue()); inCopyingContext->CopyDirectObjectAsIs(resourcesDictionaryIt.GetValue()); } } // now write a new xobject entry. dict->WriteKey("XObject"); DictionaryContext* xobjectDict = inObjectContext.StartDictionary(); PDFObjectCastPtr<PDFDictionary> existingXObjectDict(inParser->QueryDictionaryObject(inResourcesDictionary,"XObject")); string imageObjectName; if(existingXObjectDict.GetPtr()) { // i'm having a very sophisticated algo here to create a new unique name. // i'm making sure it's different in one letter from any name, using a well known discrete math proof method MapIterator<PDFNameToPDFObjectMap> itExisting = existingXObjectDict->GetIterator(); unsigned long i=0; while(itExisting.MoveNext()) { string name = itExisting.GetKey()->GetValue(); xobjectDict->WriteKey(name); inCopyingContext->CopyDirectObjectAsIs(itExisting.GetValue()); imageObjectName.push_back((char)(GetDifferentChar((name.length() >= i+1) ? name[i]:0x39))); ++i; } inObjectContext.EndLine(); } PDFFormXObjectVector::iterator itForms = mContenxts.begin(); imageObjectName.push_back('_'); for(int i=0;itForms != mContenxts.end();++i,++itForms) { string formObjectName = imageObjectName + Int(i).ToString(); xobjectDict->WriteKey(formObjectName); xobjectDict->WriteObjectReferenceValue((*itForms)->GetObjectID()); formResourcesNames.push_back(formObjectName); } inObjectContext.EndDictionary(xobjectDict); inObjectContext.EndDictionary(dict); return formResourcesNames; } unsigned char PDFModifiedPage::GetDifferentChar(unsigned char inCharCode) { // numerals if(inCharCode >= 0x30 && inCharCode <= 0x38) return inCharCode+1; if(inCharCode == 0x39) return 0x30; // lowercase if(inCharCode >= 0x61 && inCharCode <= 0x79) return inCharCode+1; if(inCharCode == 0x7a) return 0x61; // uppercase if(inCharCode >= 0x41 && inCharCode <= 0x59) return inCharCode+1; if(inCharCode == 0x5a) return 0x41; return 0x41; } PDFFormXObject* PDFModifiedPage::GetCurrentFormContext() { return mCurrentContext; } ResourcesDictionary* PDFModifiedPage::GetCurrentResourcesDictionary() { return mCurrentContext ? &(mCurrentContext->GetResourcesDictionary()):NULL; } <commit_msg>bug fix in page annotations copying. should just stick to simple copying<commit_after>/* Source File : PDFModifiedPage.cpp Copyright 2013 Gal Kahana PDFWriter Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "PDFModifiedPage.h" #include "AbstractContentContext.h" #include "PDFFormXObject.h" #include "XObjectContentContext.h" #include "PDFWriter.h" #include "PDFParser.h" #include "PDFPageInput.h" #include "PDFDictionary.h" #include "PDFDocumentCopyingContext.h" #include "PDFObjectCast.h" #include "RefCountPtr.h" #include "DictionaryContext.h" #include "PDFIndirectObjectReference.h" #include "PDFArray.h" #include "BoxingBase.h" #include "PDFStream.h" #include "PDFObject.h" #include <string> using namespace std; PDFModifiedPage::PDFModifiedPage(PDFWriter* inWriter,unsigned long inPageIndex,bool inEnsureContentEncapsulation) { mWriter = inWriter; mPageIndex = inPageIndex; mCurrentContext = NULL; mEnsureContentEncapsulation = inEnsureContentEncapsulation; } PDFModifiedPage::~PDFModifiedPage(void) { } AbstractContentContext* PDFModifiedPage::StartContentContext() { if(!mCurrentContext) { PDFRectangle mediaBox = PDFPageInput(&mWriter->GetModifiedFileParser(),mWriter->GetModifiedFileParser().ParsePage(mPageIndex)).GetMediaBox(); mCurrentContext = mWriter->StartFormXObject(mediaBox); } return mCurrentContext->GetContentContext(); } PDFHummus::EStatusCode PDFModifiedPage::PauseContentContext() { // does the same return EndContentContext(); } PDFHummus::EStatusCode PDFModifiedPage::EndContentContext() { EStatusCode status = mWriter->EndFormXObject(mCurrentContext); mContenxts.push_back(mCurrentContext); mCurrentContext = NULL; return status; } AbstractContentContext* PDFModifiedPage::GetContentContext() { return mCurrentContext ? mCurrentContext->GetContentContext():NULL; } PDFHummus::EStatusCode PDFModifiedPage::AttachURLLinktoCurrentPage(const std::string& inURL, const PDFRectangle& inLinkClickArea) { return mWriter->GetDocumentContext().AttachURLLinktoCurrentPage(inURL, inLinkClickArea); } PDFHummus::EStatusCode PDFModifiedPage::WritePage() { // allocate an object ID for the new contents stream (for placing the form) // we first create the modified page object, so that we can define a name for the new form xobject // that is unique ObjectsContext& objectContext = mWriter->GetObjectsContext(); ObjectIDType newContentObjectID = objectContext.GetInDirectObjectsRegistry().AllocateNewObjectID(); ObjectIDType newEncapsulatingObjectID = 0; // create a copying context, so we can copy the page dictionary, and modify its contents + resources dict PDFDocumentCopyingContext* copyingContext = mWriter->CreatePDFCopyingContextForModifiedFile(); // get the page object ObjectIDType pageObjectID = copyingContext->GetSourceDocumentParser()->GetPageObjectID(mPageIndex); PDFObjectCastPtr<PDFDictionary> pageDictionaryObject = copyingContext->GetSourceDocumentParser()->ParsePage(mPageIndex); MapIterator<PDFNameToPDFObjectMap> pageDictionaryObjectIt = pageDictionaryObject->GetIterator(); // create modified page object objectContext.StartModifiedIndirectObject(pageObjectID); DictionaryContext* modifiedPageObject = mWriter->GetObjectsContext().StartDictionary(); // copy all elements of the page to the new page object, but the "Contents", "Resources" and "Annots" elements while(pageDictionaryObjectIt.MoveNext()) { if(pageDictionaryObjectIt.GetKey()->GetValue() != "Resources" && pageDictionaryObjectIt.GetKey()->GetValue() != "Contents" && pageDictionaryObjectIt.GetKey()->GetValue() != "Annots" ) { modifiedPageObject->WriteKey(pageDictionaryObjectIt.GetKey()->GetValue()); copyingContext->CopyDirectObjectAsIs(pageDictionaryObjectIt.GetValue()); } } // Write new annotations entry, joining existing annotations, and new ones (from links attaching or what not) if (!!pageDictionaryObject->Exists("Annots") || mWriter->GetDocumentContext().GetAnnotations().size() > 0) { modifiedPageObject->WriteKey("Annots"); objectContext.StartArray(); // write old annots, if any exist PDFObjectCastPtr<PDFArray> anArray(copyingContext->GetSourceDocumentParser()->QueryDictionaryObject(pageDictionaryObject.GetPtr(),"Annots")); SingleValueContainerIterator<PDFObjectVector> refs = anArray->GetIterator(); //PDFObjectCastPtr<PDFIndirectObjectReference> ref; while (refs.MoveNext()) copyingContext->CopyDirectObjectAsIs(refs.GetItem()); // write new annots from links ObjectIDTypeSet& annotations = mWriter->GetDocumentContext().GetAnnotations(); if (annotations.size() > 0) { ObjectIDTypeSet::iterator it = annotations.begin(); for (; it != annotations.end(); ++it) objectContext.WriteNewIndirectObjectReference(*it); } annotations.clear(); objectContext.EndArray(eTokenSeparatorEndLine); } // Write new contents entry, joining the existing contents with the new one. take care of various scenarios of the existing Contents modifiedPageObject->WriteKey("Contents"); if(!pageDictionaryObject->Exists("Contents")) { // no contents objectContext.WriteIndirectObjectReference(newContentObjectID); } else { objectContext.StartArray(); if (mEnsureContentEncapsulation) { newEncapsulatingObjectID = objectContext.GetInDirectObjectsRegistry().AllocateNewObjectID(); objectContext.WriteNewIndirectObjectReference(newEncapsulatingObjectID); } RefCountPtr<PDFObject> pageContent(copyingContext->GetSourceDocumentParser()->QueryDictionaryObject(pageDictionaryObject.GetPtr(), "Contents")); if (pageContent->GetType() == PDFObject::ePDFObjectStream) { // single content stream. must be a refrence which points to it PDFObjectCastPtr<PDFIndirectObjectReference> ref(pageDictionaryObject->QueryDirectObject("Contents")); objectContext.WriteIndirectObjectReference(ref->mObjectID, ref->mVersion); } else if (pageContent->GetType() == PDFObject::ePDFObjectArray) { PDFArray* anArray = (PDFArray*)pageContent.GetPtr(); // multiple content streams SingleValueContainerIterator<PDFObjectVector> refs = anArray->GetIterator(); PDFObjectCastPtr<PDFIndirectObjectReference> ref; while (refs.MoveNext()) { ref = refs.GetItem(); objectContext.WriteIndirectObjectReference(ref->mObjectID, ref->mVersion); } } else { // this basically means no content...or whatever. just ignore. } objectContext.WriteNewIndirectObjectReference(newContentObjectID); objectContext.EndArray(); objectContext.EndLine(); } // Write a new resource entry. copy all but the "XObject" entry, which needs to be modified. Just for kicks i'm keeping the original // form (either direct dictionary, or indirect object) ObjectIDType resourcesIndirect = 0; ObjectIDType newResourcesIndirect = 0; vector<string> formResourcesNames; modifiedPageObject->WriteKey("Resources"); if(!pageDictionaryObject->Exists("Resources")) { // no existing resource dictionary, so write a new one DictionaryContext* dict = objectContext.StartDictionary(); dict->WriteKey("XObject"); DictionaryContext* xobjectDict = objectContext.StartDictionary(); for(unsigned long i=0;i<mContenxts.size();++i) { string formObjectName = string("myForm_") + Int(i).ToString(); dict->WriteKey(formObjectName); dict->WriteObjectReferenceValue(mContenxts[i]->GetObjectID()); formResourcesNames.push_back(formObjectName); } objectContext.EndDictionary(xobjectDict); objectContext.EndDictionary(dict); } else { // resources may be direct, or indirect. if direct, write as is, adding the new form xobject, otherwise wait till page object ends and write then PDFObjectCastPtr<PDFIndirectObjectReference> resourceDictRef(pageDictionaryObject->QueryDirectObject("Resources")); if(!resourceDictRef) { PDFObjectCastPtr<PDFDictionary> resourceDict(pageDictionaryObject->QueryDirectObject("Resources")); formResourcesNames = WriteModifiedResourcesDict(copyingContext->GetSourceDocumentParser(),resourceDict.GetPtr(),objectContext,copyingContext); } else { resourcesIndirect = resourceDictRef->mObjectID; // later will write a modified version of the resources dictionary, with the new form. // only modify the resources dict object if wasn't already modified (can happen when sharing resources dict between multiple pages). // in the case where it was alrady modified, create a new resources dictionary that's a copy, and use it instead, to avoid overwriting // the previous modification GetObjectWriteInformationResult res = objectContext.GetInDirectObjectsRegistry().GetObjectWriteInformation(resourcesIndirect); if(res.first && res.second.mIsDirty) { newResourcesIndirect = objectContext.GetInDirectObjectsRegistry().AllocateNewObjectID(); modifiedPageObject->WriteObjectReferenceValue(newResourcesIndirect); } else modifiedPageObject->WriteObjectReferenceValue(resourcesIndirect); } } objectContext.EndDictionary(modifiedPageObject); objectContext.EndIndirectObject(); if(resourcesIndirect!=0) { if(newResourcesIndirect != 0) objectContext.StartNewIndirectObject(newResourcesIndirect); else objectContext.StartModifiedIndirectObject(resourcesIndirect); PDFObjectCastPtr<PDFDictionary> resourceDict(copyingContext->GetSourceDocumentParser()->ParseNewObject(resourcesIndirect)); formResourcesNames = WriteModifiedResourcesDict(copyingContext->GetSourceDocumentParser(),resourceDict.GetPtr(),objectContext,copyingContext); objectContext.EndIndirectObject(); } // if required write encapsulation code, so that new stream is independent of graphic context of original PDFStream* newStream; PrimitiveObjectsWriter primitivesWriter; if (newEncapsulatingObjectID != 0) { objectContext.StartNewIndirectObject(newEncapsulatingObjectID); newStream = objectContext.StartPDFStream(); primitivesWriter.SetStreamForWriting(newStream->GetWriteStream()); primitivesWriter.WriteKeyword("q"); objectContext.EndPDFStream(newStream); } // last but not least, create the actual content stream object, placing the form objectContext.StartNewIndirectObject(newContentObjectID); newStream = objectContext.StartPDFStream(); primitivesWriter.SetStreamForWriting(newStream->GetWriteStream()); if (newEncapsulatingObjectID != 0) { primitivesWriter.WriteKeyword("Q"); } vector<string>::iterator it = formResourcesNames.begin(); for(;it!=formResourcesNames.end();++it) { primitivesWriter.WriteKeyword("q"); primitivesWriter.WriteInteger(1); primitivesWriter.WriteInteger(0); primitivesWriter.WriteInteger(0); primitivesWriter.WriteInteger(1); primitivesWriter.WriteInteger(0); primitivesWriter.WriteInteger(0); primitivesWriter.WriteKeyword("cm"); primitivesWriter.WriteName(*it); primitivesWriter.WriteKeyword("Do"); primitivesWriter.WriteKeyword("Q"); } objectContext.EndPDFStream(newStream); return eSuccess; } vector<string> PDFModifiedPage::WriteModifiedResourcesDict(PDFParser* inParser,PDFDictionary* inResourcesDictionary,ObjectsContext& inObjectContext,PDFDocumentCopyingContext* inCopyingContext) { vector<string> formResourcesNames; MapIterator<PDFNameToPDFObjectMap> resourcesDictionaryIt = inResourcesDictionary->GetIterator(); // create modified page object DictionaryContext* dict = mWriter->GetObjectsContext().StartDictionary(); // copy all elements of the page to the new page object, but the "Contents" and "Resources" elements while(resourcesDictionaryIt.MoveNext()) { if(resourcesDictionaryIt.GetKey()->GetValue() != "XObject") { dict->WriteKey(resourcesDictionaryIt.GetKey()->GetValue()); inCopyingContext->CopyDirectObjectAsIs(resourcesDictionaryIt.GetValue()); } } // now write a new xobject entry. dict->WriteKey("XObject"); DictionaryContext* xobjectDict = inObjectContext.StartDictionary(); PDFObjectCastPtr<PDFDictionary> existingXObjectDict(inParser->QueryDictionaryObject(inResourcesDictionary,"XObject")); string imageObjectName; if(existingXObjectDict.GetPtr()) { // i'm having a very sophisticated algo here to create a new unique name. // i'm making sure it's different in one letter from any name, using a well known discrete math proof method MapIterator<PDFNameToPDFObjectMap> itExisting = existingXObjectDict->GetIterator(); unsigned long i=0; while(itExisting.MoveNext()) { string name = itExisting.GetKey()->GetValue(); xobjectDict->WriteKey(name); inCopyingContext->CopyDirectObjectAsIs(itExisting.GetValue()); imageObjectName.push_back((char)(GetDifferentChar((name.length() >= i+1) ? name[i]:0x39))); ++i; } inObjectContext.EndLine(); } PDFFormXObjectVector::iterator itForms = mContenxts.begin(); imageObjectName.push_back('_'); for(int i=0;itForms != mContenxts.end();++i,++itForms) { string formObjectName = imageObjectName + Int(i).ToString(); xobjectDict->WriteKey(formObjectName); xobjectDict->WriteObjectReferenceValue((*itForms)->GetObjectID()); formResourcesNames.push_back(formObjectName); } inObjectContext.EndDictionary(xobjectDict); inObjectContext.EndDictionary(dict); return formResourcesNames; } unsigned char PDFModifiedPage::GetDifferentChar(unsigned char inCharCode) { // numerals if(inCharCode >= 0x30 && inCharCode <= 0x38) return inCharCode+1; if(inCharCode == 0x39) return 0x30; // lowercase if(inCharCode >= 0x61 && inCharCode <= 0x79) return inCharCode+1; if(inCharCode == 0x7a) return 0x61; // uppercase if(inCharCode >= 0x41 && inCharCode <= 0x59) return inCharCode+1; if(inCharCode == 0x5a) return 0x41; return 0x41; } PDFFormXObject* PDFModifiedPage::GetCurrentFormContext() { return mCurrentContext; } ResourcesDictionary* PDFModifiedPage::GetCurrentResourcesDictionary() { return mCurrentContext ? &(mCurrentContext->GetResourcesDictionary()):NULL; } <|endoftext|>
<commit_before>// Macro redoFinish.C is used after macro mergeOutput.C has been used for merging. // Before using this macro first read the explanation at the beginning of macro mergeOutput.C. enum libModes {mLocal,mLocalSource}; void redoFinish(TString type="ESD", Int_t mode=mLocal) { // type: type of analysis can be ESD, AOD, MC, ESDMC0, ESDMC1 // (if type="" output files are from MC simulation (default)) // mode: if mode = mLocal: analyze data on your computer using aliroot // if mode = mLocalSource: analyze data on your computer using root + source files // Name of merged, large statistics file obtained with macro mergeOutput.C: TString mergedFileName = "mergedAnalysisResults.root"; // Final output file name holding final results for large statistics sample: TString outputFileName = "AnalysisResults.root"; const Int_t nMethods = 10; TString method[nMethods] = {"MCEP","SP","GFC","QC","FQD","LYZ1SUM","LYZ1PROD","LYZ2SUM","LYZ2PROD","LYZEP"}; // Load needed libraries: LoadLibrariesRF(mode); // Accessing the merged, large statistics file obtained with macro mergeOutput.C. // On this file the flow analysis will be redone, its content modified to store // the correct final results and eventually renamed into TString outputFileName. TString pwd(gSystem->pwd()); pwd+="/"; pwd+=mergedFileName.Data(); TFile *mergedFile = NULL; if(gSystem->AccessPathName(pwd.Data(),kFileExists)) { cout<<"WARNING: You do not have a merged output file:"<<endl; cout<<" "<<pwd.Data()<<endl; cout<<endl; cout<<"In order to get that file use macro mergeOutput.C first."<<endl; cout<<endl; exit(0); } else { // Create temporarily copy of "mergedAnalysisResults.root": TSystemFile *fileTemp = new TSystemFile(mergedFileName.Data(),"."); fileTemp->Copy("mergedAnalysisResultsTemp.root"); delete fileTemp; // Access merged file: mergedFile = TFile::Open(pwd.Data(),"UPDATE"); } // Access from mergedFile the merged files for each method and from them the lists holding histograms: TString fileName[nMethods]; TDirectoryFile *dirFile[nMethods] = {NULL}; TString listName[nMethods]; TList *list[nMethods] = {NULL}; for(Int_t i=0;i<nMethods;i++) { // Form a file name for each method: fileName[i]+="output"; fileName[i]+=method[i].Data(); fileName[i]+="analysis"; fileName[i]+=type.Data(); // Access this file: dirFile[i] = (TDirectoryFile*)mergedFile->FindObjectAny(fileName[i].Data()); // Form a list name for each method: listName[i]+="cobj"; listName[i]+=method[i].Data(); // Access this list: if(dirFile[i]) { dirFile[i]->GetObject(listName[i].Data(),list[i]); } else { cout<<"WARNING: Couldn't find a file "<<fileName[i].Data()<<".root !!!!"<<endl; } } // End of for(Int_t i=0;i<nMethods;i++) // Redo finish for each method (REMARK: this implementation can be dramatically improved!): // MCEP: for(Int_t i=0;i<nMethods;i++) { if(list[i] && strcmp(list[i]->GetName(),"cobjMCEP")==0) { AliFlowAnalysisWithMCEventPlane* mcep = new AliFlowAnalysisWithMCEventPlane(); mcep->GetOutputHistograms(list[i]); mcep->Finish(); dirFile[i]->Add(list[i],kTRUE); dirFile[i]->Write(dirFile[i]->GetName(),TObject::kSingleKey+TObject::kOverwrite); } // SP: else if(list[i] && strcmp(list[i]->GetName(),"cobjSP")==0) { AliFlowAnalysisWithScalarProduct* sp = new AliFlowAnalysisWithScalarProduct(); sp->GetOutputHistograms(list[i]); sp->Finish(); dirFile[i]->Add(list[i],kTRUE); dirFile[i]->Write(dirFile[i]->GetName(),TObject::kSingleKey+TObject::kOverwrite); } // GFC: else if(list[i] && strcmp(list[i]->GetName(),"cobjGFC")==0) { AliFlowAnalysisWithCumulants* gfc = new AliFlowAnalysisWithCumulants(); gfc->GetOutputHistograms(list[i]); gfc->Finish(); dirFile[i]->Add(list[i],kTRUE); dirFile[i]->Write(dirFile[i]->GetName(),TObject::kSingleKey+TObject::kOverwrite); } // QC: else if(list[i] && strcmp(list[i]->GetName(),"cobjQC")==0) { AliFlowAnalysisWithQCumulants* qc = new AliFlowAnalysisWithQCumulants(); qc->GetOutputHistograms(list[i]); qc->Finish(); dirFile[i]->Add(list[i],kTRUE); dirFile[i]->Write(dirFile[i]->GetName(),TObject::kSingleKey+TObject::kOverwrite); } // FQD: else if(list[i] && strcmp(list[i]->GetName(),"cobjFQD")==0) { AliFlowAnalysisWithFittingQDistribution* fqd = new AliFlowAnalysisWithFittingQDistribution(); fqd->GetOutputHistograms(list[i]); fqd->Finish(kTRUE); dirFile[i]->Add(list[i],kTRUE); dirFile[i]->Write(dirFile[i]->GetName(),TObject::kSingleKey+TObject::kOverwrite); } // LYZ1SUM: else if(list[i] && strcmp(list[i]->GetName(),"cobjLYZ1SUM")==0) { AliFlowAnalysisWithLeeYangZeros* lyz1sum = new AliFlowAnalysisWithLeeYangZeros(); lyz1sum->SetFirstRun(kTRUE); lyz1sum->SetUseSum(kTRUE); lyz1sum->GetOutputHistograms(list[i]); lyz1sum->Finish(); dirFile[i]->Add(list[i],kTRUE); dirFile[i]->Write(dirFile[i]->GetName(),TObject::kSingleKey+TObject::kOverwrite); } // LYZ2SUM: else if(list[i] && strcmp(list[i]->GetName(),"cobjLYZ2SUM")==0) { AliFlowAnalysisWithLeeYangZeros* lyz2sum = new AliFlowAnalysisWithLeeYangZeros(); lyz2sum->SetFirstRun(kFALSE); lyz2sum->SetUseSum(kTRUE); lyz2sum->GetOutputHistograms(list[i]); lyz2sum->Finish(); dirFile[i]->Add(list[i],kTRUE); dirFile[i]->Write(dirFile[i]->GetName(),TObject::kSingleKey+TObject::kOverwrite); } // LYZ1PROD: else if(list[i] && strcmp(list[i]->GetName(),"cobjLYZ1PROD")==0) { AliFlowAnalysisWithLeeYangZeros* lyz1prod = new AliFlowAnalysisWithLeeYangZeros(); lyz1prod->SetFirstRun(kTRUE); lyz1prod->SetUseSum(kFALSE); lyz1prod->GetOutputHistograms(list[i]); lyz1prod->Finish(); dirFile[i]->Add(list[i],kTRUE); dirFile[i]->Write(dirFile[i]->GetName(),TObject::kSingleKey+TObject::kOverwrite); } // LYZ2PROD: else if(list[i] && strcmp(list[i]->GetName(),"cobjLYZ2PROD")==0) { AliFlowAnalysisWithLeeYangZeros* lyz2prod = new AliFlowAnalysisWithLeeYangZeros(); lyz2prod->SetFirstRun(kFALSE); lyz2prod->SetUseSum(kFALSE); lyz2prod->GetOutputHistograms(list[i]); lyz2prod->Finish(); dirFile[i]->Add(list[i],kTRUE); dirFile[i]->Write(dirFile[i]->GetName(),TObject::kSingleKey+TObject::kOverwrite); } // LYZEP: else if(list[i] && strcmp(list[i]->GetName(),"cobjLYZEP")==0) { AliFlowAnalysisWithLYZEventPlane* lyzep = new AliFlowAnalysisWithLYZEventPlane(); lyzep->GetOutputHistograms(list[i]); lyzep->Finish(); dirFile[i]->Add(list[i],kTRUE); dirFile[i]->Write(dirFile[i]->GetName(),TObject::kSingleKey+TObject::kOverwrite); } } // End of for(Int_t i=0;i<nMethods;i++) // Close the final output file: mergedFile->Close(); delete mergedFile; // Giving the final names: TSystemFile *outputFileFinal = new TSystemFile(mergedFileName.Data(),"."); outputFileFinal->Rename(outputFileName.Data()); delete outputFileFinal; TSystemFile *mergedFileFinal = new TSystemFile("mergedAnalysisResultsTemp.root","."); mergedFileFinal->Rename(mergedFileName.Data()); delete mergedFileFinal; } // End of void redoFinish(Int_t mode=mLocal) void LoadLibrariesRF(const libModes mode) { //-------------------------------------- // Load the needed libraries most of them already loaded by aliroot //-------------------------------------- //gSystem->Load("libTree"); gSystem->Load("libGeom"); gSystem->Load("libVMC"); gSystem->Load("libXMLIO"); gSystem->Load("libPhysics"); //---------------------------------------------------------- // >>>>>>>>>>> Local mode <<<<<<<<<<<<<< //---------------------------------------------------------- if (mode==mLocal) { //-------------------------------------------------------- // If you want to use already compiled libraries // in the aliroot distribution //-------------------------------------------------------- //================================================================================== //load needed libraries: gSystem->AddIncludePath("-I$ROOTSYS/include"); //gSystem->Load("libTree"); // for AliRoot gSystem->AddIncludePath("-I$ALICE_ROOT/include"); gSystem->Load("libANALYSIS"); gSystem->Load("libPWG2flowCommon"); //cerr<<"libPWG2flowCommon loaded ..."<<endl; } else if (mode==mLocalSource) { // In root inline compile // Constants gROOT->LoadMacro("AliFlowCommon/AliFlowCommonConstants.cxx+"); gROOT->LoadMacro("AliFlowCommon/AliFlowLYZConstants.cxx+"); gROOT->LoadMacro("AliFlowCommon/AliFlowCumuConstants.cxx+"); // Flow event gROOT->LoadMacro("AliFlowCommon/AliFlowVector.cxx+"); gROOT->LoadMacro("AliFlowCommon/AliFlowTrackSimple.cxx+"); gROOT->LoadMacro("AliFlowCommon/AliFlowEventSimple.cxx+"); // Cuts gROOT->LoadMacro("AliFlowCommon/AliFlowTrackSimpleCuts.cxx+"); // Output histosgrams gROOT->LoadMacro("AliFlowCommon/AliFlowCommonHist.cxx+"); gROOT->LoadMacro("AliFlowCommon/AliFlowCommonHistResults.cxx+"); gROOT->LoadMacro("AliFlowCommon/AliFlowLYZHist1.cxx+"); gROOT->LoadMacro("AliFlowCommon/AliFlowLYZHist2.cxx+"); cout << "finished loading macros!" << endl; } // end of else if (mode==mLocalSource) } // end of void LoadLibrariesRF(const libModes mode) <commit_msg>also working locally in root<commit_after>// Macro redoFinish.C is used after macro mergeOutput.C has been used for merging. // Before using this macro first read the explanation at the beginning of macro mergeOutput.C. enum libModes {mLocal,mLocalSource}; void redoFinish(TString type="ESD", Int_t mode=mLocal) { // type: type of analysis can be ESD, AOD, MC, ESDMC0, ESDMC1 // (if type="" output files are from MC simulation (default)) // mode: if mode = mLocal: analyze data on your computer using aliroot // if mode = mLocalSource: analyze data on your computer using root + source files // Name of merged, large statistics file obtained with macro mergeOutput.C: TString mergedFileName = "mergedAnalysisResults.root"; // Final output file name holding final results for large statistics sample: TString outputFileName = "AnalysisResults.root"; const Int_t nMethods = 10; TString method[nMethods] = {"MCEP","SP","GFC","QC","FQD","LYZ1SUM","LYZ1PROD","LYZ2SUM","LYZ2PROD","LYZEP"}; // Load needed libraries: LoadLibrariesRF(mode); // Accessing the merged, large statistics file obtained with macro mergeOutput.C. // On this file the flow analysis will be redone, its content modified to store // the correct final results and eventually renamed into TString outputFileName. TString pwd(gSystem->pwd()); pwd+="/"; pwd+=mergedFileName.Data(); TFile *mergedFile = NULL; if(gSystem->AccessPathName(pwd.Data(),kFileExists)) { cout<<"WARNING: You do not have a merged output file:"<<endl; cout<<" "<<pwd.Data()<<endl; cout<<endl; cout<<"In order to get that file use macro mergeOutput.C first."<<endl; cout<<endl; exit(0); } else { // Create temporarily copy of "mergedAnalysisResults.root": TSystemFile *fileTemp = new TSystemFile(mergedFileName.Data(),"."); fileTemp->Copy("mergedAnalysisResultsTemp.root"); delete fileTemp; // Access merged file: mergedFile = TFile::Open(pwd.Data(),"UPDATE"); } // Access from mergedFile the merged files for each method and from them the lists holding histograms: TString fileName[nMethods]; TDirectoryFile *dirFile[nMethods] = {NULL}; TString listName[nMethods]; TList *list[nMethods] = {NULL}; for(Int_t i=0;i<nMethods;i++) { // Form a file name for each method: fileName[i]+="output"; fileName[i]+=method[i].Data(); fileName[i]+="analysis"; fileName[i]+=type.Data(); // Access this file: dirFile[i] = (TDirectoryFile*)mergedFile->FindObjectAny(fileName[i].Data()); // Form a list name for each method: listName[i]+="cobj"; listName[i]+=method[i].Data(); // Access this list: if(dirFile[i]) { dirFile[i]->GetObject(listName[i].Data(),list[i]); } else { cout<<"WARNING: Couldn't find a file "<<fileName[i].Data()<<".root !!!!"<<endl; } } // End of for(Int_t i=0;i<nMethods;i++) // Redo finish for each method (REMARK: this implementation can be dramatically improved!): // MCEP: for(Int_t i=0;i<nMethods;i++) { if(list[i] && strcmp(list[i]->GetName(),"cobjMCEP")==0) { AliFlowAnalysisWithMCEventPlane* mcep = new AliFlowAnalysisWithMCEventPlane(); mcep->GetOutputHistograms(list[i]); mcep->Finish(); dirFile[i]->Add(list[i],kTRUE); dirFile[i]->Write(dirFile[i]->GetName(),TObject::kSingleKey+TObject::kOverwrite); } // SP: else if(list[i] && strcmp(list[i]->GetName(),"cobjSP")==0) { AliFlowAnalysisWithScalarProduct* sp = new AliFlowAnalysisWithScalarProduct(); sp->GetOutputHistograms(list[i]); sp->Finish(); dirFile[i]->Add(list[i],kTRUE); dirFile[i]->Write(dirFile[i]->GetName(),TObject::kSingleKey+TObject::kOverwrite); } // GFC: else if(list[i] && strcmp(list[i]->GetName(),"cobjGFC")==0) { AliFlowAnalysisWithCumulants* gfc = new AliFlowAnalysisWithCumulants(); gfc->GetOutputHistograms(list[i]); gfc->Finish(); dirFile[i]->Add(list[i],kTRUE); dirFile[i]->Write(dirFile[i]->GetName(),TObject::kSingleKey+TObject::kOverwrite); } // QC: else if(list[i] && strcmp(list[i]->GetName(),"cobjQC")==0) { AliFlowAnalysisWithQCumulants* qc = new AliFlowAnalysisWithQCumulants(); qc->GetOutputHistograms(list[i]); qc->Finish(); dirFile[i]->Add(list[i],kTRUE); dirFile[i]->Write(dirFile[i]->GetName(),TObject::kSingleKey+TObject::kOverwrite); } // FQD: else if(list[i] && strcmp(list[i]->GetName(),"cobjFQD")==0) { AliFlowAnalysisWithFittingQDistribution* fqd = new AliFlowAnalysisWithFittingQDistribution(); fqd->GetOutputHistograms(list[i]); fqd->Finish(kTRUE); dirFile[i]->Add(list[i],kTRUE); dirFile[i]->Write(dirFile[i]->GetName(),TObject::kSingleKey+TObject::kOverwrite); } // LYZ1SUM: else if(list[i] && strcmp(list[i]->GetName(),"cobjLYZ1SUM")==0) { AliFlowAnalysisWithLeeYangZeros* lyz1sum = new AliFlowAnalysisWithLeeYangZeros(); lyz1sum->SetFirstRun(kTRUE); lyz1sum->SetUseSum(kTRUE); lyz1sum->GetOutputHistograms(list[i]); lyz1sum->Finish(); dirFile[i]->Add(list[i],kTRUE); dirFile[i]->Write(dirFile[i]->GetName(),TObject::kSingleKey+TObject::kOverwrite); } // LYZ2SUM: else if(list[i] && strcmp(list[i]->GetName(),"cobjLYZ2SUM")==0) { AliFlowAnalysisWithLeeYangZeros* lyz2sum = new AliFlowAnalysisWithLeeYangZeros(); lyz2sum->SetFirstRun(kFALSE); lyz2sum->SetUseSum(kTRUE); lyz2sum->GetOutputHistograms(list[i]); lyz2sum->Finish(); dirFile[i]->Add(list[i],kTRUE); dirFile[i]->Write(dirFile[i]->GetName(),TObject::kSingleKey+TObject::kOverwrite); } // LYZ1PROD: else if(list[i] && strcmp(list[i]->GetName(),"cobjLYZ1PROD")==0) { AliFlowAnalysisWithLeeYangZeros* lyz1prod = new AliFlowAnalysisWithLeeYangZeros(); lyz1prod->SetFirstRun(kTRUE); lyz1prod->SetUseSum(kFALSE); lyz1prod->GetOutputHistograms(list[i]); lyz1prod->Finish(); dirFile[i]->Add(list[i],kTRUE); dirFile[i]->Write(dirFile[i]->GetName(),TObject::kSingleKey+TObject::kOverwrite); } // LYZ2PROD: else if(list[i] && strcmp(list[i]->GetName(),"cobjLYZ2PROD")==0) { AliFlowAnalysisWithLeeYangZeros* lyz2prod = new AliFlowAnalysisWithLeeYangZeros(); lyz2prod->SetFirstRun(kFALSE); lyz2prod->SetUseSum(kFALSE); lyz2prod->GetOutputHistograms(list[i]); lyz2prod->Finish(); dirFile[i]->Add(list[i],kTRUE); dirFile[i]->Write(dirFile[i]->GetName(),TObject::kSingleKey+TObject::kOverwrite); } // LYZEP: else if(list[i] && strcmp(list[i]->GetName(),"cobjLYZEP")==0) { AliFlowAnalysisWithLYZEventPlane* lyzep = new AliFlowAnalysisWithLYZEventPlane(); lyzep->GetOutputHistograms(list[i]); lyzep->Finish(); dirFile[i]->Add(list[i],kTRUE); dirFile[i]->Write(dirFile[i]->GetName(),TObject::kSingleKey+TObject::kOverwrite); } } // End of for(Int_t i=0;i<nMethods;i++) // Close the final output file: mergedFile->Close(); delete mergedFile; // Giving the final names: TSystemFile *outputFileFinal = new TSystemFile(mergedFileName.Data(),"."); outputFileFinal->Rename(outputFileName.Data()); delete outputFileFinal; TSystemFile *mergedFileFinal = new TSystemFile("mergedAnalysisResultsTemp.root","."); mergedFileFinal->Rename(mergedFileName.Data()); delete mergedFileFinal; } // End of void redoFinish(Int_t mode=mLocal) void LoadLibrariesRF(const libModes mode) { //-------------------------------------- // Load the needed libraries most of them already loaded by aliroot //-------------------------------------- //gSystem->Load("libTree"); gSystem->Load("libGeom"); gSystem->Load("libVMC"); gSystem->Load("libXMLIO"); gSystem->Load("libPhysics"); //---------------------------------------------------------- // >>>>>>>>>>> Local mode <<<<<<<<<<<<<< //---------------------------------------------------------- if (mode==mLocal) { //-------------------------------------------------------- // If you want to use already compiled libraries // in the aliroot distribution //-------------------------------------------------------- //================================================================================== //load needed libraries: gSystem->AddIncludePath("-I$ROOTSYS/include"); //gSystem->Load("libTree"); // for AliRoot gSystem->AddIncludePath("-I$ALICE_ROOT/include"); gSystem->Load("libANALYSIS"); gSystem->Load("libPWG2flowCommon"); //cerr<<"libPWG2flowCommon loaded ..."<<endl; } else if (mode==mLocalSource) { // In root inline compile // Constants gROOT->LoadMacro("AliFlowCommon/AliFlowCommonConstants.cxx+"); gROOT->LoadMacro("AliFlowCommon/AliFlowLYZConstants.cxx+"); gROOT->LoadMacro("AliFlowCommon/AliFlowCumuConstants.cxx+"); // Flow event gROOT->LoadMacro("AliFlowCommon/AliFlowVector.cxx+"); gROOT->LoadMacro("AliFlowCommon/AliFlowTrackSimple.cxx+"); gROOT->LoadMacro("AliFlowCommon/AliFlowEventSimple.cxx+"); // Cuts gROOT->LoadMacro("AliFlowCommon/AliFlowTrackSimpleCuts.cxx+"); // Output histograms gROOT->LoadMacro("AliFlowCommon/AliFlowCommonHist.cxx+"); gROOT->LoadMacro("AliFlowCommon/AliFlowCommonHistResults.cxx+"); gROOT->LoadMacro("AliFlowCommon/AliFlowLYZHist1.cxx+"); gROOT->LoadMacro("AliFlowCommon/AliFlowLYZHist2.cxx+"); // Functions needed for various methods gROOT->LoadMacro("AliFlowCommon/AliCumulantsFunctions.cxx+"); gROOT->LoadMacro("AliFlowCommon/AliFlowLYZEventPlane.cxx+"); // Flow Analysis code for various methods gROOT->LoadMacro("AliFlowCommon/AliFlowAnalysisWithMCEventPlane.cxx+"); gROOT->LoadMacro("AliFlowCommon/AliFlowAnalysisWithScalarProduct.cxx+"); gROOT->LoadMacro("AliFlowCommon/AliFlowAnalysisWithLYZEventPlane.cxx+"); gROOT->LoadMacro("AliFlowCommon/AliFlowAnalysisWithLeeYangZeros.cxx+"); gROOT->LoadMacro("AliFlowCommon/AliFlowAnalysisWithCumulants.cxx+"); gROOT->LoadMacro("AliFlowCommon/AliFlowAnalysisWithQCumulants.cxx+"); gROOT->LoadMacro("AliFlowCommon/AliFlowAnalysisWithFittingQDistribution.cxx+"); cout << "finished loading macros!" << endl; } // end of else if (mode==mLocalSource) } // end of void LoadLibrariesRF(const libModes mode) <|endoftext|>
<commit_before>// // This file is part of the Marble Virtual Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2013 Mihail Ivchenko <ematirov@gmail.com> // Copyright 2014 Sanjiban Bairagya <sanjiban22393@gmail.com> // Copyright 2014 Illya Kovalevskyy <illya.kovalevskyy@gmail.com> // #include <QDoubleSpinBox> #include <QToolButton> #include <QLabel> #include <QHBoxLayout> #include <QComboBox> #include "FlyToEditWidget.h" #include "MarbleWidget.h" #include "geodata/data/GeoDataFlyTo.h" #include "GeoDataTypes.h" #include "GeoDataCamera.h" #include "MarblePlacemarkModel.h" namespace Marble { FlyToEditWidget::FlyToEditWidget( const QModelIndex &index, MarbleWidget* widget, QWidget *parent ) : QWidget( parent ), m_widget( widget ), m_index( index ), m_button( new QToolButton ) { QHBoxLayout *layout = new QHBoxLayout; layout->setSpacing( 5 ); QLabel* iconLabel = new QLabel; iconLabel->setPixmap( QPixmap( ":/marble/flag.png" ) ); layout->addWidget( iconLabel ); QHBoxLayout *pairLayout = new QHBoxLayout; pairLayout->setSpacing( 10 ); QHBoxLayout *durationLayout = new QHBoxLayout; durationLayout->setSpacing( 5 ); QLabel *durationLabel = new QLabel; durationLabel->setText( tr("Duration:") ); durationLayout->addWidget( durationLabel ); m_durationSpin = new QDoubleSpinBox; durationLayout->addWidget( m_durationSpin ); m_durationSpin->setValue( flyToElement()->duration() ); m_durationSpin->setSuffix( tr(" s", "seconds") ); QHBoxLayout *modeLayout = new QHBoxLayout; modeLayout->addSpacing( 5 ); QLabel *modeLabel = new QLabel; modeLabel->setText( tr("Mode:") ); modeLayout->addWidget( modeLabel ); m_modeCombo = new QComboBox; modeLayout->addWidget( m_modeCombo ); m_modeCombo->addItem( tr("") ); m_modeCombo->addItem( tr("Smooth") ); m_modeCombo->addItem( tr("Bounce") ); if( flyToElement()->flyToMode() == GeoDataFlyTo::Smooth ){ m_modeCombo->setCurrentIndex( 1 ); } else if( flyToElement()->flyToMode() == GeoDataFlyTo::Bounce ){ m_modeCombo->setCurrentIndex( 2 ); } else { m_modeCombo->setCurrentIndex( 0 ); } pairLayout->addLayout( durationLayout ); pairLayout->addLayout( modeLayout ); layout->addLayout( pairLayout ); QToolButton* flyToPinCenter = new QToolButton; flyToPinCenter->setIcon(QIcon(":/marble/places.png")); flyToPinCenter->setToolTip(tr("Current map center")); connect(flyToPinCenter, SIGNAL(clicked()), this, SLOT(updateCoordinates())); layout->addWidget(flyToPinCenter); m_button->setIcon( QIcon( ":/marble/document-save.png" ) ); connect(m_button, SIGNAL(clicked()), this, SLOT(save())); layout->addWidget( m_button ); setLayout( layout ); } bool FlyToEditWidget::editable() const { return m_button->isEnabled(); } void FlyToEditWidget::setEditable( bool editable ) { m_button->setEnabled( editable ); } void FlyToEditWidget::setFirstFlyTo(const QPersistentModelIndex &index) { if( m_index.internalPointer() == index.internalPointer() ) { m_durationSpin->setEnabled( false ); } else { if( !m_durationSpin->isEnabled() ) { m_durationSpin->setEnabled( true ); } } } void FlyToEditWidget::updateCoordinates() { m_coord = m_widget->focusPoint(); m_coord.setAltitude( m_widget->lookAt().range() ); } void FlyToEditWidget::save() { if (flyToElement()->view() != 0 && m_coord != GeoDataCoordinates()) { GeoDataCoordinates coords = m_coord; if ( flyToElement()->view()->nodeType() == GeoDataTypes::GeoDataCameraType ) { GeoDataCamera* camera = dynamic_cast<GeoDataCamera*>( flyToElement()->view() ); camera->setCoordinates( coords ); } else if ( flyToElement()->view()->nodeType() == GeoDataTypes::GeoDataLookAtType ) { GeoDataLookAt* lookAt = dynamic_cast<GeoDataLookAt*>( flyToElement()->view() ); lookAt->setCoordinates( coords ); } else{ GeoDataLookAt* lookAt = new GeoDataLookAt; lookAt->setCoordinates( coords ); flyToElement()->setView( lookAt ); } } flyToElement()->setDuration(m_durationSpin->value()); if( m_modeCombo->currentText() == "Smooth" ){ flyToElement()->setFlyToMode( GeoDataFlyTo::Smooth ); } else if( m_modeCombo->currentText() == "Bounce" ){ flyToElement()->setFlyToMode( GeoDataFlyTo::Bounce ); } emit editingDone(m_index); } GeoDataFlyTo* FlyToEditWidget::flyToElement() { GeoDataObject *object = qvariant_cast<GeoDataObject*>(m_index.data( MarblePlacemarkModel::ObjectPointerRole ) ); Q_ASSERT( object ); Q_ASSERT( object->nodeType() == GeoDataTypes::GeoDataFlyToType ); return static_cast<GeoDataFlyTo*>( object ); } } // namespace Marble #include "FlyToEditWidget.moc" <commit_msg>Removed redundant empty combobox entry in FlyToEditWidget for editing of flyToMode<commit_after>// // This file is part of the Marble Virtual Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2013 Mihail Ivchenko <ematirov@gmail.com> // Copyright 2014 Sanjiban Bairagya <sanjiban22393@gmail.com> // Copyright 2014 Illya Kovalevskyy <illya.kovalevskyy@gmail.com> // #include <QDoubleSpinBox> #include <QToolButton> #include <QLabel> #include <QHBoxLayout> #include <QComboBox> #include "FlyToEditWidget.h" #include "MarbleWidget.h" #include "geodata/data/GeoDataFlyTo.h" #include "GeoDataTypes.h" #include "GeoDataCamera.h" #include "MarblePlacemarkModel.h" namespace Marble { FlyToEditWidget::FlyToEditWidget( const QModelIndex &index, MarbleWidget* widget, QWidget *parent ) : QWidget( parent ), m_widget( widget ), m_index( index ), m_button( new QToolButton ) { QHBoxLayout *layout = new QHBoxLayout; layout->setSpacing( 5 ); QLabel* iconLabel = new QLabel; iconLabel->setPixmap( QPixmap( ":/marble/flag.png" ) ); layout->addWidget( iconLabel ); QHBoxLayout *pairLayout = new QHBoxLayout; pairLayout->setSpacing( 10 ); QHBoxLayout *durationLayout = new QHBoxLayout; durationLayout->setSpacing( 5 ); QLabel *durationLabel = new QLabel; durationLabel->setText( tr("Duration:") ); durationLayout->addWidget( durationLabel ); m_durationSpin = new QDoubleSpinBox; durationLayout->addWidget( m_durationSpin ); m_durationSpin->setValue( flyToElement()->duration() ); m_durationSpin->setSuffix( tr(" s", "seconds") ); QHBoxLayout *modeLayout = new QHBoxLayout; modeLayout->addSpacing( 5 ); QLabel *modeLabel = new QLabel; modeLabel->setText( tr("Mode:") ); modeLayout->addWidget( modeLabel ); m_modeCombo = new QComboBox; modeLayout->addWidget( m_modeCombo ); m_modeCombo->addItem( tr("Smooth") ); m_modeCombo->addItem( tr("Bounce") ); if( flyToElement()->flyToMode() == GeoDataFlyTo::Smooth ){ m_modeCombo->setCurrentIndex( 0 ); } else if( flyToElement()->flyToMode() == GeoDataFlyTo::Bounce ){ m_modeCombo->setCurrentIndex( 1 ); } else { m_modeCombo->setCurrentIndex( -1 ); } pairLayout->addLayout( durationLayout ); pairLayout->addLayout( modeLayout ); layout->addLayout( pairLayout ); QToolButton* flyToPinCenter = new QToolButton; flyToPinCenter->setIcon(QIcon(":/marble/places.png")); flyToPinCenter->setToolTip(tr("Current map center")); connect(flyToPinCenter, SIGNAL(clicked()), this, SLOT(updateCoordinates())); layout->addWidget(flyToPinCenter); m_button->setIcon( QIcon( ":/marble/document-save.png" ) ); connect(m_button, SIGNAL(clicked()), this, SLOT(save())); layout->addWidget( m_button ); setLayout( layout ); } bool FlyToEditWidget::editable() const { return m_button->isEnabled(); } void FlyToEditWidget::setEditable( bool editable ) { m_button->setEnabled( editable ); } void FlyToEditWidget::setFirstFlyTo(const QPersistentModelIndex &index) { if( m_index.internalPointer() == index.internalPointer() ) { m_durationSpin->setEnabled( false ); } else { if( !m_durationSpin->isEnabled() ) { m_durationSpin->setEnabled( true ); } } } void FlyToEditWidget::updateCoordinates() { m_coord = m_widget->focusPoint(); m_coord.setAltitude( m_widget->lookAt().range() ); } void FlyToEditWidget::save() { if (flyToElement()->view() != 0 && m_coord != GeoDataCoordinates()) { GeoDataCoordinates coords = m_coord; if ( flyToElement()->view()->nodeType() == GeoDataTypes::GeoDataCameraType ) { GeoDataCamera* camera = dynamic_cast<GeoDataCamera*>( flyToElement()->view() ); camera->setCoordinates( coords ); } else if ( flyToElement()->view()->nodeType() == GeoDataTypes::GeoDataLookAtType ) { GeoDataLookAt* lookAt = dynamic_cast<GeoDataLookAt*>( flyToElement()->view() ); lookAt->setCoordinates( coords ); } else{ GeoDataLookAt* lookAt = new GeoDataLookAt; lookAt->setCoordinates( coords ); flyToElement()->setView( lookAt ); } } flyToElement()->setDuration(m_durationSpin->value()); if( m_modeCombo->currentText() == "Smooth" ){ flyToElement()->setFlyToMode( GeoDataFlyTo::Smooth ); } else if( m_modeCombo->currentText() == "Bounce" ){ flyToElement()->setFlyToMode( GeoDataFlyTo::Bounce ); } emit editingDone(m_index); } GeoDataFlyTo* FlyToEditWidget::flyToElement() { GeoDataObject *object = qvariant_cast<GeoDataObject*>(m_index.data( MarblePlacemarkModel::ObjectPointerRole ) ); Q_ASSERT( object ); Q_ASSERT( object->nodeType() == GeoDataTypes::GeoDataFlyToType ); return static_cast<GeoDataFlyTo*>( object ); } } // namespace Marble #include "FlyToEditWidget.moc" <|endoftext|>
<commit_before>/* * Copyright 2009-2011 The VOTCA Development Team (http://www.votca.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <stdio.h> #include <string> #include "xyzwriter.h" namespace votca { namespace csg { using namespace std; void XYZWriter::Open(string file, bool bAppend) { _out = fopen(file.c_str(), bAppend ? "at" : "wt"); } void XYZWriter::Close() { fclose(_out); } void XYZWriter::Write(Topology *conf) { Topology *top = conf; fprintf(_out, "%d\n", top->Beads().size()); fprintf(_out, "frame: %d time: %f\n", top->getStep()+1, top->getTime()); for(BeadContainer::iterator iter=conf->Beads().begin(); iter!=conf->Beads().end(); ++iter) { Bead *bi = *iter; vec r = bi->getPos(); //truncate strings if necessary string atomname = bi->getName(); if (atomname.size() > 3) { atomname = atomname.substr(0,3); } while(atomname.size()<3) atomname=" " + atomname; fprintf(_out, "%s%10.5f%10.5f%10.5f\n", atomname.c_str(), 10.*r.getX(), 10.*r.getY(), 10.*r.getZ() ); } fflush(_out); } }} <commit_msg>xyzwriter: fixed warning<commit_after>/* * Copyright 2009-2011 The VOTCA Development Team (http://www.votca.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <stdio.h> #include <string> #include "xyzwriter.h" namespace votca { namespace csg { using namespace std; void XYZWriter::Open(string file, bool bAppend) { _out = fopen(file.c_str(), bAppend ? "at" : "wt"); } void XYZWriter::Close() { fclose(_out); } void XYZWriter::Write(Topology *conf) { Topology *top = conf; fprintf(_out, "%lu\n", top->Beads().size()); fprintf(_out, "frame: %d time: %f\n", top->getStep()+1, top->getTime()); for(BeadContainer::iterator iter=conf->Beads().begin(); iter!=conf->Beads().end(); ++iter) { Bead *bi = *iter; vec r = bi->getPos(); //truncate strings if necessary string atomname = bi->getName(); if (atomname.size() > 3) { atomname = atomname.substr(0,3); } while(atomname.size()<3) atomname=" " + atomname; fprintf(_out, "%s%10.5f%10.5f%10.5f\n", atomname.c_str(), 10.*r.getX(), 10.*r.getY(), 10.*r.getZ() ); } fflush(_out); } }} <|endoftext|>
<commit_before>#include "machines.hh" #include "worker.hh" #include "substitution-goal.hh" #include "derivation-goal.hh" namespace nix { void Store::buildPaths(const std::vector<StorePathWithOutputs> & drvPaths, BuildMode buildMode) { Worker worker(*this); Goals goals; for (auto & path : drvPaths) { if (path.path.isDerivation()) goals.insert(worker.makeDerivationGoal(path.path, path.outputs, buildMode)); else goals.insert(worker.makeSubstitutionGoal(path.path, buildMode == bmRepair ? Repair : NoRepair)); } worker.run(goals); StorePathSet failed; std::optional<Error> ex; for (auto & i : goals) { if (i->ex) { if (ex) logError(i->ex->info()); else ex = i->ex; } if (i->exitCode != Goal::ecSuccess) { if (auto i2 = dynamic_cast<DerivationGoal *>(i.get())) failed.insert(i2->drvPath); else if (auto i2 = dynamic_cast<SubstitutionGoal *>(i.get())) failed.insert(i2->storePath); } } if (failed.size() == 1 && ex) { ex->status = worker.exitStatus(); throw *ex; } else if (!failed.empty()) { if (ex) logError(ex->info()); throw Error(worker.exitStatus(), "build of %s failed", showPaths(failed)); } } BuildResult Store::buildDerivation(const StorePath & drvPath, const BasicDerivation & drv, BuildMode buildMode) { Worker worker(*this); auto goal = worker.makeBasicDerivationGoal(drvPath, drv, {}, buildMode); BuildResult result; try { worker.run(Goals{goal}); result = goal->getResult(); } catch (Error & e) { result.status = BuildResult::MiscFailure; result.errorMsg = e.msg(); } return result; } void Store::ensurePath(const StorePath & path) { /* If the path is already valid, we're done. */ if (isValidPath(path)) return; Worker worker(*this); GoalPtr goal = worker.makeSubstitutionGoal(path); Goals goals = {goal}; worker.run(goals); if (goal->exitCode != Goal::ecSuccess) { if (goal->ex) { goal->ex->status = worker.exitStatus(); throw *goal->ex; } else throw Error(worker.exitStatus(), "path '%s' does not exist and cannot be created", printStorePath(path)); } } void LocalStore::repairPath(const StorePath & path) { Worker worker(*this); GoalPtr goal = worker.makeSubstitutionGoal(path, Repair); Goals goals = {goal}; worker.run(goals); if (goal->exitCode != Goal::ecSuccess) { /* Since substituting the path didn't work, if we have a valid deriver, then rebuild the deriver. */ auto info = queryPathInfo(path); if (info->deriver && isValidPath(*info->deriver)) { goals.clear(); goals.insert(worker.makeDerivationGoal(*info->deriver, StringSet(), bmRepair)); worker.run(goals); } else throw Error(worker.exitStatus(), "cannot repair path '%s'", printStorePath(path)); } } } <commit_msg>LocalStore: Send back the new realisations<commit_after>#include "machines.hh" #include "worker.hh" #include "substitution-goal.hh" #include "derivation-goal.hh" namespace nix { void Store::buildPaths(const std::vector<StorePathWithOutputs> & drvPaths, BuildMode buildMode) { Worker worker(*this); Goals goals; for (auto & path : drvPaths) { if (path.path.isDerivation()) goals.insert(worker.makeDerivationGoal(path.path, path.outputs, buildMode)); else goals.insert(worker.makeSubstitutionGoal(path.path, buildMode == bmRepair ? Repair : NoRepair)); } worker.run(goals); StorePathSet failed; std::optional<Error> ex; for (auto & i : goals) { if (i->ex) { if (ex) logError(i->ex->info()); else ex = i->ex; } if (i->exitCode != Goal::ecSuccess) { if (auto i2 = dynamic_cast<DerivationGoal *>(i.get())) failed.insert(i2->drvPath); else if (auto i2 = dynamic_cast<SubstitutionGoal *>(i.get())) failed.insert(i2->storePath); } } if (failed.size() == 1 && ex) { ex->status = worker.exitStatus(); throw *ex; } else if (!failed.empty()) { if (ex) logError(ex->info()); throw Error(worker.exitStatus(), "build of %s failed", showPaths(failed)); } } BuildResult Store::buildDerivation(const StorePath & drvPath, const BasicDerivation & drv, BuildMode buildMode) { Worker worker(*this); auto goal = worker.makeBasicDerivationGoal(drvPath, drv, {}, buildMode); BuildResult result; try { worker.run(Goals{goal}); result = goal->getResult(); } catch (Error & e) { result.status = BuildResult::MiscFailure; result.errorMsg = e.msg(); } // XXX: Should use `goal->queryPartialDerivationOutputMap()` once it's // extended to return the full realisation for each output auto staticDrvOutputs = drv.outputsAndOptPaths(*this); auto outputHashes = staticOutputHashes(*this, drv); for (auto & [outputName, staticOutput] : staticDrvOutputs) { auto outputId = DrvOutput{outputHashes.at(outputName), outputName}; if (staticOutput.second) result.builtOutputs.insert_or_assign( outputId, Realisation{ outputId, *staticOutput.second} ); if (settings.isExperimentalFeatureEnabled("ca-derivations")) { auto realisation = this->queryRealisation(outputId); if (realisation) result.builtOutputs.insert_or_assign( outputId, *realisation ); } } return result; } void Store::ensurePath(const StorePath & path) { /* If the path is already valid, we're done. */ if (isValidPath(path)) return; Worker worker(*this); GoalPtr goal = worker.makeSubstitutionGoal(path); Goals goals = {goal}; worker.run(goals); if (goal->exitCode != Goal::ecSuccess) { if (goal->ex) { goal->ex->status = worker.exitStatus(); throw *goal->ex; } else throw Error(worker.exitStatus(), "path '%s' does not exist and cannot be created", printStorePath(path)); } } void LocalStore::repairPath(const StorePath & path) { Worker worker(*this); GoalPtr goal = worker.makeSubstitutionGoal(path, Repair); Goals goals = {goal}; worker.run(goals); if (goal->exitCode != Goal::ecSuccess) { /* Since substituting the path didn't work, if we have a valid deriver, then rebuild the deriver. */ auto info = queryPathInfo(path); if (info->deriver && isValidPath(*info->deriver)) { goals.clear(); goals.insert(worker.makeDerivationGoal(*info->deriver, StringSet(), bmRepair)); worker.run(goals); } else throw Error(worker.exitStatus(), "cannot repair path '%s'", printStorePath(path)); } } } <|endoftext|>
<commit_before>#include "core/stringutils.h" #include "catch.hpp" namespace euco = euphoria::core; TEST_CASE("stringutils-laststrings", "[stringutils]") { SECTION("basic") { const auto r = euco::last_strings("hello.world", '.'); CHECK(r.first == "hello"); CHECK(r.second == ".world"); } SECTION("last") { const auto r = euco::last_strings("hello.", '.'); CHECK(r.first == "hello"); CHECK(r.second == "."); } SECTION("empty") { const auto r = euco::last_strings("hello_world", '.'); CHECK(r.first == "hello_world"); CHECK(r.second.empty()); } } TEST_CASE("stringutils-tolower", "[stringutils]") { CHECK("abc" == euco::to_lower("abc")); CHECK("def" == euco::to_lower("DEF")); CHECK("42" == euco::to_lower("42")); CHECK("simple test" == euco::to_lower("simplE Test")); } TEST_CASE("stringutils-toupper", "[stringutils]") { CHECK("ABC" == euco::to_upper("abc")); CHECK("DEF" == euco::to_upper("DEF")); CHECK("42" == euco::to_upper("42")); CHECK("SIMPLE TEST" == euco::to_upper("simplE Test")); } TEST_CASE("stringutils-chartostring", "[stringutils]") { CHECK("<space>" == euco::char_to_string(' ')); CHECK("<null>" == euco::char_to_string(0)); CHECK("<\\n>" == euco::char_to_string('\n')); // can also be \r and while newline might be true, \n is easier to recognize CHECK("A" == euco::char_to_string('A')); CHECK("<start of heading>(0x1)" == euco::char_to_string(1)); CHECK("<space>(0x20)" == euco::char_to_string(' ', euco::CharToStringStyle::include_hex)); CHECK("P(0x50)" == euco::char_to_string('P', euco::CharToStringStyle::include_hex)); } TEST_CASE("stringutils-findfirstindexmismatch", "[stringutils]") { CHECK(std::string::npos == euco::find_first_index_of_mismatch("dog", "dog")); CHECK(std::string::npos == euco::find_first_index_of_mismatch("", "")); CHECK(0 == euco::find_first_index_of_mismatch("a", "b")); CHECK(0 == euco::find_first_index_of_mismatch("a", "A")); CHECK(1 == euco::find_first_index_of_mismatch("dog", "dag")); CHECK(3 == euco::find_first_index_of_mismatch("dog", "doggo")); CHECK(3 == euco::find_first_index_of_mismatch("doggo", "dog")); } TEST_CASE("stringutils-striplast", "[stringutils]") { CHECK("hello" == euco::strip_last_string("hello.world", '.')); CHECK(euco::strip_last_string("hello_world", '.').empty()); } TEST_CASE("stringutils-strip", "[stringutils]") { CHECK("abc" == euco::strip("abc", " ")); CHECK("abc" == euco::strip(" abc ", " ")); CHECK("abc" == euco::strip(" a b c ", " ")); CHECK("abc" == euco::strip(" a b c ", " ")); } TEST_CASE("stringutils-rem", "[stringutils]") { CHECK("abc" == euco::remove_consecutive("abc", " ")); CHECK(" abc " == euco::remove_consecutive(" abc ", " ")); CHECK(" a b c " == euco::remove_consecutive(" a b c ", " ")); CHECK(" a b c " == euco::remove_consecutive(" a b c ", " ")); } TEST_CASE("stringutils-default_stringsort", "[stringutils]") { CHECK(euco::string_compare("aaa", "bbb") < 0); CHECK(euco::string_compare("aag", "aaa") > 0); CHECK(euco::string_compare("abc", "abc") == 0); } TEST_CASE("stringutils-human_stringsort", "[stringutils]") { const auto lhs = std::string("dog 2"); const auto rhs = std::string("dog 10"); CHECK(lhs > rhs); CHECK(euco::string_compare(lhs, rhs) < 0); } <commit_msg>test: added test for split function<commit_after>#include "core/stringutils.h" #include "tests/stringeq.h" #include "catch.hpp" namespace euco = euphoria::core; using namespace euphoria::tests; TEST_CASE("stringutils-laststrings", "[stringutils]") { SECTION("basic") { const auto r = euco::last_strings("hello.world", '.'); CHECK(r.first == "hello"); CHECK(r.second == ".world"); } SECTION("last") { const auto r = euco::last_strings("hello.", '.'); CHECK(r.first == "hello"); CHECK(r.second == "."); } SECTION("empty") { const auto r = euco::last_strings("hello_world", '.'); CHECK(r.first == "hello_world"); CHECK(r.second.empty()); } } TEST_CASE("stringutils-tolower", "[stringutils]") { CHECK("abc" == euco::to_lower("abc")); CHECK("def" == euco::to_lower("DEF")); CHECK("42" == euco::to_lower("42")); CHECK("simple test" == euco::to_lower("simplE Test")); } TEST_CASE("stringutils-toupper", "[stringutils]") { CHECK("ABC" == euco::to_upper("abc")); CHECK("DEF" == euco::to_upper("DEF")); CHECK("42" == euco::to_upper("42")); CHECK("SIMPLE TEST" == euco::to_upper("simplE Test")); } TEST_CASE("stringutils-chartostring", "[stringutils]") { CHECK("<space>" == euco::char_to_string(' ')); CHECK("<null>" == euco::char_to_string(0)); CHECK("<\\n>" == euco::char_to_string('\n')); // can also be \r and while newline might be true, \n is easier to recognize CHECK("A" == euco::char_to_string('A')); CHECK("<start of heading>(0x1)" == euco::char_to_string(1)); CHECK("<space>(0x20)" == euco::char_to_string(' ', euco::CharToStringStyle::include_hex)); CHECK("P(0x50)" == euco::char_to_string('P', euco::CharToStringStyle::include_hex)); } TEST_CASE("stringutils-findfirstindexmismatch", "[stringutils]") { CHECK(std::string::npos == euco::find_first_index_of_mismatch("dog", "dog")); CHECK(std::string::npos == euco::find_first_index_of_mismatch("", "")); CHECK(0 == euco::find_first_index_of_mismatch("a", "b")); CHECK(0 == euco::find_first_index_of_mismatch("a", "A")); CHECK(1 == euco::find_first_index_of_mismatch("dog", "dag")); CHECK(3 == euco::find_first_index_of_mismatch("dog", "doggo")); CHECK(3 == euco::find_first_index_of_mismatch("doggo", "dog")); } TEST_CASE("stringutils-striplast", "[stringutils]") { CHECK("hello" == euco::strip_last_string("hello.world", '.')); CHECK(euco::strip_last_string("hello_world", '.').empty()); } TEST_CASE("stringutils-strip", "[stringutils]") { CHECK("abc" == euco::strip("abc", " ")); CHECK("abc" == euco::strip(" abc ", " ")); CHECK("abc" == euco::strip(" a b c ", " ")); CHECK("abc" == euco::strip(" a b c ", " ")); } TEST_CASE("stringutils-rem", "[stringutils]") { CHECK("abc" == euco::remove_consecutive("abc", " ")); CHECK(" abc " == euco::remove_consecutive(" abc ", " ")); CHECK(" a b c " == euco::remove_consecutive(" a b c ", " ")); CHECK(" a b c " == euco::remove_consecutive(" a b c ", " ")); } TEST_CASE("stringutils-default_stringsort", "[stringutils]") { CHECK(euco::string_compare("aaa", "bbb") < 0); CHECK(euco::string_compare("aag", "aaa") > 0); CHECK(euco::string_compare("abc", "abc") == 0); } TEST_CASE("stringutils-human_stringsort", "[stringutils]") { const auto lhs = std::string("dog 2"); const auto rhs = std::string("dog 10"); CHECK(lhs > rhs); CHECK(euco::string_compare(lhs, rhs) < 0); } TEST_CASE("stringutils-split", "[stringutils]") { CHECK(string_is_equal({}, euco::split("", ','))); CHECK(string_is_equal({"a", "b", "c"}, euco::split("a,b,c", ','))); CHECK(string_is_equal({"a", "", "b", "c"}, euco::split("a,,b,c", ','))); CHECK(string_is_equal({"", "a", "b", "c"}, euco::split(",a,b,c", ','))); CHECK(string_is_equal({"a", "b", "c"}, euco::split("a,b,c,", ','))); CHECK(string_is_equal({"a", "", "", "b"}, euco::split("a,,,b", ','))); CHECK(string_is_equal({"another", "bites", "cars"}, euco::split("another,bites,cars", ','))); CHECK(string_is_equal({"a", "b", "c"}, euco::split("a/b/c", '/'))); CHECK(string_is_equal({"another", "bites", "cars"}, euco::split("another/bites/cars", '/'))); } TEST_CASE("stringutils-split-spaces", "[stringutils]") { CHECK(string_is_equal({}, euco::split_on_spaces(""))); CHECK(string_is_equal({}, euco::split_on_spaces(" \n \r \t "))); CHECK(string_is_equal({"a", "b", "c"}, euco::split_on_spaces("a b c"))); CHECK(string_is_equal({"a", "b", "c"}, euco::split_on_spaces(" a b c "))); CHECK(string_is_equal({"a", "b", "c"}, euco::split_on_spaces("\na\tb\rc "))); CHECK(string_is_equal({"another", "bites", "cars"}, euco::split_on_spaces("another bites cars"))); } <|endoftext|>
<commit_before>// ***************************************************************************** // // Copyright (c) 2014, Southwest Research Institute® (SwRI®) // 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. // * 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. // * Neither the name of Southwest Research Institute® (SwRI®) nor the // names of its contributors may be used to endorse or promote products // derived from this software without specific prior written permission. // // 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 <COPYRIGHT HOLDER> 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 <mapviz_plugins/odometry_plugin.h> // C++ standard libraries #include <cstdio> #include <vector> // QT libraries #include <QDialog> #include <QGLWidget> #include <QPainter> #include <QPalette> #include <opencv2/core/core.hpp> // ROS libraries #include <ros/master.h> #include <swri_image_util/geometry_util.h> #include <swri_transform_util/transform_util.h> #include <mapviz/select_topic_dialog.h> // Declare plugin #include <pluginlib/class_list_macros.h> PLUGINLIB_EXPORT_CLASS(mapviz_plugins::OdometryPlugin, mapviz::MapvizPlugin) namespace mapviz_plugins { OdometryPlugin::OdometryPlugin() : config_widget_(new QWidget()) { ui_.setupUi(config_widget_); ui_.color->setColor(Qt::green); // Set background white QPalette p(config_widget_->palette()); p.setColor(QPalette::Background, Qt::white); config_widget_->setPalette(p); // Set status text red QPalette p3(ui_.status->palette()); p3.setColor(QPalette::Text, Qt::red); ui_.status->setPalette(p3); QObject::connect(ui_.selecttopic, SIGNAL(clicked()), this, SLOT(SelectTopic())); QObject::connect(ui_.topic, SIGNAL(editingFinished()), this, SLOT(TopicEdited())); QObject::connect(ui_.positiontolerance, SIGNAL(valueChanged(double)), this, SLOT(PositionToleranceChanged(double))); QObject::connect(ui_.buffersize, SIGNAL(valueChanged(int)), this, SLOT(BufferSizeChanged(int))); QObject::connect(ui_.drawstyle, SIGNAL(activated(QString)), this, SLOT(SetDrawStyle(QString))); QObject::connect(ui_.static_arrow_sizes, SIGNAL(clicked(bool)), this, SLOT(SetStaticArrowSizes(bool))); QObject::connect(ui_.arrow_size, SIGNAL(valueChanged(int)), this, SLOT(SetArrowSize(int))); QObject::connect(ui_.color, SIGNAL(colorEdited(const QColor&)), this, SLOT(SetColor(const QColor&))); QObject::connect(ui_.show_laps, SIGNAL(toggled(bool)), this, SLOT(LapToggled(bool))); QObject::connect(ui_.show_covariance, SIGNAL(toggled(bool)), this, SLOT(CovariancedToggled(bool))); QObject::connect(ui_.buttonResetBuffer, SIGNAL(pressed()), this, SLOT(ClearPoints())); } OdometryPlugin::~OdometryPlugin() { } void OdometryPlugin::SelectTopic() { ros::master::TopicInfo topic = mapviz::SelectTopicDialog::selectTopic("nav_msgs/Odometry"); if (!topic.name.empty()) { ui_.topic->setText(QString::fromStdString(topic.name)); TopicEdited(); } } void OdometryPlugin::TopicEdited() { std::string topic = ui_.topic->text().trimmed().toStdString(); if (topic != topic_) { initialized_ = false; ClearPoints(); has_message_ = false; PrintWarning("No messages received."); odometry_sub_.shutdown(); topic_ = topic; if (!topic.empty()) { odometry_sub_ = node_.subscribe( topic_, 1, &OdometryPlugin::odometryCallback, this); ROS_INFO("Subscribing to %s", topic_.c_str()); } } } void OdometryPlugin::odometryCallback( const nav_msgs::OdometryConstPtr odometry) { if (!has_message_) { initialized_ = true; has_message_ = true; } // Note that unlike some plugins, this one does not store nor rely on the // source_frame_ member variable. This one can potentially store many // messages with different source frames, so we need to store and transform // them individually. StampedPoint stamped_point; stamped_point.stamp = odometry->header.stamp; stamped_point.source_frame = odometry->header.frame_id; stamped_point.point = tf::Point(odometry->pose.pose.position.x, odometry->pose.pose.position.y, odometry->pose.pose.position.z); stamped_point.orientation = tf::Quaternion( odometry->pose.pose.orientation.x, odometry->pose.pose.orientation.y, odometry->pose.pose.orientation.z, odometry->pose.pose.orientation.w); if ( ui_.show_covariance->isChecked() ) { tf::Matrix3x3 tf_cov = swri_transform_util::GetUpperLeft(odometry->pose.covariance); if (tf_cov[0][0] < 100000 && tf_cov[1][1] < 100000) { cv::Mat cov_matrix_3d(3, 3, CV_32FC1); for (int32_t r = 0; r < 3; r++) { for (int32_t c = 0; c < 3; c++) { cov_matrix_3d.at<float>(r, c) = tf_cov[r][c]; } } cv::Mat cov_matrix_2d = swri_image_util::ProjectEllipsoid(cov_matrix_3d); if (!cov_matrix_2d.empty()) { stamped_point.cov_points = swri_image_util::GetEllipsePoints( cov_matrix_2d, stamped_point.point, 3, 32); stamped_point.transformed_cov_points = stamped_point.cov_points; } else { ROS_ERROR("Failed to project x, y, z covariance to xy-plane."); } } } pushPoint( std::move(stamped_point) ); } void OdometryPlugin::PrintError(const std::string& message) { PrintErrorHelper(ui_.status, message); } void OdometryPlugin::PrintInfo(const std::string& message) { PrintInfoHelper(ui_.status, message); } void OdometryPlugin::PrintWarning(const std::string& message) { PrintWarningHelper(ui_.status, message); } QWidget* OdometryPlugin::GetConfigWidget(QWidget* parent) { config_widget_->setParent(parent); return config_widget_; } bool OdometryPlugin::Initialize(QGLWidget* canvas) { canvas_ = canvas; SetColor(ui_.color->color()); return true; } void OdometryPlugin::Draw(double x, double y, double scale) { if (ui_.show_covariance->isChecked()) { DrawCovariance(); } if (DrawPoints(scale)) { PrintInfo("OK"); } } void OdometryPlugin::Paint(QPainter* painter, double x, double y, double scale) { //dont render any timestamps if the show_timestamps is set to 0 int interval = ui_.show_timestamps->value(); if (interval == 0) { return; } QTransform tf = painter->worldTransform(); QFont font("Helvetica", 10); painter->setFont(font); painter->save(); painter->resetTransform(); //set the draw color for the text to be the same as the rest QPen pen(QBrush(ui_.color->color()), 1); painter->setPen(pen); int counter = 0;//used to alternate between rendering text on some points for (const StampedPoint& point: points()) { if (point.transformed && counter % interval == 0)//this renders a timestamp every 'interval' points { QPointF qpoint = tf.map(QPointF(point.transformed_point.getX(), point.transformed_point.getY())); QString time; time.setNum(point.stamp.toSec(), 'g', 12); painter->drawText(qpoint, time); } counter++; } painter->restore(); } void OdometryPlugin::LoadConfig(const YAML::Node& node, const std::string& path) { if (node["topic"]) { std::string topic; node["topic"] >> topic; ui_.topic->setText(topic.c_str()); } if (node["color"]) { std::string color; node["color"] >> color; QColor qcolor(color.c_str()); SetColor(qcolor); ui_.color->setColor(qcolor); } if (node["draw_style"]) { std::string draw_style; node["draw_style"] >> draw_style; if (draw_style == "lines") { ui_.drawstyle->setCurrentIndex(0); SetDrawStyle( LINES ); } else if (draw_style == "points") { ui_.drawstyle->setCurrentIndex(1); SetDrawStyle( POINTS ); } else if (draw_style == "arrows") { ui_.drawstyle->setCurrentIndex(2); SetDrawStyle( ARROWS ); } } if (node["position_tolerance"]) { double position_tolerance; node["position_tolerance"] >> position_tolerance; ui_.positiontolerance->setValue(position_tolerance); PositionToleranceChanged(position_tolerance); } if (node["buffer_size"]) { double buffer_size; node["buffer_size"] >> buffer_size; ui_.buffersize->setValue(buffer_size); BufferSizeChanged(buffer_size); } if (node["show_covariance"]) { bool show_covariance = false; node["show_covariance"] >> show_covariance; ui_.show_covariance->setChecked(show_covariance); CovariancedToggled(show_covariance); } if (node["show_laps"]) { bool show_laps = false; node["show_laps"] >> show_laps; ui_.show_laps->setChecked(show_laps); LapToggled(show_laps); } if (node["static_arrow_sizes"]) { bool static_arrow_sizes = node["static_arrow_sizes"].as<bool>(); ui_.static_arrow_sizes->setChecked(static_arrow_sizes); SetStaticArrowSizes(static_arrow_sizes); } if (node["arrow_size"]) { double arrow_size = node["arrow_size"].as<int>(); ui_.arrow_size->setValue(arrow_size); SetArrowSize(arrow_size); } if (node["show_timestamps"]) { ui_.show_timestamps->setValue(node["show_timestamps"].as<int>()); } TopicEdited(); } void OdometryPlugin::SaveConfig(YAML::Emitter& emitter, const std::string& path) { std::string topic = ui_.topic->text().toStdString(); emitter << YAML::Key << "topic" << YAML::Value << topic; std::string color = ui_.color->color().name().toStdString(); emitter << YAML::Key << "color" << YAML::Value << color; std::string draw_style = ui_.drawstyle->currentText().toStdString(); emitter << YAML::Key << "draw_style" << YAML::Value << draw_style; emitter << YAML::Key << "position_tolerance" << YAML::Value << positionTolerance(); emitter << YAML::Key << "buffer_size" << YAML::Value << bufferSize(); bool show_laps = ui_.show_laps->isChecked(); emitter << YAML::Key << "show_laps" << YAML::Value << show_laps; bool show_covariance = ui_.show_covariance->isChecked(); emitter << YAML::Key << "show_covariance" << YAML::Value << show_covariance; emitter << YAML::Key << "static_arrow_sizes" << YAML::Value << ui_.static_arrow_sizes->isChecked(); emitter << YAML::Key << "arrow_size" << YAML::Value << ui_.arrow_size->value(); emitter << YAML::Key << "tampstamps" << YAML::Value << ui_.show_timestamps->value(); } } <commit_msg>Fixed typo in string (#608)<commit_after>// ***************************************************************************** // // Copyright (c) 2014, Southwest Research Institute® (SwRI®) // 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. // * 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. // * Neither the name of Southwest Research Institute® (SwRI®) nor the // names of its contributors may be used to endorse or promote products // derived from this software without specific prior written permission. // // 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 <COPYRIGHT HOLDER> 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 <mapviz_plugins/odometry_plugin.h> // C++ standard libraries #include <cstdio> #include <vector> // QT libraries #include <QDialog> #include <QGLWidget> #include <QPainter> #include <QPalette> #include <opencv2/core/core.hpp> // ROS libraries #include <ros/master.h> #include <swri_image_util/geometry_util.h> #include <swri_transform_util/transform_util.h> #include <mapviz/select_topic_dialog.h> // Declare plugin #include <pluginlib/class_list_macros.h> PLUGINLIB_EXPORT_CLASS(mapviz_plugins::OdometryPlugin, mapviz::MapvizPlugin) namespace mapviz_plugins { OdometryPlugin::OdometryPlugin() : config_widget_(new QWidget()) { ui_.setupUi(config_widget_); ui_.color->setColor(Qt::green); // Set background white QPalette p(config_widget_->palette()); p.setColor(QPalette::Background, Qt::white); config_widget_->setPalette(p); // Set status text red QPalette p3(ui_.status->palette()); p3.setColor(QPalette::Text, Qt::red); ui_.status->setPalette(p3); QObject::connect(ui_.selecttopic, SIGNAL(clicked()), this, SLOT(SelectTopic())); QObject::connect(ui_.topic, SIGNAL(editingFinished()), this, SLOT(TopicEdited())); QObject::connect(ui_.positiontolerance, SIGNAL(valueChanged(double)), this, SLOT(PositionToleranceChanged(double))); QObject::connect(ui_.buffersize, SIGNAL(valueChanged(int)), this, SLOT(BufferSizeChanged(int))); QObject::connect(ui_.drawstyle, SIGNAL(activated(QString)), this, SLOT(SetDrawStyle(QString))); QObject::connect(ui_.static_arrow_sizes, SIGNAL(clicked(bool)), this, SLOT(SetStaticArrowSizes(bool))); QObject::connect(ui_.arrow_size, SIGNAL(valueChanged(int)), this, SLOT(SetArrowSize(int))); QObject::connect(ui_.color, SIGNAL(colorEdited(const QColor&)), this, SLOT(SetColor(const QColor&))); QObject::connect(ui_.show_laps, SIGNAL(toggled(bool)), this, SLOT(LapToggled(bool))); QObject::connect(ui_.show_covariance, SIGNAL(toggled(bool)), this, SLOT(CovariancedToggled(bool))); QObject::connect(ui_.buttonResetBuffer, SIGNAL(pressed()), this, SLOT(ClearPoints())); } OdometryPlugin::~OdometryPlugin() { } void OdometryPlugin::SelectTopic() { ros::master::TopicInfo topic = mapviz::SelectTopicDialog::selectTopic("nav_msgs/Odometry"); if (!topic.name.empty()) { ui_.topic->setText(QString::fromStdString(topic.name)); TopicEdited(); } } void OdometryPlugin::TopicEdited() { std::string topic = ui_.topic->text().trimmed().toStdString(); if (topic != topic_) { initialized_ = false; ClearPoints(); has_message_ = false; PrintWarning("No messages received."); odometry_sub_.shutdown(); topic_ = topic; if (!topic.empty()) { odometry_sub_ = node_.subscribe( topic_, 1, &OdometryPlugin::odometryCallback, this); ROS_INFO("Subscribing to %s", topic_.c_str()); } } } void OdometryPlugin::odometryCallback( const nav_msgs::OdometryConstPtr odometry) { if (!has_message_) { initialized_ = true; has_message_ = true; } // Note that unlike some plugins, this one does not store nor rely on the // source_frame_ member variable. This one can potentially store many // messages with different source frames, so we need to store and transform // them individually. StampedPoint stamped_point; stamped_point.stamp = odometry->header.stamp; stamped_point.source_frame = odometry->header.frame_id; stamped_point.point = tf::Point(odometry->pose.pose.position.x, odometry->pose.pose.position.y, odometry->pose.pose.position.z); stamped_point.orientation = tf::Quaternion( odometry->pose.pose.orientation.x, odometry->pose.pose.orientation.y, odometry->pose.pose.orientation.z, odometry->pose.pose.orientation.w); if ( ui_.show_covariance->isChecked() ) { tf::Matrix3x3 tf_cov = swri_transform_util::GetUpperLeft(odometry->pose.covariance); if (tf_cov[0][0] < 100000 && tf_cov[1][1] < 100000) { cv::Mat cov_matrix_3d(3, 3, CV_32FC1); for (int32_t r = 0; r < 3; r++) { for (int32_t c = 0; c < 3; c++) { cov_matrix_3d.at<float>(r, c) = tf_cov[r][c]; } } cv::Mat cov_matrix_2d = swri_image_util::ProjectEllipsoid(cov_matrix_3d); if (!cov_matrix_2d.empty()) { stamped_point.cov_points = swri_image_util::GetEllipsePoints( cov_matrix_2d, stamped_point.point, 3, 32); stamped_point.transformed_cov_points = stamped_point.cov_points; } else { ROS_ERROR("Failed to project x, y, z covariance to xy-plane."); } } } pushPoint( std::move(stamped_point) ); } void OdometryPlugin::PrintError(const std::string& message) { PrintErrorHelper(ui_.status, message); } void OdometryPlugin::PrintInfo(const std::string& message) { PrintInfoHelper(ui_.status, message); } void OdometryPlugin::PrintWarning(const std::string& message) { PrintWarningHelper(ui_.status, message); } QWidget* OdometryPlugin::GetConfigWidget(QWidget* parent) { config_widget_->setParent(parent); return config_widget_; } bool OdometryPlugin::Initialize(QGLWidget* canvas) { canvas_ = canvas; SetColor(ui_.color->color()); return true; } void OdometryPlugin::Draw(double x, double y, double scale) { if (ui_.show_covariance->isChecked()) { DrawCovariance(); } if (DrawPoints(scale)) { PrintInfo("OK"); } } void OdometryPlugin::Paint(QPainter* painter, double x, double y, double scale) { //dont render any timestamps if the show_timestamps is set to 0 int interval = ui_.show_timestamps->value(); if (interval == 0) { return; } QTransform tf = painter->worldTransform(); QFont font("Helvetica", 10); painter->setFont(font); painter->save(); painter->resetTransform(); //set the draw color for the text to be the same as the rest QPen pen(QBrush(ui_.color->color()), 1); painter->setPen(pen); int counter = 0;//used to alternate between rendering text on some points for (const StampedPoint& point: points()) { if (point.transformed && counter % interval == 0)//this renders a timestamp every 'interval' points { QPointF qpoint = tf.map(QPointF(point.transformed_point.getX(), point.transformed_point.getY())); QString time; time.setNum(point.stamp.toSec(), 'g', 12); painter->drawText(qpoint, time); } counter++; } painter->restore(); } void OdometryPlugin::LoadConfig(const YAML::Node& node, const std::string& path) { if (node["topic"]) { std::string topic; node["topic"] >> topic; ui_.topic->setText(topic.c_str()); } if (node["color"]) { std::string color; node["color"] >> color; QColor qcolor(color.c_str()); SetColor(qcolor); ui_.color->setColor(qcolor); } if (node["draw_style"]) { std::string draw_style; node["draw_style"] >> draw_style; if (draw_style == "lines") { ui_.drawstyle->setCurrentIndex(0); SetDrawStyle( LINES ); } else if (draw_style == "points") { ui_.drawstyle->setCurrentIndex(1); SetDrawStyle( POINTS ); } else if (draw_style == "arrows") { ui_.drawstyle->setCurrentIndex(2); SetDrawStyle( ARROWS ); } } if (node["position_tolerance"]) { double position_tolerance; node["position_tolerance"] >> position_tolerance; ui_.positiontolerance->setValue(position_tolerance); PositionToleranceChanged(position_tolerance); } if (node["buffer_size"]) { double buffer_size; node["buffer_size"] >> buffer_size; ui_.buffersize->setValue(buffer_size); BufferSizeChanged(buffer_size); } if (node["show_covariance"]) { bool show_covariance = false; node["show_covariance"] >> show_covariance; ui_.show_covariance->setChecked(show_covariance); CovariancedToggled(show_covariance); } if (node["show_laps"]) { bool show_laps = false; node["show_laps"] >> show_laps; ui_.show_laps->setChecked(show_laps); LapToggled(show_laps); } if (node["static_arrow_sizes"]) { bool static_arrow_sizes = node["static_arrow_sizes"].as<bool>(); ui_.static_arrow_sizes->setChecked(static_arrow_sizes); SetStaticArrowSizes(static_arrow_sizes); } if (node["arrow_size"]) { double arrow_size = node["arrow_size"].as<int>(); ui_.arrow_size->setValue(arrow_size); SetArrowSize(arrow_size); } if (node["show_timestamps"]) { ui_.show_timestamps->setValue(node["show_timestamps"].as<int>()); } TopicEdited(); } void OdometryPlugin::SaveConfig(YAML::Emitter& emitter, const std::string& path) { std::string topic = ui_.topic->text().toStdString(); emitter << YAML::Key << "topic" << YAML::Value << topic; std::string color = ui_.color->color().name().toStdString(); emitter << YAML::Key << "color" << YAML::Value << color; std::string draw_style = ui_.drawstyle->currentText().toStdString(); emitter << YAML::Key << "draw_style" << YAML::Value << draw_style; emitter << YAML::Key << "position_tolerance" << YAML::Value << positionTolerance(); emitter << YAML::Key << "buffer_size" << YAML::Value << bufferSize(); bool show_laps = ui_.show_laps->isChecked(); emitter << YAML::Key << "show_laps" << YAML::Value << show_laps; bool show_covariance = ui_.show_covariance->isChecked(); emitter << YAML::Key << "show_covariance" << YAML::Value << show_covariance; emitter << YAML::Key << "static_arrow_sizes" << YAML::Value << ui_.static_arrow_sizes->isChecked(); emitter << YAML::Key << "arrow_size" << YAML::Value << ui_.arrow_size->value(); emitter << YAML::Key << "show_timestamps" << YAML::Value << ui_.show_timestamps->value(); } } <|endoftext|>
<commit_before>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file constraint_checker.cc **/ #include "modules/planning/constraint_checker/constraint_checker.h" #include "modules/common/log.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { namespace { template <typename T> bool WithinRange(const T v, const T lower, const T upper) { return lower <= v && v <= upper; } } bool ConstraintChecker::ValidTrajectory( const DiscretizedTrajectory& trajectory) { // TODO(all): this is wrong; must be set to trajectory time range; const double kMaxCheckRelativeTime = 2.0; for (const auto& p : trajectory.trajectory_points()) { double t = p.relative_time(); if (t > kMaxCheckRelativeTime) { break; } double lon_v = p.v(); if (!WithinRange(lon_v, FLAGS_speed_lower_bound, FLAGS_speed_upper_bound)) { ADEBUG << "Velocity at relative time " << t << " exceeds bound, value: " << lon_v << ", bound [" << FLAGS_speed_lower_bound << ", " << FLAGS_speed_upper_bound << "]."; return false; } double lon_a = p.a(); if (!WithinRange(lon_a, FLAGS_longitudinal_acceleration_lower_bound, FLAGS_longitudinal_acceleration_upper_bound)) { ADEBUG << "Longitudinal acceleration at relative time " << t << " exceeds bound, value: " << lon_a << ", bound [" << FLAGS_longitudinal_acceleration_lower_bound << ", " << FLAGS_longitudinal_acceleration_upper_bound << "]."; return false; } double kappa = p.path_point().kappa(); if (!WithinRange(kappa, -FLAGS_kappa_bound, FLAGS_kappa_bound)) { ADEBUG << "Kappa at relative time " << t << " exceeds bound, value: " << kappa << ", bound [" << -FLAGS_kappa_bound << ", " << FLAGS_kappa_bound << "]."; return false; } } for (std::size_t i = 1; i < trajectory.NumOfPoints(); ++i) { const auto& p0 = trajectory.TrajectoryPointAt(i - 1); const auto& p1 = trajectory.TrajectoryPointAt(i); if (p1.relative_time() > kMaxCheckRelativeTime) { break; } double t = p0.relative_time(); double dt = p1.relative_time() - p0.relative_time(); double d_lon_a = p1.a() - p0.a(); double lon_jerk = d_lon_a / dt; if (!WithinRange(lon_jerk, FLAGS_longitudinal_jerk_lower_bound, FLAGS_longitudinal_jerk_upper_bound)) { ADEBUG << "Longitudinal jerk at relative time " << t << " exceeds bound, value: " << lon_jerk << ", bound [" << FLAGS_longitudinal_jerk_lower_bound << ", " << FLAGS_longitudinal_jerk_upper_bound << "]."; return false; } double lat_a = p1.v() * p1.v() * p1.path_point().kappa(); if (!WithinRange(lat_a, -FLAGS_lateral_acceleration_bound, FLAGS_lateral_acceleration_bound)) { ADEBUG << "Lateral acceleration at relative time " << t << " exceeds bound, value: " << lat_a << ", bound [" << -FLAGS_lateral_acceleration_bound << ", " << FLAGS_lateral_acceleration_bound << "]."; return false; } double d_lat_a = p1.v() * p1.v() * p1.path_point().kappa() - p0.v() * p0.v() * p0.path_point().kappa(); double lat_jerk = d_lat_a / dt; if (!WithinRange(lat_jerk, -FLAGS_lateral_jerk_bound, FLAGS_lateral_jerk_bound)) { ADEBUG << "Lateral jerk at relative time " << t << " exceeds bound, value: " << lat_jerk << ", bound [" << -FLAGS_lateral_jerk_bound << ", " << FLAGS_lateral_jerk_bound << "]."; return false; } } return true; } } // namespace planning } // namespace apollo <commit_msg>Planning: check trajectory validity for the whole time length which is 8.0 seconds<commit_after>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file constraint_checker.cc **/ #include "modules/planning/constraint_checker/constraint_checker.h" #include "modules/common/log.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { namespace { template <typename T> bool WithinRange(const T v, const T lower, const T upper) { return lower <= v && v <= upper; } } bool ConstraintChecker::ValidTrajectory( const DiscretizedTrajectory& trajectory) { const double kMaxCheckRelativeTime = FLAGS_trajectory_time_length; for (const auto& p : trajectory.trajectory_points()) { double t = p.relative_time(); if (t > kMaxCheckRelativeTime) { break; } double lon_v = p.v(); if (!WithinRange(lon_v, FLAGS_speed_lower_bound, FLAGS_speed_upper_bound)) { ADEBUG << "Velocity at relative time " << t << " exceeds bound, value: " << lon_v << ", bound [" << FLAGS_speed_lower_bound << ", " << FLAGS_speed_upper_bound << "]."; return false; } double lon_a = p.a(); if (!WithinRange(lon_a, FLAGS_longitudinal_acceleration_lower_bound, FLAGS_longitudinal_acceleration_upper_bound)) { ADEBUG << "Longitudinal acceleration at relative time " << t << " exceeds bound, value: " << lon_a << ", bound [" << FLAGS_longitudinal_acceleration_lower_bound << ", " << FLAGS_longitudinal_acceleration_upper_bound << "]."; return false; } double kappa = p.path_point().kappa(); if (!WithinRange(kappa, -FLAGS_kappa_bound, FLAGS_kappa_bound)) { ADEBUG << "Kappa at relative time " << t << " exceeds bound, value: " << kappa << ", bound [" << -FLAGS_kappa_bound << ", " << FLAGS_kappa_bound << "]."; return false; } } for (std::size_t i = 1; i < trajectory.NumOfPoints(); ++i) { const auto& p0 = trajectory.TrajectoryPointAt(i - 1); const auto& p1 = trajectory.TrajectoryPointAt(i); if (p1.relative_time() > kMaxCheckRelativeTime) { break; } double t = p0.relative_time(); double dt = p1.relative_time() - p0.relative_time(); double d_lon_a = p1.a() - p0.a(); double lon_jerk = d_lon_a / dt; if (!WithinRange(lon_jerk, FLAGS_longitudinal_jerk_lower_bound, FLAGS_longitudinal_jerk_upper_bound)) { ADEBUG << "Longitudinal jerk at relative time " << t << " exceeds bound, value: " << lon_jerk << ", bound [" << FLAGS_longitudinal_jerk_lower_bound << ", " << FLAGS_longitudinal_jerk_upper_bound << "]."; return false; } double lat_a = p1.v() * p1.v() * p1.path_point().kappa(); if (!WithinRange(lat_a, -FLAGS_lateral_acceleration_bound, FLAGS_lateral_acceleration_bound)) { ADEBUG << "Lateral acceleration at relative time " << t << " exceeds bound, value: " << lat_a << ", bound [" << -FLAGS_lateral_acceleration_bound << ", " << FLAGS_lateral_acceleration_bound << "]."; return false; } double d_lat_a = p1.v() * p1.v() * p1.path_point().kappa() - p0.v() * p0.v() * p0.path_point().kappa(); double lat_jerk = d_lat_a / dt; if (!WithinRange(lat_jerk, -FLAGS_lateral_jerk_bound, FLAGS_lateral_jerk_bound)) { ADEBUG << "Lateral jerk at relative time " << t << " exceeds bound, value: " << lat_jerk << ", bound [" << -FLAGS_lateral_jerk_bound << ", " << FLAGS_lateral_jerk_bound << "]."; return false; } } return true; } } // namespace planning } // namespace apollo <|endoftext|>
<commit_before>// test program for quasi random numbers #include "Math/QuasiRandom.h" #include "Math/Random.h" #include "TH2.h" #include "TCanvas.h" #include "TApplication.h" //#include "TSopwatch.h" #include <iostream> using namespace ROOT::Math; int testQuasiRandom() { const int n = 10000; TH2D * h0 = new TH2D("h0","Pseudo-random Sequence",200,0,1,200,0,1); TH2D * h1 = new TH2D("h1","Sobol Sequence",200,0,1,200,0,1); TH2D * h2 = new TH2D("h2","Niederrer Sequence",200,0,1,200,0,1); RandomMT r0; QuasiRandomSobol r1(2); QuasiRandomNiederreiter r2(2); // generate n sequences double x[2]; for (unsigned int i = 0; i < n; ++i) { r0.RndmArray(2,x); h0->Fill(x[0],x[1]); } for (unsigned int i = 0; i < n; ++i) { r1.Next(x); h1->Fill(x[0],x[1]); } double vx[2*n]; r2.RndmArray(n,vx); for (unsigned int i = 0; i < n; ++i) { h2->Fill(vx[2*i],vx[2*i+1]); } TCanvas * c1 = new TCanvas("c1","Random sequence",600,1200); c1->Divide(1,3); c1->cd(1); h0->Draw("COLZ"); c1->cd(2); // check uniformity h1->Draw("COLZ"); c1->cd(3); h2->Draw("COLZ"); gPad->Update(); // test number of empty bins int nzerobins0 = 0; int nzerobins1 = 0; int nzerobins2 = 0; for (int i = 1; i <= h1->GetNbinsX(); ++i) { for (int j = 1; j <= h1->GetNbinsY(); ++j) { if (h0->GetBinContent(i,j) == 0 ) nzerobins0++; if (h1->GetBinContent(i,j) == 0 ) nzerobins1++; if (h2->GetBinContent(i,j) == 0 ) nzerobins2++; } } std::cout << "number of empty bins for pseudo-random = " << nzerobins0 << std::endl; std::cout << "number of empty bins for Sobol = " << nzerobins1 << std::endl; std::cout << "number of empty bins for Niederreiter = " << nzerobins2 << std::endl; int iret = 0; if (nzerobins1 >= nzerobins0 ) iret += 1; if (nzerobins2 >= nzerobins0 ) iret += 2; return iret; } int main(int argc, char **argv) { std::cout << "***************************************************\n"; std::cout << " TEST QUASI-RANDOM generators "<< std::endl; std::cout << "***************************************************\n\n"; int iret = 0; if (argc > 1) { TApplication theApp("App",&argc,argv); iret = testQuasiRandom(); theApp.Run(); } else iret = testQuasiRandom(); if (iret != 0) std::cerr << "TEST QUASI-RANDOM FAILED " << std::endl; return iret; } <commit_msg>Fix a warning and improve handling of graphics<commit_after>// test program for quasi random numbers #include "Math/QuasiRandom.h" #include "Math/Random.h" #include "TH2.h" #include "TCanvas.h" #include "TApplication.h" //#include "TSopwatch.h" #include <iostream> using namespace ROOT::Math; bool showGraphics = false; int testQuasiRandom() { const int n = 10000; TH2D * h0 = new TH2D("h0","Pseudo-random Sequence",200,0,1,200,0,1); TH2D * h1 = new TH2D("h1","Sobol Sequence",200,0,1,200,0,1); TH2D * h2 = new TH2D("h2","Niederrer Sequence",200,0,1,200,0,1); RandomMT r0; QuasiRandomSobol r1(2); QuasiRandomNiederreiter r2(2); // generate n sequences double x[2]; for (int i = 0; i < n; ++i) { r0.RndmArray(2,x); h0->Fill(x[0],x[1]); } for (int i = 0; i < n; ++i) { r1.Next(x); h1->Fill(x[0],x[1]); } double vx[2*n]; r2.RndmArray(n,vx); for (int i = 0; i < n; ++i) { h2->Fill(vx[2*i],vx[2*i+1]); } if (showGraphics) { TCanvas * c1 = new TCanvas("c1","Random sequence",600,1200); c1->Divide(1,3); c1->cd(1); h0->Draw("COLZ"); c1->cd(2); // check uniformity h1->Draw("COLZ"); c1->cd(3); h2->Draw("COLZ"); gPad->Update(); } // test number of empty bins int nzerobins0 = 0; int nzerobins1 = 0; int nzerobins2 = 0; for (int i = 1; i <= h1->GetNbinsX(); ++i) { for (int j = 1; j <= h1->GetNbinsY(); ++j) { if (h0->GetBinContent(i,j) == 0 ) nzerobins0++; if (h1->GetBinContent(i,j) == 0 ) nzerobins1++; if (h2->GetBinContent(i,j) == 0 ) nzerobins2++; } } std::cout << "number of empty bins for pseudo-random = " << nzerobins0 << std::endl; std::cout << "number of empty bins for Sobol = " << nzerobins1 << std::endl; std::cout << "number of empty bins for Niederreiter = " << nzerobins2 << std::endl; int iret = 0; if (nzerobins1 >= nzerobins0 ) iret += 1; if (nzerobins2 >= nzerobins0 ) iret += 2; return iret; } int main(int argc, char **argv) { std::cout << "***************************************************\n"; std::cout << " TEST QUASI-RANDOM generators "<< std::endl; std::cout << "***************************************************\n\n"; // Parse command line arguments for (Int_t i=1 ; i<argc ; i++) { std::string arg = argv[i] ; if (arg == "-g") { showGraphics = true; } if (arg == "-h") { std::cout << "Usage: " << argv[0] << " [-g] [-v]\n"; std::cout << " where:\n"; std::cout << " -g : graphics mode\n"; std::cout << std::endl; return -1; } } TApplication* theApp = 0; if ( showGraphics ) theApp = new TApplication("App",&argc,argv); int iret = testQuasiRandom(); if ( showGraphics ) { theApp->Run(); delete theApp; } if (iret != 0) std::cerr << "TEST QUASI-RANDOM FAILED " << std::endl; return iret; } <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <vector> #include "media/base/mock_filters.h" #include "media/filters/decoder_base.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using ::testing::NotNull; namespace media { class MockOutput : public StreamSample { MOCK_CONST_METHOD0(IsEndOfStream, bool()); }; class MockDecoder : public MediaFilter {}; class MockBuffer : public Buffer { public: MOCK_CONST_METHOD0(GetData, const uint8*()); MOCK_CONST_METHOD0(GetDataSize, size_t()); }; ACTION(Initialize) { AutoTaskRunner done_runner(arg2); *arg1 = true; } ACTION_P(SaveDecodeRequest, list) { scoped_refptr<Buffer> buffer = arg0; list->push_back(arg1); } ACTION(CompleteDemuxRequest) { arg0->Run(new MockBuffer()); delete arg0; } class MockDecoderImpl : public DecoderBase<MockDecoder, MockOutput> { public: MockDecoderImpl() { media_format_.SetAsString(MediaFormat::kMimeType, "mock"); } // DecoderBase Implementations. MOCK_METHOD3(DoInitialize, void(DemuxerStream* demuxer_stream, bool* success, Task* done_cb)); MOCK_METHOD0(DoStop, void()); MOCK_METHOD2(DoSeek, void(base::TimeDelta time, Task* done_cb)); MOCK_METHOD2(DoDecode, void(Buffer* input, Task* done_cb)); private: FRIEND_TEST(DecoderBaseTest, FlowControl); DISALLOW_COPY_AND_ASSIGN(MockDecoderImpl); }; class MockReadCallback { public: MockReadCallback() {} MOCK_METHOD1(ReadCallback, void(MockOutput* output)); private: DISALLOW_COPY_AND_ASSIGN(MockReadCallback); }; // Test the flow control of decoder base by the following sequnce of actions: // - Read() -> DecoderStream // \ Read() -> DemuxerStream // - Read() -> DecoderBase // \ Read() -> DemixerStream // - ReadCallback() -> DecoderBase // \ DoDecode() -> Decoder // - ReadCallback() -> DecoderBase // \ DoDecode() -> Decoder // - DecodeCallback() -> DecoderBase // \ ReadCallback() -> client // - DecodeCallback() -> DecoderBase // \ ReadCallback() -> client TEST(DecoderBaseTest, FlowControl) { MessageLoop message_loop; scoped_refptr<MockDecoderImpl> decoder = new MockDecoderImpl(); scoped_refptr<MockDemuxerStream> demuxer_stream = new MockDemuxerStream(); MockFilterCallback callback; MockReadCallback read_callback; decoder->set_message_loop(&message_loop); // Initailize. EXPECT_CALL(callback, OnFilterCallback()); EXPECT_CALL(callback, OnCallbackDestroyed()); EXPECT_CALL(*decoder, DoInitialize(NotNull(), NotNull(), NotNull())) .WillOnce(Initialize()); decoder->Initialize(demuxer_stream.get(), callback.NewCallback()); message_loop.RunAllPending(); // Read. std::vector<Task*> decode_requests; EXPECT_CALL(*demuxer_stream, Read(NotNull())) .Times(2) .WillRepeatedly(CompleteDemuxRequest()); EXPECT_CALL(*decoder, DoDecode(NotNull(), NotNull())) .Times(2) .WillRepeatedly(SaveDecodeRequest(&decode_requests)); decoder->Read(NewCallback(&read_callback, &MockReadCallback::ReadCallback)); decoder->Read(NewCallback(&read_callback, &MockReadCallback::ReadCallback)); message_loop.RunAllPending(); // Fulfill the decode request. EXPECT_CALL(read_callback, ReadCallback(NotNull())).Times(2); for (size_t i = 0; i < decode_requests.size(); ++i) { decoder->EnqueueResult(new MockOutput()); AutoTaskRunner done_cb(decode_requests[i]); } decode_requests.clear(); message_loop.RunAllPending(); // Stop. EXPECT_CALL(*decoder, DoStop()); decoder->Stop(); message_loop.RunAllPending(); } } // namespace media <commit_msg>Disable a media unit test<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <vector> #include "media/base/mock_filters.h" #include "media/filters/decoder_base.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using ::testing::NotNull; namespace media { class MockOutput : public StreamSample { MOCK_CONST_METHOD0(IsEndOfStream, bool()); }; class MockDecoder : public MediaFilter {}; class MockBuffer : public Buffer { public: MOCK_CONST_METHOD0(GetData, const uint8*()); MOCK_CONST_METHOD0(GetDataSize, size_t()); }; ACTION(Initialize) { AutoTaskRunner done_runner(arg2); *arg1 = true; } ACTION_P(SaveDecodeRequest, list) { scoped_refptr<Buffer> buffer = arg0; list->push_back(arg1); } ACTION(CompleteDemuxRequest) { arg0->Run(new MockBuffer()); delete arg0; } class MockDecoderImpl : public DecoderBase<MockDecoder, MockOutput> { public: MockDecoderImpl() { media_format_.SetAsString(MediaFormat::kMimeType, "mock"); } // DecoderBase Implementations. MOCK_METHOD3(DoInitialize, void(DemuxerStream* demuxer_stream, bool* success, Task* done_cb)); MOCK_METHOD0(DoStop, void()); MOCK_METHOD2(DoSeek, void(base::TimeDelta time, Task* done_cb)); MOCK_METHOD2(DoDecode, void(Buffer* input, Task* done_cb)); private: FRIEND_TEST(DecoderBaseTest, FlowControl); DISALLOW_COPY_AND_ASSIGN(MockDecoderImpl); }; class MockReadCallback { public: MockReadCallback() {} MOCK_METHOD1(ReadCallback, void(MockOutput* output)); private: DISALLOW_COPY_AND_ASSIGN(MockReadCallback); }; // Test the flow control of decoder base by the following sequnce of actions: // - Read() -> DecoderStream // \ Read() -> DemuxerStream // - Read() -> DecoderBase // \ Read() -> DemixerStream // - ReadCallback() -> DecoderBase // \ DoDecode() -> Decoder // - ReadCallback() -> DecoderBase // \ DoDecode() -> Decoder // - DecodeCallback() -> DecoderBase // \ ReadCallback() -> client // - DecodeCallback() -> DecoderBase // \ ReadCallback() -> client TEST(DecoderBaseTest, DISABLED_FlowControl) { MessageLoop message_loop; scoped_refptr<MockDecoderImpl> decoder = new MockDecoderImpl(); scoped_refptr<MockDemuxerStream> demuxer_stream = new MockDemuxerStream(); MockFilterCallback callback; MockReadCallback read_callback; decoder->set_message_loop(&message_loop); // Initailize. EXPECT_CALL(callback, OnFilterCallback()); EXPECT_CALL(callback, OnCallbackDestroyed()); EXPECT_CALL(*decoder, DoInitialize(NotNull(), NotNull(), NotNull())) .WillOnce(Initialize()); decoder->Initialize(demuxer_stream.get(), callback.NewCallback()); message_loop.RunAllPending(); // Read. std::vector<Task*> decode_requests; EXPECT_CALL(*demuxer_stream, Read(NotNull())) .Times(2) .WillRepeatedly(CompleteDemuxRequest()); EXPECT_CALL(*decoder, DoDecode(NotNull(), NotNull())) .Times(2) .WillRepeatedly(SaveDecodeRequest(&decode_requests)); decoder->Read(NewCallback(&read_callback, &MockReadCallback::ReadCallback)); decoder->Read(NewCallback(&read_callback, &MockReadCallback::ReadCallback)); message_loop.RunAllPending(); // Fulfill the decode request. EXPECT_CALL(read_callback, ReadCallback(NotNull())).Times(2); for (size_t i = 0; i < decode_requests.size(); ++i) { decoder->EnqueueResult(new MockOutput()); AutoTaskRunner done_cb(decode_requests[i]); } decode_requests.clear(); message_loop.RunAllPending(); // Stop. EXPECT_CALL(*decoder, DoStop()); decoder->Stop(); message_loop.RunAllPending(); } } // namespace media <|endoftext|>
<commit_before> #include "jnif.h" static jmethodID m_eobject__testNumber; static jmethodID m_enumber__doubleValue; static jmethodID m_enumber__intValue; static jmethodID m_enumber__longValue; static jclass ERT_class; static jmethodID m_ERT__box_int; static jmethodID m_ERT__box_long; static jmethodID m_ERT__box_double; static jmethodID m_ERT__box_parse; static uint32_t INT_MAX_VALUE; static uint64_t LONG_MAX_VALUE; void initialize_jnif_number(JavaVM* vm, JNIEnv *je) { jclass eobject_class = je->FindClass("erjang/EObject"); m_eobject__testNumber = je->GetMethodID(eobject_class, "testNumber", "()Lerjang/ENumber;"); jclass enumber_class = je->FindClass("erjang/ENumber"); m_enumber__doubleValue = je->GetMethodID(enumber_class, "doubleValue", "()D"); m_enumber__intValue = je->GetMethodID(enumber_class, "intValue", "()I"); m_enumber__longValue = je->GetMethodID(enumber_class, "longValue", "()J"); ERT_class = (jclass) je->NewGlobalRef ( je->FindClass("erjang/ERT") ); m_ERT__box_int = je->GetStaticMethodID (ERT_class, "box", "(I)Lerjang/ESmall;"); m_ERT__box_long = je->GetStaticMethodID (ERT_class, "box", "(J)Lerjang/EInteger;"); m_ERT__box_double = je->GetStaticMethodID (ERT_class, "box", "(D)Lerjang/EDouble;"); m_ERT__box_parse = je->GetStaticMethodID (ERT_class, "box_parse", "(Ljava/lang/String;)Lerjang/EInteger;"); jclass Integer_class = je->FindClass("java/lang/Integer"); jfieldID f_int_max_value = je->GetStaticFieldID(Integer_class, "MAX_VALUE", "I"); INT_MAX_VALUE = je->GetStaticIntField(Integer_class, f_int_max_value); jclass Long_class = je->FindClass("java/lang/Long"); jfieldID f_long_max_value = je->GetStaticFieldID(Long_class, "MAX_VALUE", "J"); LONG_MAX_VALUE = je->GetStaticLongField(Long_class, f_long_max_value); } int enif_get_double(ErlNifEnv* ee, ERL_NIF_TERM term, double* dp) { jobject o = ee->je->CallObjectMethod(E2J(term), m_eobject__testNumber); if (o == NULL) return NIF_FALSE; *dp = ee->je->CallDoubleMethod(o, m_enumber__doubleValue); return NIF_TRUE; } int enif_get_int(ErlNifEnv* ee, ERL_NIF_TERM term, int* ip) { jobject o = ee->je->CallObjectMethod(E2J(term), m_eobject__testNumber); if (o == NULL) return NIF_FALSE; *ip = ee->je->CallIntMethod(o, m_enumber__intValue); return NIF_TRUE; } int enif_get_int64(ErlNifEnv* ee, ERL_NIF_TERM term, ErlNifSInt64* ip) { jobject o = ee->je->CallObjectMethod(E2J(term), m_eobject__testNumber); if (o == NULL) return NIF_FALSE; *ip = (jlong) ee->je->CallLongMethod(o, m_enumber__longValue); return NIF_TRUE; } int enif_get_uint(ErlNifEnv* ee, ERL_NIF_TERM term, unsigned* ip) { jobject o = ee->je->CallObjectMethod(E2J(term), m_eobject__testNumber); if (o == NULL) return NIF_FALSE; jlong value = ee->je->CallLongMethod(o, m_enumber__longValue); if (value < 0) return NIF_FALSE; *ip = (jlong) value; return NIF_TRUE; } extern ERL_NIF_TERM enif_make_uint (ErlNifEnv* ee, unsigned i) { jobject boxed; if (i > INT_MAX_VALUE) { boxed = ee->je->CallStaticObjectMethod(ERT_class, m_ERT__box_long, (jlong) i); } else { boxed = ee->je->CallStaticObjectMethod(ERT_class, m_ERT__box_int, (jint) i); } return jnif_retain(ee, boxed); } extern ERL_NIF_TERM enif_make_int (ErlNifEnv* ee, int i) { jobject boxed; boxed = ee->je->CallStaticObjectMethod(ERT_class, m_ERT__box_int, (jint) i); return jnif_retain(ee, boxed); } extern ERL_NIF_TERM enif_make_ulong (ErlNifEnv* ee, unsigned long i) { jobject boxed; if (i > LONG_MAX_VALUE) { const int n = snprintf(NULL, 0, "%lu", i); assert(n > 0); char buf[n+1]; int c = snprintf(buf, n+1, "%lu", i); assert(buf[n] == '\0'); jobject str = ee->je->NewStringUTF(buf); boxed = ee->je->CallStaticObjectMethod(ERT_class, m_ERT__box_parse, buf); } else { boxed = ee->je->CallStaticObjectMethod(ERT_class, m_ERT__box_long, (jlong) i); } return jnif_retain(ee, boxed); } <commit_msg>Add enif_is_number<commit_after> #include "jnif.h" static jmethodID m_eobject__testNumber; static jmethodID m_enumber__doubleValue; static jmethodID m_enumber__intValue; static jmethodID m_enumber__longValue; static jclass ERT_class; static jmethodID m_ERT__box_int; static jmethodID m_ERT__box_long; static jmethodID m_ERT__box_double; static jmethodID m_ERT__box_parse; static uint32_t INT_MAX_VALUE; static uint64_t LONG_MAX_VALUE; void initialize_jnif_number(JavaVM* vm, JNIEnv *je) { jclass eobject_class = je->FindClass("erjang/EObject"); m_eobject__testNumber = je->GetMethodID(eobject_class, "testNumber", "()Lerjang/ENumber;"); jclass enumber_class = je->FindClass("erjang/ENumber"); m_enumber__doubleValue = je->GetMethodID(enumber_class, "doubleValue", "()D"); m_enumber__intValue = je->GetMethodID(enumber_class, "intValue", "()I"); m_enumber__longValue = je->GetMethodID(enumber_class, "longValue", "()J"); ERT_class = (jclass) je->NewGlobalRef ( je->FindClass("erjang/ERT") ); m_ERT__box_int = je->GetStaticMethodID (ERT_class, "box", "(I)Lerjang/ESmall;"); m_ERT__box_long = je->GetStaticMethodID (ERT_class, "box", "(J)Lerjang/EInteger;"); m_ERT__box_double = je->GetStaticMethodID (ERT_class, "box", "(D)Lerjang/EDouble;"); m_ERT__box_parse = je->GetStaticMethodID (ERT_class, "box_parse", "(Ljava/lang/String;)Lerjang/EInteger;"); jclass Integer_class = je->FindClass("java/lang/Integer"); jfieldID f_int_max_value = je->GetStaticFieldID(Integer_class, "MAX_VALUE", "I"); INT_MAX_VALUE = je->GetStaticIntField(Integer_class, f_int_max_value); jclass Long_class = je->FindClass("java/lang/Long"); jfieldID f_long_max_value = je->GetStaticFieldID(Long_class, "MAX_VALUE", "J"); LONG_MAX_VALUE = je->GetStaticLongField(Long_class, f_long_max_value); } int enif_is_number(ErlNifEnv* ee, ERL_NIF_TERM term) { if (ee->je->CallObjectMethod( E2J(term), m_eobject__testNumber ) != NULL) { return NIF_TRUE; } else { return NIF_FALSE; } } int enif_get_double(ErlNifEnv* ee, ERL_NIF_TERM term, double* dp) { jobject o = ee->je->CallObjectMethod(E2J(term), m_eobject__testNumber); if (o == NULL) return NIF_FALSE; *dp = ee->je->CallDoubleMethod(o, m_enumber__doubleValue); return NIF_TRUE; } int enif_get_int(ErlNifEnv* ee, ERL_NIF_TERM term, int* ip) { jobject o = ee->je->CallObjectMethod(E2J(term), m_eobject__testNumber); if (o == NULL) return NIF_FALSE; *ip = ee->je->CallIntMethod(o, m_enumber__intValue); return NIF_TRUE; } int enif_get_int64(ErlNifEnv* ee, ERL_NIF_TERM term, ErlNifSInt64* ip) { jobject o = ee->je->CallObjectMethod(E2J(term), m_eobject__testNumber); if (o == NULL) return NIF_FALSE; *ip = (jlong) ee->je->CallLongMethod(o, m_enumber__longValue); return NIF_TRUE; } int enif_get_uint(ErlNifEnv* ee, ERL_NIF_TERM term, unsigned* ip) { jobject o = ee->je->CallObjectMethod(E2J(term), m_eobject__testNumber); if (o == NULL) return NIF_FALSE; jlong value = ee->je->CallLongMethod(o, m_enumber__longValue); if (value < 0) return NIF_FALSE; *ip = (jlong) value; return NIF_TRUE; } extern ERL_NIF_TERM enif_make_uint (ErlNifEnv* ee, unsigned i) { jobject boxed; if (i > INT_MAX_VALUE) { boxed = ee->je->CallStaticObjectMethod(ERT_class, m_ERT__box_long, (jlong) i); } else { boxed = ee->je->CallStaticObjectMethod(ERT_class, m_ERT__box_int, (jint) i); } return jnif_retain(ee, boxed); } extern ERL_NIF_TERM enif_make_int (ErlNifEnv* ee, int i) { jobject boxed; boxed = ee->je->CallStaticObjectMethod(ERT_class, m_ERT__box_int, (jint) i); return jnif_retain(ee, boxed); } extern ERL_NIF_TERM enif_make_ulong (ErlNifEnv* ee, unsigned long i) { jobject boxed; if (i > LONG_MAX_VALUE) { const int n = snprintf(NULL, 0, "%lu", i); assert(n > 0); char buf[n+1]; int c = snprintf(buf, n+1, "%lu", i); assert(buf[n] == '\0'); jobject str = ee->je->NewStringUTF(buf); boxed = ee->je->CallStaticObjectMethod(ERT_class, m_ERT__box_parse, buf); } else { boxed = ee->je->CallStaticObjectMethod(ERT_class, m_ERT__box_long, (jlong) i); } return jnif_retain(ee, boxed); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: DrawViewWrapper.cxx,v $ * * $Revision: 1.14 $ * * last change: $Author: kz $ $Date: 2006-12-12 16:45:16 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_chart2.hxx" #include "DrawViewWrapper.hxx" #include "DrawModelWrapper.hxx" #include "ConfigurationAccess.hxx" #include "ViewSingletons.hxx" // header for class SdrPage #ifndef _SVDPAGE_HXX #include <svx/svdpage.hxx> #endif //header for class SdrPageView #ifndef _SVDPAGV_HXX #include <svx/svdpagv.hxx> #endif // header for class SdrModel #ifndef _SVDMODEL_HXX #include <svx/svdmodel.hxx> #endif #ifndef _SVDETC_HXX #include <svx/svdetc.hxx> #endif #ifndef _SVDOUTL_HXX #include <svx/svdoutl.hxx> #endif // header for class SvxForbiddenCharactersTable #ifndef _FORBIDDENCHARACTERSTABLE_HXX #include <svx/forbiddencharacterstable.hxx> #endif #ifndef _SVX_SVXIDS_HRC #include <svx/svxids.hrc> #endif //............................................................................. namespace chart { //............................................................................. /* void lcl_initOutliner( SdrOutliner* pTargetOutliner, SdrOutliner* pSourceOutliner ) { //just an unsuccessful try to initialize the text edit outliner correctly //if( bInit ) { pTargetOutliner->EraseVirtualDevice(); pTargetOutliner->SetUpdateMode(FALSE); pTargetOutliner->SetEditTextObjectPool( pSourceOutliner->GetEditTextObjectPool() ); pTargetOutliner->SetDefTab( pSourceOutliner->GetDefTab() ); } pTargetOutliner->SetRefDevice( pSourceOutliner->GetRefDevice() ); pTargetOutliner->SetForbiddenCharsTable( pSourceOutliner->GetForbiddenCharsTable() ); pTargetOutliner->SetAsianCompressionMode( pSourceOutliner->GetAsianCompressionMode() ); pTargetOutliner->SetKernAsianPunctuation( pSourceOutliner->IsKernAsianPunctuation() ); pTargetOutliner->SetStyleSheetPool( pSourceOutliner->GetStyleSheetPool() ); pTargetOutliner->SetRefMapMode( pSourceOutliner->GetRefMapMode() ); pTargetOutliner->SetDefaultLanguage( pSourceOutliner->GetDefaultLanguage() ); pTargetOutliner->SetHyphenator( pSourceOutliner->GetHyphenator() ); USHORT nX, nY; pSourceOutliner->GetGlobalCharStretching( nX, nY ); pTargetOutliner->SetGlobalCharStretching( nX, nY ); *//* if ( !GetRefDevice() ) { MapMode aMapMode(eObjUnit, Point(0,0), aObjUnit, aObjUnit); pTargetOutliner->SetRefMapMode(aMapMode); } *//* } */ DrawViewWrapper::DrawViewWrapper( SdrModel* pSdrModel, OutputDevice* pOut) : E3dView(pSdrModel, pOut) , m_pWrappedDLPageView(NULL) , m_pMarkHandleProvider(NULL) , m_apOutliner( SdrMakeOutliner( OUTLINERMODE_TEXTOBJECT, pSdrModel ) ) { // #114898# SetBufferedOutputAllowed(true); SetBufferedOverlayAllowed(true); ReInit(); } void DrawViewWrapper::ReInit() { OutputDevice* pOutDev = this->GetFirstOutputDevice(); Size aOutputSize(100,100); if(pOutDev) aOutputSize = pOutDev->GetOutputSize(); m_pWrappedDLPageView = this->ShowSdrPage(this->GetModel()->GetPage(0)); m_pWrappedDLPageView->GetPage()->SetSize( aOutputSize ); this->SetPageBorderVisible(false); this->SetBordVisible(false); this->SetGridVisible(false); this->SetGridFront(false); this->SetHlplVisible(false); this->SetNoDragXorPolys(true);//for interactive 3D resize-dragging: paint only a single rectangle (not a simulated 3D object) //this->SetResizeAtCenter(true);//for interactive resize-dragging: keep the object center fix //a correct work area is at least necessary for correct values in the position and size dialog //Rectangle aRect = pOutDev->PixelToLogic(Rectangle(Point(0,0), aOutputSize)); Rectangle aRect(Point(0,0), aOutputSize); this->SetWorkArea(aRect); } DrawViewWrapper::~DrawViewWrapper() { m_pWrappedDLPageView = NULL;//@ todo: sufficient? or remove necessary aComeBackTimer.Stop();//@todo this should be done in destructor of base class } //virtual void DrawViewWrapper::SetMarkHandles() { if( m_pMarkHandleProvider && m_pMarkHandleProvider->getMarkHandles( aHdl ) ) return; else SdrView::SetMarkHandles(); } SdrObject* DrawViewWrapper::getHitObject( const Point& rPnt ) const { const short HITPIX=2; //hit-tolerance in pixel SdrObject* pRet = NULL; //ULONG nOptions =SDRSEARCH_DEEP|SDRSEARCH_PASS2BOUND|SDRSEARCH_PASS3NEAREST; //ULONG nOptions = SDRSEARCH_TESTMARKABLE; ULONG nOptions = SDRSEARCH_DEEP | SDRSEARCH_TESTMARKABLE; //ULONG nOptions = SDRSEARCH_DEEP|SDRSEARCH_ALSOONMASTER|SDRSEARCH_WHOLEPAGE|SDRSEARCH_PASS2BOUND|SDRSEARCH_PASS3NEAREST; //ULONG nOptions = 0; short nHitTolerance = 50; { OutputDevice* pOutDev = this->GetFirstOutputDevice(); if(pOutDev) nHitTolerance = static_cast<short>(pOutDev->PixelToLogic(Size(HITPIX,0)).Width()); } this->SdrView::PickObj(rPnt, nHitTolerance, pRet, m_pWrappedDLPageView, nOptions); return pRet; } void DrawViewWrapper::MarkObject( SdrObject* pObj ) { bool bFrameDragSingles = true;//true == green == surrounding handles pObj->SetMarkProtect(false); if( m_pMarkHandleProvider ) bFrameDragSingles = m_pMarkHandleProvider->getFrameDragSingles(); this->SetFrameDragSingles(bFrameDragSingles);//decide wether each single object should get handles this->SdrView::MarkObj( pObj, m_pWrappedDLPageView ); this->showMarkHandles(); } void DrawViewWrapper::setMarkHandleProvider( MarkHandleProvider* pMarkHandleProvider ) { m_pMarkHandleProvider = pMarkHandleProvider; } void DrawViewWrapper::CompleteRedraw( OutputDevice* pOut, const Region& rReg ) { svtools::ColorConfig aColorConfig; Color aFillColor = Color( aColorConfig.GetColorValue( svtools::DOCCOLOR ).nColor ); this->SetApplicationBackgroundColor(aFillColor); this->E3dView::CompleteRedraw( pOut, rReg ); } SdrObject* DrawViewWrapper::getSelectedObject() const { SdrObject* pObj(NULL); const SdrMarkList& rMarkList = this->GetMarkedObjectList(); if(rMarkList.GetMarkCount() == 1) { SdrMark* pMark = rMarkList.GetMark(0); pObj = pMark->GetMarkedSdrObj(); } return pObj; } SdrObject* DrawViewWrapper::getTextEditObject() const { SdrObject* pObj = this->getSelectedObject(); SdrObject* pTextObj = NULL; if( pObj && pObj->HasTextEdit()) pTextObj = (SdrTextObj*)pObj; return pTextObj; } SdrOutliner* DrawViewWrapper::getOutliner() const { // lcl_initOutliner( m_apOutliner.get(), &GetModel()->GetDrawOutliner() ); return m_apOutliner.get(); } SfxItemSet DrawViewWrapper::getPositionAndSizeItemSetFromMarkedObject() const { SfxItemSet aFullSet( GetModel()->GetItemPool(), SID_ATTR_TRANSFORM_POS_X,SID_ATTR_TRANSFORM_ANGLE, SID_ATTR_TRANSFORM_PROTECT_POS,SID_ATTR_TRANSFORM_AUTOHEIGHT, SDRATTR_ECKENRADIUS,SDRATTR_ECKENRADIUS, SID_ATTR_METRIC,SID_ATTR_METRIC, 0); SfxItemSet aGeoSet( E3dView::GetGeoAttrFromMarked() ); aFullSet.Put( aGeoSet ); aFullSet.Put( SfxUInt16Item(SID_ATTR_METRIC,ViewSingletons::getConfigurationAccess()->getFieldUnit()) ); return aFullSet; } //............................................................................. } //namespace chart //............................................................................. <commit_msg>INTEGRATION: CWS chart2mst3 (1.9.8); FILE MERGED 2007/02/07 13:07:24 iha 1.9.8.18: RESYNC: (1.13-1.14); FILE MERGED 2006/11/28 10:46:19 bm 1.9.8.17: aw024 adaption corrected 2006/11/26 11:34:14 bm 1.9.8.16: aw024 adaptions 2006/11/24 21:42:22 iha 1.9.8.15: incompatibel changes for aw024 2006/11/22 17:23:52 iha 1.9.8.14: RESYNC: (1.12-1.13); FILE MERGED 2006/10/20 21:07:38 iha 1.9.8.13: implement selection of additional shapes 2006/10/18 17:05:30 bm 1.9.8.12: RESYNC: (1.10-1.12); FILE MERGED 2006/08/08 12:27:46 iha 1.9.8.11: avoid a paint call during the destructor hierarchy 2006/04/03 12:06:59 iha 1.9.8.10: prevent wrong reselection caused by ComeBackTimer of Draw 2006/02/22 16:40:15 bm 1.9.8.9: getNamedSdrObject: select nothing if name is an empty string 2005/11/29 18:00:19 bm 1.9.8.8: -ViewSingletons, ConfigurationAccess is a singleton itself now 2005/10/07 11:23:51 bm 1.9.8.7: RESYNC: (1.9-1.10); FILE MERGED 2005/09/13 17:31:57 iha 1.9.8.6: enable selection of 3D objects in scene 2005/08/30 14:44:17 bm 1.9.8.5: +attachParentReferenceDevice 2005/08/29 08:25:03 iha 1.9.8.4: don't hold separat PageView 2005/07/05 15:39:58 iha 1.9.8.3: redefine diagram size 2005/06/03 14:33:40 iha 1.9.8.2: don't manipulate page size in drawview 2005/05/31 19:08:17 iha 1.9.8.1: create view without controller<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: DrawViewWrapper.cxx,v $ * * $Revision: 1.15 $ * * last change: $Author: vg $ $Date: 2007-05-22 17:51:08 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_chart2.hxx" #include "DrawViewWrapper.hxx" #include "chartview/DrawModelWrapper.hxx" #include "ConfigurationAccess.hxx" // header for class SdrPage #ifndef _SVDPAGE_HXX #include <svx/svdpage.hxx> #endif //header for class SdrPageView #ifndef _SVDPAGV_HXX #include <svx/svdpagv.hxx> #endif // header for class SdrModel #ifndef _SVDMODEL_HXX #include <svx/svdmodel.hxx> #endif // header for class E3dScene #ifndef _E3D_SCENE3D_HXX #include <svx/scene3d.hxx> #endif #ifndef _SVDETC_HXX #include <svx/svdetc.hxx> #endif #ifndef _SVDOUTL_HXX #include <svx/svdoutl.hxx> #endif // header for class SvxForbiddenCharactersTable #ifndef _FORBIDDENCHARACTERSTABLE_HXX #include <svx/forbiddencharacterstable.hxx> #endif #ifndef _SVX_SVXIDS_HRC #include <svx/svxids.hrc> #endif // header for class SvxShape #ifndef _SVX_UNOSHAPE_HXX #include <svx/unoshape.hxx> #endif #include <com/sun/star/container/XChild.hpp> #include <com/sun/star/lang/XUnoTunnel.hpp> #include <sfx2/objsh.hxx> using namespace ::com::sun::star; //............................................................................. namespace chart { //............................................................................. namespace { short lcl_getHitTolerance( OutputDevice* pOutDev ) { const short HITPIX=2; //hit-tolerance in pixel short nHitTolerance = 50; if(pOutDev) nHitTolerance = static_cast<short>(pOutDev->PixelToLogic(Size(HITPIX,0)).Width()); return nHitTolerance; } // this code is copied from sfx2/source/doc/objembed.cxx SfxObjectShell * lcl_GetParentObjectShell( const uno::Reference< frame::XModel > & xModel ) { SfxObjectShell* pResult = NULL; try { uno::Reference< container::XChild > xChildModel( xModel, uno::UNO_QUERY ); if ( xChildModel.is() ) { uno::Reference< lang::XUnoTunnel > xParentTunnel( xChildModel->getParent(), uno::UNO_QUERY ); if ( xParentTunnel.is() ) { SvGlobalName aSfxIdent( SFX_GLOBAL_CLASSID ); pResult = reinterpret_cast< SfxObjectShell * >( xParentTunnel->getSomething( uno::Sequence< sal_Int8 >( aSfxIdent.GetByteSequence() ) ) ); } } } catch( uno::Exception& ) { // TODO: error handling } return pResult; } // this code is copied from sfx2/source/doc/objembed.cxx. It is a workaround to // get the reference device (e.g. printer) fromthe parent document OutputDevice * lcl_GetParentRefDevice( const uno::Reference< frame::XModel > & xModel ) { SfxObjectShell * pParent = lcl_GetParentObjectShell( xModel ); if ( pParent ) return pParent->GetDocumentRefDev(); return NULL; } } /* void lcl_initOutliner( SdrOutliner* pTargetOutliner, SdrOutliner* pSourceOutliner ) { //just an unsuccessful try to initialize the text edit outliner correctly //if( bInit ) { pTargetOutliner->EraseVirtualDevice(); pTargetOutliner->SetUpdateMode(FALSE); pTargetOutliner->SetEditTextObjectPool( pSourceOutliner->GetEditTextObjectPool() ); pTargetOutliner->SetDefTab( pSourceOutliner->GetDefTab() ); } pTargetOutliner->SetRefDevice( pSourceOutliner->GetRefDevice() ); pTargetOutliner->SetForbiddenCharsTable( pSourceOutliner->GetForbiddenCharsTable() ); pTargetOutliner->SetAsianCompressionMode( pSourceOutliner->GetAsianCompressionMode() ); pTargetOutliner->SetKernAsianPunctuation( pSourceOutliner->IsKernAsianPunctuation() ); pTargetOutliner->SetStyleSheetPool( pSourceOutliner->GetStyleSheetPool() ); pTargetOutliner->SetRefMapMode( pSourceOutliner->GetRefMapMode() ); pTargetOutliner->SetDefaultLanguage( pSourceOutliner->GetDefaultLanguage() ); pTargetOutliner->SetHyphenator( pSourceOutliner->GetHyphenator() ); USHORT nX, nY; pSourceOutliner->GetGlobalCharStretching( nX, nY ); pTargetOutliner->SetGlobalCharStretching( nX, nY ); *//* if ( !GetRefDevice() ) { MapMode aMapMode(eObjUnit, Point(0,0), aObjUnit, aObjUnit); pTargetOutliner->SetRefMapMode(aMapMode); } *//* } */ DrawViewWrapper::DrawViewWrapper( SdrModel* pSdrModel, OutputDevice* pOut) : E3dView(pSdrModel, pOut) , m_pMarkHandleProvider(NULL) , m_apOutliner( SdrMakeOutliner( OUTLINERMODE_TEXTOBJECT, pSdrModel ) ) { // #114898# SetBufferedOutputAllowed(true); SetBufferedOverlayAllowed(true); ReInit(); } void DrawViewWrapper::ReInit() { OutputDevice* pOutDev = this->GetFirstOutputDevice(); Size aOutputSize(100,100); if(pOutDev) aOutputSize = pOutDev->GetOutputSize(); this->ShowSdrPage(this->GetModel()->GetPage(0)); this->SetPageBorderVisible(false); this->SetBordVisible(false); this->SetGridVisible(false); this->SetGridFront(false); this->SetHlplVisible(false); this->SetNoDragXorPolys(true);//for interactive 3D resize-dragging: paint only a single rectangle (not a simulated 3D object) //this->SetResizeAtCenter(true);//for interactive resize-dragging: keep the object center fix //a correct work area is at least necessary for correct values in the position and size dialog Rectangle aRect(Point(0,0), aOutputSize); this->SetWorkArea(aRect); } DrawViewWrapper::~DrawViewWrapper() { aComeBackTimer.Stop();//@todo this should be done in destructor of base class UnmarkAllObj();//necessary to aavoid a paint call during the destructor hierarchy } SdrPageView* DrawViewWrapper::GetPageView() const { SdrPageView* pSdrPageView = this->GetSdrPageView(); return pSdrPageView; }; //virtual void DrawViewWrapper::SetMarkHandles() { if( m_pMarkHandleProvider && m_pMarkHandleProvider->getMarkHandles( aHdl ) ) return; else SdrView::SetMarkHandles(); } SdrObject* DrawViewWrapper::getHitObject( const Point& rPnt ) const { SdrObject* pRet = NULL; //ULONG nOptions =SDRSEARCH_DEEP|SDRSEARCH_PASS2BOUND|SDRSEARCH_PASS3NEAREST; ULONG nOptions = SDRSEARCH_DEEP | SDRSEARCH_TESTMARKABLE; SdrPageView* pSdrPageView = this->GetPageView(); this->SdrView::PickObj(rPnt, lcl_getHitTolerance( this->GetFirstOutputDevice() ), pRet, pSdrPageView, nOptions); if( pRet ) { //3d objects need a special treatment //because the simple PickObj method is not accurate in this case for performance reasons E3dObject* pE3d = dynamic_cast< E3dObject* >(pRet); if( pE3d ) { E3dScene* pScene = pE3d->GetScene(); if( pScene ) { ::std::vector< SdrObject* > aHitList; sal_uInt32 nHitCount = pScene->HitTest( rPnt, aHitList ); if( nHitCount ) pRet = aHitList[0]; } } } return pRet; } void DrawViewWrapper::MarkObject( SdrObject* pObj ) { bool bFrameDragSingles = true;//true == green == surrounding handles if(pObj) pObj->SetMarkProtect(false); if( m_pMarkHandleProvider ) bFrameDragSingles = m_pMarkHandleProvider->getFrameDragSingles(); this->SetFrameDragSingles(bFrameDragSingles);//decide wether each single object should get handles this->SdrView::MarkObj( pObj, this->GetPageView() ); this->showMarkHandles(); } void DrawViewWrapper::setMarkHandleProvider( MarkHandleProvider* pMarkHandleProvider ) { m_pMarkHandleProvider = pMarkHandleProvider; } void DrawViewWrapper::CompleteRedraw( OutputDevice* pOut, const Region& rReg ) { svtools::ColorConfig aColorConfig; Color aFillColor = Color( aColorConfig.GetColorValue( svtools::DOCCOLOR ).nColor ); this->SetApplicationBackgroundColor(aFillColor); this->E3dView::CompleteRedraw( pOut, rReg ); } SdrObject* DrawViewWrapper::getSelectedObject() const { SdrObject* pObj(NULL); const SdrMarkList& rMarkList = this->GetMarkedObjectList(); if(rMarkList.GetMarkCount() == 1) { SdrMark* pMark = rMarkList.GetMark(0); pObj = pMark->GetMarkedSdrObj(); } return pObj; } SdrObject* DrawViewWrapper::getTextEditObject() const { SdrObject* pObj = this->getSelectedObject(); SdrObject* pTextObj = NULL; if( pObj && pObj->HasTextEdit()) pTextObj = (SdrTextObj*)pObj; return pTextObj; } void DrawViewWrapper::attachParentReferenceDevice( const uno::Reference< frame::XModel > & xChartModel ) { OutputDevice * pParentRefDev( lcl_GetParentRefDevice( xChartModel )); SdrOutliner * pOutliner( getOutliner()); if( pParentRefDev && pOutliner ) { pOutliner->SetRefDevice( pParentRefDev ); } } SdrOutliner* DrawViewWrapper::getOutliner() const { // lcl_initOutliner( m_apOutliner.get(), &GetModel()->GetDrawOutliner() ); return m_apOutliner.get(); } SfxItemSet DrawViewWrapper::getPositionAndSizeItemSetFromMarkedObject() const { SfxItemSet aFullSet( GetModel()->GetItemPool(), SID_ATTR_TRANSFORM_POS_X,SID_ATTR_TRANSFORM_ANGLE, SID_ATTR_TRANSFORM_PROTECT_POS,SID_ATTR_TRANSFORM_AUTOHEIGHT, SDRATTR_ECKENRADIUS,SDRATTR_ECKENRADIUS, SID_ATTR_METRIC,SID_ATTR_METRIC, 0); SfxItemSet aGeoSet( E3dView::GetGeoAttrFromMarked() ); aFullSet.Put( aGeoSet ); aFullSet.Put( SfxUInt16Item(SID_ATTR_METRIC,ConfigurationAccess::getConfigurationAccess()->getFieldUnit()) ); return aFullSet; } SdrObject* DrawViewWrapper::getNamedSdrObject( const rtl::OUString& rName ) const { if(rName.getLength()==0) return 0; SdrPageView* pSdrPageView = this->GetPageView(); if( pSdrPageView ) { return DrawModelWrapper::getNamedSdrObject( rName, pSdrPageView->GetObjList() ); } return 0; } bool DrawViewWrapper::IsObjectHit( SdrObject* pObj, const Point& rPnt ) const { if(pObj) { Rectangle aRect(pObj->GetCurrentBoundRect()); return aRect.IsInside(rPnt); } return false; } void DrawViewWrapper::SFX_NOTIFY(SfxBroadcaster& rBC, const TypeId& rBCType, const SfxHint& rHint, const TypeId& rHintType) { //prevent wrong reselection of objects SdrModel* pSdrModel( this->GetModel() ); if( pSdrModel && pSdrModel->isLocked() ) return; E3dView::SFX_NOTIFY(rBC, rBCType, rHint, rHintType); } //static SdrObject* DrawViewWrapper::getSdrObject( const uno::Reference< drawing::XShape >& xShape ) { SdrObject* pRet = 0; uno::Reference< lang::XUnoTunnel > xUnoTunnel( xShape, uno::UNO_QUERY ); uno::Reference< lang::XTypeProvider > xTypeProvider( xShape, uno::UNO_QUERY ); if(xUnoTunnel.is()&&xTypeProvider.is()) { SvxShape* pSvxShape = reinterpret_cast<SvxShape*>(xUnoTunnel->getSomething( SvxShape::getUnoTunnelId() )); if(pSvxShape) pRet = pSvxShape->GetSdrObject(); } return pRet; } //............................................................................. } //namespace chart //............................................................................. <|endoftext|>
<commit_before>/** * Copyright (c) 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ #include "DelSuper.h" #include <algorithm> #include <map> #include <string> #include <vector> #include <unordered_set> #include <unordered_map> #include "walkers.h" #include "DexClass.h" #include "DexOpcode.h" #include "DexUtil.h" #include "ReachableClasses.h" namespace { static const DexCodeItemOpcode s_return_invoke_super_void_opcs[2] = { OPCODE_INVOKE_SUPER, OPCODE_RETURN_VOID }; static const DexCodeItemOpcode s_return_invoke_super_opcs[3] = { OPCODE_INVOKE_SUPER, OPCODE_MOVE_RESULT, OPCODE_RETURN }; static const DexCodeItemOpcode s_return_invoke_super_wide_opcs[3] = { OPCODE_INVOKE_SUPER, OPCODE_MOVE_RESULT_WIDE, OPCODE_RETURN_WIDE }; static const DexCodeItemOpcode s_return_invoke_super_obj_opcs[3] = { OPCODE_INVOKE_SUPER, OPCODE_MOVE_RESULT_OBJECT, OPCODE_RETURN_OBJECT }; class DelSuper { private: const std::vector<DexClass*>& m_scope; std::vector<DexMethod*> m_delmeths; int m_num_methods; int m_num_passed; int m_num_trivial; int m_num_relaxed_vis; int m_num_private; int m_num_culled_no_code; int m_num_culled_too_short; int m_num_culled_not_trivial; int m_num_culled_static; int m_num_culled_name_differs; int m_num_culled_proto_differs; int m_num_culled_return_move_result_differs; int m_num_culled_args_differs; int m_num_culled_super_is_non_public_sdk; int m_num_culled_super_not_def; /** * This method ensures that the method arguments pass directly through * to the super invocation, for methods where the prototypes are already, * known to match. * * matching: * * void method(int a1, int a2, int a3) { * super.method(a1, a2, a3); * } * * NOT matching: * * void method(int a1, int a2, int a3) { * super.method(a1, a1, a1); * } * * void method(int a1, int a2, int a3) { * super.method(a3, a2, a1); * } * * void method(int a1, int a2, int a3) { * super.method(a1, a2, 0); * } * * Cases where method prototypes don't even match (e.g. different * number of types of arguments) are filtered before hand so we * don't handle that case here. * */ bool do_invoke_meth_args_pass_through( const DexMethod* meth, const DexOpcode* opc) { assert(opc->opcode() == OPCODE_INVOKE_SUPER); assert(opc->has_arg_word_count() == true); uint16_t start_reg = meth->get_code()->get_registers_size() - meth->get_code()->get_ins_size(); uint16_t end_reg = meth->get_code()->get_registers_size(); // args to this method start at 'start_reg', so they should // be passed into invoke_super of opc {start_reg, ..., end_reg} uint16_t arg_word_count = opc->arg_word_count(); if (arg_word_count != end_reg - start_reg) { return false; } // N.B. don't need to check reg < end_reg in for loop // because of above length check for (uint16_t i = 0, reg = start_reg ; i < arg_word_count ; ++i, ++reg) { uint16_t opc_reg = opc->src(i); if (reg != opc_reg) { return false; } } return true; } bool are_opcs_equal( const std::vector<DexOpcode*> insns, const DexCodeItemOpcode* opcs, size_t opcs_len) { if (insns.size() != opcs_len) return false; for (size_t i = 0 ; i < opcs_len ; ++i) { if (insns[i]->opcode() != opcs[i]) return false; } return true; } /** * Trivial return invoke supers are: * * - Must have a body (bytecode) * - Opcodes must be match one pattern exactly (no more, no less): * - invoke-super, return-void (void) * - invoke-super, move-result, return (prim) * - invoke-super, move-result-wide, return-wide (wide prim) * - invoke-super, move-result-object, return-object (obj) * - Not static methods * - Method name must match name of super method * - Method proto must match name of super method * - Method vis must match vis of super method * - Method return src register must match move-result dest register * - Method args must all go into invoke without rearrangement */ bool is_trivial_return_invoke_super(const DexMethod* meth) { const DexCode* code = meth->get_code(); // Must have code if (!code) { m_num_culled_no_code++; return false; } // Must have at least two instructions const auto& insns = code->get_instructions(); if (insns.size() < 2) { m_num_culled_too_short++; return false; } // Must satisfy one of the four "trivial invoke super" patterns if (!(are_opcs_equal(insns, s_return_invoke_super_void_opcs, 2) || are_opcs_equal(insns, s_return_invoke_super_opcs, 3) || are_opcs_equal(insns, s_return_invoke_super_wide_opcs, 3) || are_opcs_equal(insns, s_return_invoke_super_obj_opcs, 3))) { m_num_culled_not_trivial++; return false; } // Must not be static if (meth->get_access() & ACC_STATIC) { m_num_culled_static++; return false; } // Must not be private if (meth->get_access() & ACC_PRIVATE) { m_num_private++; } // For non-void scenarios, capture move-result and return opcodes DexOpcode* move_res_opc = nullptr; DexOpcode* return_opc = nullptr; if (insns.size() == 3) { move_res_opc = insns[1]; return_opc = insns[2]; } m_num_trivial++; // Get invoked method const DexOpcode* opc = insns[0]; const DexOpcodeMethod* mopc = static_cast<const DexOpcodeMethod*>(opc); DexMethod* invoked_meth = mopc->get_method(); // Invoked method name must match if (meth->get_name() != invoked_meth->get_name()) { m_num_culled_name_differs++; return false; } // Invoked method proto must match if (meth->get_proto() != invoked_meth->get_proto()) { m_num_culled_proto_differs++; return false; } // Method return src register must match move-result dest register if (move_res_opc && return_opc && move_res_opc->dest() != return_opc->src(0)) { m_num_culled_return_move_result_differs++; return false; } // Method args must pass through directly if (!do_invoke_meth_args_pass_through(meth, insns[0])) { m_num_culled_args_differs++; return false; } // If the invoked method does not have access flags, we can't operate // on it at all. if (!invoked_meth->is_def()) { m_num_culled_super_not_def++; return false; } // If invoked method is not public, make it public if (!is_public(invoked_meth)) { if(!type_class_internal(invoked_meth->get_class())) { m_num_culled_super_is_non_public_sdk++; return false; } else { set_public(invoked_meth); m_num_relaxed_vis++; } } return true; } public: explicit DelSuper(const std::vector<DexClass*>& scope) : m_scope(scope), m_num_methods(0), m_num_passed(0), m_num_trivial(0), m_num_relaxed_vis(0), m_num_private(0), m_num_culled_no_code(0), m_num_culled_too_short(0), m_num_culled_not_trivial(0), m_num_culled_static(0), m_num_culled_name_differs(0), m_num_culled_proto_differs(0), m_num_culled_return_move_result_differs(0), m_num_culled_args_differs(0), m_num_culled_super_is_non_public_sdk(0), m_num_culled_super_not_def(0) { } void run(bool do_delete) { walk_methods(m_scope, [&](DexMethod* meth) { m_num_methods++; if (is_trivial_return_invoke_super(meth)) { TRACE(SUPER, 5, "Found trivial return invoke-super: %s\n", SHOW(meth)); m_delmeths.push_back(meth); m_num_passed++; } }); if (do_delete) { for (const auto meth : m_delmeths) { auto clazz = type_class(meth->get_class()); always_assert(meth->is_virtual()); clazz->get_vmethods().remove(meth); TRACE(SUPER, 5, "Deleted trivial return invoke-super: %s\n", SHOW(meth)); } } print_stats(do_delete); } void print_stats(bool do_delete) { TRACE(SUPER, 1, "Examined %d total methods\n", m_num_methods); TRACE(SUPER, 1, "Found %d candidate trivial methods\n", m_num_trivial); TRACE(SUPER, 5, "Culled %d due to super not defined\n", m_num_culled_super_not_def); TRACE(SUPER, 5, "Culled %d due to method is static\n", m_num_culled_static); TRACE(SUPER, 5, "Culled %d due to method name doesn't match super\n", m_num_culled_name_differs); TRACE(SUPER, 5, "Culled %d due to method proto doesn't match super\n", m_num_culled_proto_differs); TRACE(SUPER, 5, "Culled %d due to method doesn't return move result\n", m_num_culled_return_move_result_differs); TRACE(SUPER, 5, "Culled %d due to method args doesn't match super\n", m_num_culled_args_differs); TRACE(SUPER, 5, "Culled %d due to non-public super method in sdk\n", m_num_culled_super_is_non_public_sdk); TRACE(SUPER, 1, "Found %d trivial return invoke-super methods\n", m_num_passed); if (do_delete) { TRACE(SUPER, 1, "Deleted %d trivial return invoke-super methods\n", m_num_passed); TRACE(SUPER, 1, "Promoted %d methods to public visibility\n", m_num_relaxed_vis); } else { TRACE(SUPER, 1, "Preview-only; not performing any changes.\n"); TRACE(SUPER, 1, "Would delete %d trivial return invoke-super methods\n", m_num_passed); TRACE(SUPER, 1, "Would promote %d methods to public visibility\n", m_num_relaxed_vis); } } }; } void DelSuperPass::run_pass(DexClassesVector& dexen, PgoFiles& pgos) { const auto& scope = build_class_scope(dexen); DelSuper(scope).run(/* do_delete = */true); } <commit_msg>DelSuper and external references<commit_after>/** * Copyright (c) 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ #include "DelSuper.h" #include <algorithm> #include <map> #include <string> #include <vector> #include <unordered_set> #include <unordered_map> #include "walkers.h" #include "DexClass.h" #include "DexOpcode.h" #include "DexUtil.h" #include "ReachableClasses.h" namespace { static const DexCodeItemOpcode s_return_invoke_super_void_opcs[2] = { OPCODE_INVOKE_SUPER, OPCODE_RETURN_VOID }; static const DexCodeItemOpcode s_return_invoke_super_opcs[3] = { OPCODE_INVOKE_SUPER, OPCODE_MOVE_RESULT, OPCODE_RETURN }; static const DexCodeItemOpcode s_return_invoke_super_wide_opcs[3] = { OPCODE_INVOKE_SUPER, OPCODE_MOVE_RESULT_WIDE, OPCODE_RETURN_WIDE }; static const DexCodeItemOpcode s_return_invoke_super_obj_opcs[3] = { OPCODE_INVOKE_SUPER, OPCODE_MOVE_RESULT_OBJECT, OPCODE_RETURN_OBJECT }; class DelSuper { private: const std::vector<DexClass*>& m_scope; std::vector<DexMethod*> m_delmeths; int m_num_methods; int m_num_passed; int m_num_trivial; int m_num_relaxed_vis; int m_num_private; int m_num_culled_no_code; int m_num_culled_too_short; int m_num_culled_not_trivial; int m_num_culled_static; int m_num_culled_name_differs; int m_num_culled_proto_differs; int m_num_culled_return_move_result_differs; int m_num_culled_args_differs; int m_num_culled_super_is_non_public_sdk; int m_num_culled_super_not_def; /** * This method ensures that the method arguments pass directly through * to the super invocation, for methods where the prototypes are already, * known to match. * * matching: * * void method(int a1, int a2, int a3) { * super.method(a1, a2, a3); * } * * NOT matching: * * void method(int a1, int a2, int a3) { * super.method(a1, a1, a1); * } * * void method(int a1, int a2, int a3) { * super.method(a3, a2, a1); * } * * void method(int a1, int a2, int a3) { * super.method(a1, a2, 0); * } * * Cases where method prototypes don't even match (e.g. different * number of types of arguments) are filtered before hand so we * don't handle that case here. * */ bool do_invoke_meth_args_pass_through( const DexMethod* meth, const DexOpcode* opc) { assert(opc->opcode() == OPCODE_INVOKE_SUPER); assert(opc->has_arg_word_count() == true); uint16_t start_reg = meth->get_code()->get_registers_size() - meth->get_code()->get_ins_size(); uint16_t end_reg = meth->get_code()->get_registers_size(); // args to this method start at 'start_reg', so they should // be passed into invoke_super of opc {start_reg, ..., end_reg} uint16_t arg_word_count = opc->arg_word_count(); if (arg_word_count != end_reg - start_reg) { return false; } // N.B. don't need to check reg < end_reg in for loop // because of above length check for (uint16_t i = 0, reg = start_reg ; i < arg_word_count ; ++i, ++reg) { uint16_t opc_reg = opc->src(i); if (reg != opc_reg) { return false; } } return true; } bool are_opcs_equal( const std::vector<DexOpcode*> insns, const DexCodeItemOpcode* opcs, size_t opcs_len) { if (insns.size() != opcs_len) return false; for (size_t i = 0 ; i < opcs_len ; ++i) { if (insns[i]->opcode() != opcs[i]) return false; } return true; } /** * Trivial return invoke supers are: * * - Must have a body (bytecode) * - Opcodes must be match one pattern exactly (no more, no less): * - invoke-super, return-void (void) * - invoke-super, move-result, return (prim) * - invoke-super, move-result-wide, return-wide (wide prim) * - invoke-super, move-result-object, return-object (obj) * - Not static methods * - Method name must match name of super method * - Method proto must match name of super method * - Method vis must match vis of super method * - Method return src register must match move-result dest register * - Method args must all go into invoke without rearrangement */ bool is_trivial_return_invoke_super(const DexMethod* meth) { const DexCode* code = meth->get_code(); // Must have code if (!code) { m_num_culled_no_code++; return false; } // Must have at least two instructions const auto& insns = code->get_instructions(); if (insns.size() < 2) { m_num_culled_too_short++; return false; } // Must satisfy one of the four "trivial invoke super" patterns if (!(are_opcs_equal(insns, s_return_invoke_super_void_opcs, 2) || are_opcs_equal(insns, s_return_invoke_super_opcs, 3) || are_opcs_equal(insns, s_return_invoke_super_wide_opcs, 3) || are_opcs_equal(insns, s_return_invoke_super_obj_opcs, 3))) { m_num_culled_not_trivial++; return false; } // Must not be static if (meth->get_access() & ACC_STATIC) { m_num_culled_static++; return false; } // Must not be private if (meth->get_access() & ACC_PRIVATE) { m_num_private++; } // For non-void scenarios, capture move-result and return opcodes DexOpcode* move_res_opc = nullptr; DexOpcode* return_opc = nullptr; if (insns.size() == 3) { move_res_opc = insns[1]; return_opc = insns[2]; } m_num_trivial++; // Get invoked method const DexOpcode* opc = insns[0]; const DexOpcodeMethod* mopc = static_cast<const DexOpcodeMethod*>(opc); DexMethod* invoked_meth = mopc->get_method(); // Invoked method name must match if (meth->get_name() != invoked_meth->get_name()) { m_num_culled_name_differs++; return false; } // Invoked method proto must match if (meth->get_proto() != invoked_meth->get_proto()) { m_num_culled_proto_differs++; return false; } // Method return src register must match move-result dest register if (move_res_opc && return_opc && move_res_opc->dest() != return_opc->src(0)) { m_num_culled_return_move_result_differs++; return false; } // Method args must pass through directly if (!do_invoke_meth_args_pass_through(meth, insns[0])) { m_num_culled_args_differs++; return false; } // If the invoked method does not have access flags, we can't operate // on it at all. if (!invoked_meth->is_def()) { m_num_culled_super_not_def++; return false; } // If invoked method is not public, make it public if (!is_public(invoked_meth)) { if (!invoked_meth->is_concrete()) { m_num_culled_super_is_non_public_sdk++; return false; } set_public(invoked_meth); m_num_relaxed_vis++; } return true; } public: explicit DelSuper(const std::vector<DexClass*>& scope) : m_scope(scope), m_num_methods(0), m_num_passed(0), m_num_trivial(0), m_num_relaxed_vis(0), m_num_private(0), m_num_culled_no_code(0), m_num_culled_too_short(0), m_num_culled_not_trivial(0), m_num_culled_static(0), m_num_culled_name_differs(0), m_num_culled_proto_differs(0), m_num_culled_return_move_result_differs(0), m_num_culled_args_differs(0), m_num_culled_super_is_non_public_sdk(0), m_num_culled_super_not_def(0) { } void run(bool do_delete) { walk_methods(m_scope, [&](DexMethod* meth) { m_num_methods++; if (is_trivial_return_invoke_super(meth)) { TRACE(SUPER, 5, "Found trivial return invoke-super: %s\n", SHOW(meth)); m_delmeths.push_back(meth); m_num_passed++; } }); if (do_delete) { for (const auto meth : m_delmeths) { auto clazz = type_class(meth->get_class()); always_assert(meth->is_virtual()); clazz->get_vmethods().remove(meth); TRACE(SUPER, 5, "Deleted trivial return invoke-super: %s\n", SHOW(meth)); } } print_stats(do_delete); } void print_stats(bool do_delete) { TRACE(SUPER, 1, "Examined %d total methods\n", m_num_methods); TRACE(SUPER, 1, "Found %d candidate trivial methods\n", m_num_trivial); TRACE(SUPER, 5, "Culled %d due to super not defined\n", m_num_culled_super_not_def); TRACE(SUPER, 5, "Culled %d due to method is static\n", m_num_culled_static); TRACE(SUPER, 5, "Culled %d due to method name doesn't match super\n", m_num_culled_name_differs); TRACE(SUPER, 5, "Culled %d due to method proto doesn't match super\n", m_num_culled_proto_differs); TRACE(SUPER, 5, "Culled %d due to method doesn't return move result\n", m_num_culled_return_move_result_differs); TRACE(SUPER, 5, "Culled %d due to method args doesn't match super\n", m_num_culled_args_differs); TRACE(SUPER, 5, "Culled %d due to non-public super method in sdk\n", m_num_culled_super_is_non_public_sdk); TRACE(SUPER, 1, "Found %d trivial return invoke-super methods\n", m_num_passed); if (do_delete) { TRACE(SUPER, 1, "Deleted %d trivial return invoke-super methods\n", m_num_passed); TRACE(SUPER, 1, "Promoted %d methods to public visibility\n", m_num_relaxed_vis); } else { TRACE(SUPER, 1, "Preview-only; not performing any changes.\n"); TRACE(SUPER, 1, "Would delete %d trivial return invoke-super methods\n", m_num_passed); TRACE(SUPER, 1, "Would promote %d methods to public visibility\n", m_num_relaxed_vis); } } }; } void DelSuperPass::run_pass(DexClassesVector& dexen, PgoFiles& pgos) { const auto& scope = build_class_scope(dexen); DelSuper(scope).run(/* do_delete = */true); } <|endoftext|>
<commit_before>#ifndef ISOMON_MONEY_CALC_HPP #define ISOMON_MONEY_CALC_HPP #include "money.hpp" namespace isomon { template <class _Number> struct money_calc {}; typedef money_calc<double> money_double; template <> struct money_calc<double> { double minors; currency unit; money_calc() : minors(NAN) {} money_calc(double m, currency u) : minors(m * u.num_minors()), unit(u) {} money_calc(money m) : minors(m.total_minors()), unit(m.unit()) {} double value() const { return minors / unit.num_minors(); } #if __cplusplus >= 201103L explicit operator double const () { return this->value(); } #endif money_calc & operator += (double rhs) { this->minors += rhs * unit.num_minors(); return *this; } money_calc & operator += (money rhs) { if (this->unit == rhs.unit()) { this->minors += rhs.total_minors(); } else { minors = NAN; unit = ISO_XXX; } return *this; } money_calc & operator += (money_calc const& rhs) { if (this->unit == rhs.unit) { this->minors += rhs.minors; } else { minors = NAN; unit = ISO_XXX; } return *this; } money_calc operator + (double rhs) const { money_calc ret(*this); ret += rhs; return ret; } money_calc operator + (money rhs) { money_calc ret(*this); ret += rhs; return ret; } money_calc operator + (money_calc const& rhs) const { money_calc ret(*this); ret += rhs; return ret; } money_calc operator - () const { money_calc ret(*this); ret.minors = -ret.minors; return ret; } money_calc & operator -= (double rhs) { return *this += -rhs; } money_calc & operator -= (money rhs) { return *this += -rhs; } money_calc & operator -= (money_calc const& rhs) { return *this += -rhs; } money_calc operator - (double rhs) const { return *this + -rhs; } money_calc operator - (money rhs) const { return *this + -rhs; } money_calc operator - (money_calc const& rhs) const { return *this + -rhs; } money_calc & operator *= (double rhs) { this->minors *= rhs; return *this; } money_calc & operator /= (double rhs) { this->minors /= rhs; return *this; } money_calc operator * (double rhs) const { money_calc ret(*this); ret *= rhs; return ret; } money_calc operator / (double rhs) const { money_calc ret(*this); ret /= rhs; return ret; } bool operator > (money_calc const& mc) const { if (unit.is_no_currency()) return false; return minors > mc.minors && unit == mc.unit; } bool operator >= (money_calc const& mc) const { if (unit.is_no_currency()) return false; return minors >= mc.minors && unit == mc.unit; } bool operator < (money_calc const& mc) const { return mc > *this; } bool operator <= (money_calc const& mc) const { return mc >= *this; } bool operator > (money m) const { return *this > money_calc(m); } bool operator >= (money m) const { return *this >= money_calc(m); } bool operator < (money m) const { return *this < money_calc(m); } bool operator <= (money m) const { return *this <= money_calc(m); } }; inline bool operator > (money m, money_calc<double> mc) { return mc < m; } inline bool operator >= (money m, money_calc<double> mc) { return mc <= m; } inline bool operator < (money m, money_calc<double> mc) { return mc > m; } inline bool operator <= (money m, money_calc<double> mc) { return mc >= m; } inline bool isfinite(money_calc<double> const& mc) { return std::isfinite(mc.minors); } inline money_calc<double> operator + (money m, double x) { return money_calc<double>(m) + x; } inline money_calc<double> operator + (double x, money m) { return m + x; } inline money_calc<double> operator + (money m, money_calc<double> mc) { return mc + m; } inline money_calc<double> operator * (money m, double x) { return money_calc<double>(m) * x; } inline money_calc<double> operator * (double x, money_calc<double> mc) { return mc * x; } inline money_calc<double> operator * (double x, money m) { return m * x; } inline money_calc<double> operator / (money m, double x) { return money_calc<double>(m) / x; } template <class _Number> money floor(money_calc<_Number> const& mc) { return detail::money_cast(mc.minors, mc.unit, number_traits<_Number>::floor); } template <class _Number> money ceil(money_calc<_Number> const& mc) { return detail::money_cast(mc.minors, mc.unit, number_traits<_Number>::ceil); } template <class _Number> money trunc(money_calc<_Number> const& mc) { return detail::money_cast(mc.minors, mc.unit, number_traits<_Number>::trunc); } template <class _Number> money round(money_calc<_Number> const& mc) { typedef number_traits<_Number> nt; return detail::money_cast(mc.minors, mc.unit, nt::roundhalfout); } template <class _Number> money rounde(money_calc<_Number> const& mc) { typedef number_traits<_Number> nt; return detail::money_cast(mc.minors, mc.unit, nt::roundhalfeven); } } // namespace #endif <commit_msg>implement some more missing operator + and - cases<commit_after>#ifndef ISOMON_MONEY_CALC_HPP #define ISOMON_MONEY_CALC_HPP #include "money.hpp" namespace isomon { template <class _Number> struct money_calc {}; typedef money_calc<double> money_double; template <> struct money_calc<double> { double minors; currency unit; money_calc() : minors(NAN) {} money_calc(double m, currency u) : minors(m * u.num_minors()), unit(u) {} money_calc(money m) : minors(m.total_minors()), unit(m.unit()) {} double value() const { return minors / unit.num_minors(); } #if __cplusplus >= 201103L explicit operator double const () { return this->value(); } #endif money_calc & operator += (double rhs) { this->minors += rhs * unit.num_minors(); return *this; } money_calc & operator += (money rhs) { if (this->unit == rhs.unit()) { this->minors += rhs.total_minors(); } else { minors = NAN; unit = ISO_XXX; } return *this; } money_calc & operator += (money_calc const& rhs) { if (this->unit == rhs.unit) { this->minors += rhs.minors; } else { minors = NAN; unit = ISO_XXX; } return *this; } money_calc operator + (double rhs) const { money_calc ret(*this); ret += rhs; return ret; } money_calc operator + (money rhs) { money_calc ret(*this); ret += rhs; return ret; } money_calc operator + (money_calc const& rhs) const { money_calc ret(*this); ret += rhs; return ret; } money_calc operator - () const { money_calc ret(*this); ret.minors = -ret.minors; return ret; } money_calc & operator -= (double rhs) { return *this += -rhs; } money_calc & operator -= (money rhs) { return *this += -rhs; } money_calc & operator -= (money_calc const& rhs) { return *this += -rhs; } money_calc operator - (double rhs) const { return *this + -rhs; } money_calc operator - (money rhs) const { return *this + -rhs; } money_calc operator - (money_calc const& rhs) const { return *this + -rhs; } money_calc & operator *= (double rhs) { this->minors *= rhs; return *this; } money_calc & operator /= (double rhs) { this->minors /= rhs; return *this; } money_calc operator * (double rhs) const { money_calc ret(*this); ret *= rhs; return ret; } money_calc operator / (double rhs) const { money_calc ret(*this); ret /= rhs; return ret; } bool operator > (money_calc const& mc) const { if (unit.is_no_currency()) return false; return minors > mc.minors && unit == mc.unit; } bool operator >= (money_calc const& mc) const { if (unit.is_no_currency()) return false; return minors >= mc.minors && unit == mc.unit; } bool operator < (money_calc const& mc) const { return mc > *this; } bool operator <= (money_calc const& mc) const { return mc >= *this; } bool operator > (money m) const { return *this > money_calc(m); } bool operator >= (money m) const { return *this >= money_calc(m); } bool operator < (money m) const { return *this < money_calc(m); } bool operator <= (money m) const { return *this <= money_calc(m); } }; inline bool operator > (money m, money_calc<double> mc) { return mc < m; } inline bool operator >= (money m, money_calc<double> mc) { return mc <= m; } inline bool operator < (money m, money_calc<double> mc) { return mc > m; } inline bool operator <= (money m, money_calc<double> mc) { return mc >= m; } inline bool isfinite(money_calc<double> const& mc) { return std::isfinite(mc.minors); } inline money_calc<double> operator + (money m, double x) { return money_calc<double>(m) + x; } inline money_calc<double> operator + (double x, money m) { return m + x; } inline money_calc<double> operator + (double x, money_calc<double> mc) { return mc + x; } inline money_calc<double> operator + (money m, money_calc<double> mc) { return mc + m; } inline money_calc<double> operator - (money m, double x) { return m + (-x); } inline money_calc<double> operator - (double x, money m) { return x + (-m); } inline money_calc<double> operator - (double x, money_calc<double> mc) { return x + (-mc); } inline money_calc<double> operator - (money m, money_calc<double> mc) { return m + (-mc); } inline money_calc<double> operator * (money m, double x) { return money_calc<double>(m) * x; } inline money_calc<double> operator * (double x, money_calc<double> mc) { return mc * x; } inline money_calc<double> operator * (double x, money m) { return m * x; } inline money_calc<double> operator / (money m, double x) { return money_calc<double>(m) / x; } template <class _Number> money floor(money_calc<_Number> const& mc) { return detail::money_cast(mc.minors, mc.unit, number_traits<_Number>::floor); } template <class _Number> money ceil(money_calc<_Number> const& mc) { return detail::money_cast(mc.minors, mc.unit, number_traits<_Number>::ceil); } template <class _Number> money trunc(money_calc<_Number> const& mc) { return detail::money_cast(mc.minors, mc.unit, number_traits<_Number>::trunc); } template <class _Number> money round(money_calc<_Number> const& mc) { typedef number_traits<_Number> nt; return detail::money_cast(mc.minors, mc.unit, nt::roundhalfout); } template <class _Number> money rounde(money_calc<_Number> const& mc) { typedef number_traits<_Number> nt; return detail::money_cast(mc.minors, mc.unit, nt::roundhalfeven); } } // namespace #endif <|endoftext|>
<commit_before>/** * Copyright (c) 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed in accordance with the terms specified in * the LICENSE file found in the root directory of this source tree. */ // clang-format off // Keep it on top of all other includes to fix double include WinSock.h header file // which is windows specific boost build problem #include <osquery/remote/utility.h> // clang-format on #include <boost/algorithm/string.hpp> #include <osquery/carver/carver.h> #include <osquery/database.h> #include <osquery/distributed.h> #include <osquery/filesystem/fileops.h> #include <osquery/flags.h> #include <osquery/hashing/hashing.h> #include <osquery/logger.h> #include <osquery/remote/serializers/json.h> #include <osquery/system.h> #include <osquery/utils/base64.h> #include <osquery/utils/json/json.h> #include <osquery/utils/system/system.h> #include <osquery/utils/system/time.h> namespace fs = boost::filesystem; namespace osquery { DECLARE_string(tls_hostname); /// Session creation endpoint for forensic file carve CLI_FLAG(string, carver_start_endpoint, "", "TLS/HTTPS init endpoint for forensic carver"); /// Data aggregation endpoint for forensic file carve CLI_FLAG( string, carver_continue_endpoint, "", "TLS/HTTPS endpoint that receives carved content after session creation"); /// Size of blocks used for POSTing data back to remote endpoints CLI_FLAG(uint32, carver_block_size, 8192, "Size of blocks used for POSTing data back to remote endpoints"); CLI_FLAG(bool, disable_carver, true, "Disable the osquery file carver (default true)"); CLI_FLAG(bool, carver_disable_function, FLAGS_disable_carver, "Disable the osquery file carver function (default true)"); CLI_FLAG(bool, carver_compression, false, "Compress archives using zstd prior to upload (default false)"); DECLARE_uint64(read_max); /// Helper function to update values related to a carve void updateCarveValue(const std::string& guid, const std::string& key, const std::string& value) { std::string carve; auto s = getDatabaseValue(kCarveDbDomain, kCarverDBPrefix + guid, carve); if (!s.ok()) { VLOG(1) << "Failed to update status of carve in database " << guid; return; } JSON tree; s = tree.fromString(carve); if (!s.ok()) { VLOG(1) << "Failed to parse carve entries: " << s.what(); return; } tree.add(key, value); std::string out; s = tree.toString(out); if (!s.ok()) { VLOG(1) << "Failed to serialize carve entries: " << s.what(); } s = setDatabaseValue(kCarveDbDomain, kCarverDBPrefix + guid, out); if (!s.ok()) { VLOG(1) << "Failed to update status of carve in database " << guid; } } Carver::Carver(const std::set<std::string>& paths, const std::string& guid, const std::string& requestId) : InternalRunnable("Carver") { status_ = Status(0, "Ok"); for (const auto& p : paths) { carvePaths_.insert(fs::path(p)); } // Construct the uri we post our data back to: startUri_ = TLSRequestHelper::makeURI(FLAGS_carver_start_endpoint); contUri_ = TLSRequestHelper::makeURI(FLAGS_carver_continue_endpoint); // Generate a unique identifier for this carve carveGuid_ = guid; // Stash the work ID to be POSTed with the carve initial request requestId_ = requestId; // TODO: Adding in a manifest file of all carved files might be nice. carveDir_ = fs::temp_directory_path() / fs::path(kCarvePathPrefix + carveGuid_); auto ret = fs::create_directory(carveDir_); if (!ret) { status_ = Status(1, "Failed to create carve file store"); return; } // Store the path to our archive for later exfiltration archivePath_ = carveDir_ / fs::path(kCarveNamePrefix + carveGuid_ + ".tar"); compressPath_ = carveDir_ / fs::path(kCarveNamePrefix + carveGuid_ + ".tar.zst"); // Update the DB to reflect that the carve is pending. updateCarveValue(carveGuid_, "status", "PENDING"); }; Carver::~Carver() { fs::remove_all(carveDir_); } void Carver::start() { // If status_ is not Ok, the creation of our tmp FS failed if (!status_.ok()) { LOG(WARNING) << "Carver has not been properly constructed"; return; } for (const auto& p : carvePaths_) { // Ensure the file is a flat file on disk before carving PlatformFile pFile(p, PF_OPEN_EXISTING | PF_READ); if (!pFile.isValid() || isDirectory(p)) { VLOG(1) << "File does not exist on disk or is subdirectory: " << p; continue; } Status s = carve(p); if (!s.ok()) { VLOG(1) << "Failed to carve file " << p << " " << s.getMessage(); } } std::set<fs::path> carvedFiles; for (const auto& p : platformGlob((carveDir_ / "*").string())) { carvedFiles.insert(fs::path(p)); } auto s = archive(carvedFiles, archivePath_, FLAGS_carver_block_size); if (!s.ok()) { VLOG(1) << "Failed to create carve archive: " << s.getMessage(); updateCarveValue(carveGuid_, "status", "ARCHIVE FAILED"); return; } fs::path uploadPath; if (FLAGS_carver_compression) { uploadPath = compressPath_; s = compress(archivePath_, compressPath_); if (!s.ok()) { VLOG(1) << "Failed to compress carve archive: " << s.getMessage(); updateCarveValue(carveGuid_, "status", "COMPRESS FAILED"); return; } } else { uploadPath = archivePath_; } PlatformFile uploadFile(uploadPath, PF_OPEN_EXISTING | PF_READ); updateCarveValue(carveGuid_, "size", std::to_string(uploadFile.size())); std::string uploadHash = (uploadFile.size() > FLAGS_read_max) ? "-1" : hashFromFile(HashType::HASH_TYPE_SHA256, uploadPath.string()); if (uploadHash == "-1") { VLOG(1) << "Archive file size exceeds read max, skipping integrity computation"; } updateCarveValue(carveGuid_, "sha256", uploadHash); s = postCarve(uploadPath); if (!s.ok()) { VLOG(1) << "Failed to post carve: " << s.getMessage(); updateCarveValue(carveGuid_, "status", "DATA POST FAILED"); return; } }; Status Carver::carve(const boost::filesystem::path& path) { PlatformFile src(path, PF_OPEN_EXISTING | PF_READ); PlatformFile dst(carveDir_ / path.leaf(), PF_CREATE_NEW | PF_WRITE); if (!dst.isValid()) { return Status(1, "Destination tmp FS is not valid."); } auto blkCount = ceil(static_cast<double>(src.size()) / static_cast<double>(FLAGS_carver_block_size)); std::vector<char> inBuff(FLAGS_carver_block_size, 0); for (size_t i = 0; i < blkCount; i++) { inBuff.clear(); auto bytesRead = src.read(inBuff.data(), FLAGS_carver_block_size); if (bytesRead > 0) { auto bytesWritten = dst.write(inBuff.data(), bytesRead); if (bytesWritten < 0) { return Status(1, "Error writing bytes to tmp fs"); } } } return Status::success(); }; Status Carver::postCarve(const boost::filesystem::path& path) { Request<TLSTransport, JSONSerializer> startRequest(startUri_); startRequest.setOption("hostname", FLAGS_tls_hostname); // Perform the start request to get the session id PlatformFile pFile(path, PF_OPEN_EXISTING | PF_READ); auto blkCount = static_cast<size_t>(ceil(static_cast<double>(pFile.size()) / static_cast<double>(FLAGS_carver_block_size))); JSON startParams; startParams.add("block_count", blkCount); startParams.add("block_size", size_t(FLAGS_carver_block_size)); startParams.add("carve_size", pFile.size()); startParams.add("carve_id", carveGuid_); startParams.add("request_id", requestId_); startParams.add("node_key", getNodeKey("tls")); auto status = startRequest.call(startParams); if (!status.ok()) { return status; } // The call succeeded, store the session id for future posts JSON startRecv; status = startRequest.getResponse(startRecv); if (!status.ok()) { return status; } auto it = startRecv.doc().FindMember("session_id"); if (it == startRecv.doc().MemberEnd()) { return Status(1, "No session_id received from remote endpoint"); } if (!it->value.IsString()) { return Status(1, "Invalid session_id received from remote endpoint"); } std::string session_id = it->value.GetString(); if (session_id.empty()) { return Status(1, "Empty session_id received from remote endpoint"); } Request<TLSTransport, JSONSerializer> contRequest(contUri_); contRequest.setOption("hostname", FLAGS_tls_hostname); for (size_t i = 0; i < blkCount; i++) { std::vector<char> block(FLAGS_carver_block_size, 0); auto r = pFile.read(block.data(), FLAGS_carver_block_size); if (r != FLAGS_carver_block_size && r > 0) { // resize the buffer to size we read as last block is likely smaller block.resize(r); } JSON params; params.add("block_id", i); params.add("session_id", session_id); params.add("request_id", requestId_); params.add("data", base64::encode(std::string(block.begin(), block.end()))); // TODO: Error sending files. status = contRequest.call(params); if (!status.ok()) { VLOG(1) << "Post of carved block " << i << " failed: " << status.getMessage(); continue; } } updateCarveValue(carveGuid_, "status", "SUCCESS"); return Status::success(); }; Status carvePaths(const std::set<std::string>& paths) { Status s; auto guid = generateNewUUID(); JSON tree; tree.add("carve_guid", guid); tree.add("time", getUnixTime()); tree.add("status", "STARTING"); tree.add("sha256", ""); tree.add("size", -1); if (paths.size() > 1) { tree.add("path", boost::algorithm::join(paths, ",")); } else { tree.add("path", *(paths.begin())); } std::string out; s = tree.toString(out); if (!s.ok()) { VLOG(1) << "Failed to serialize carve paths: " << s.what(); return s; } s = setDatabaseValue(kCarveDbDomain, kCarverDBPrefix + guid, out); if (!s.ok()) { return s; } else { auto requestId = Distributed::getCurrentRequestId(); Dispatcher::addService(std::make_shared<Carver>(paths, guid, requestId)); } return s; } } // namespace osquery <commit_msg>Fix container-overflow in Carver::carve<commit_after>/** * Copyright (c) 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed in accordance with the terms specified in * the LICENSE file found in the root directory of this source tree. */ // clang-format off // Keep it on top of all other includes to fix double include WinSock.h header file // which is windows specific boost build problem #include <osquery/remote/utility.h> // clang-format on #include <boost/algorithm/string.hpp> #include <osquery/carver/carver.h> #include <osquery/database.h> #include <osquery/distributed.h> #include <osquery/filesystem/fileops.h> #include <osquery/flags.h> #include <osquery/hashing/hashing.h> #include <osquery/logger.h> #include <osquery/remote/serializers/json.h> #include <osquery/system.h> #include <osquery/utils/base64.h> #include <osquery/utils/json/json.h> #include <osquery/utils/system/system.h> #include <osquery/utils/system/time.h> namespace fs = boost::filesystem; namespace osquery { DECLARE_string(tls_hostname); /// Session creation endpoint for forensic file carve CLI_FLAG(string, carver_start_endpoint, "", "TLS/HTTPS init endpoint for forensic carver"); /// Data aggregation endpoint for forensic file carve CLI_FLAG( string, carver_continue_endpoint, "", "TLS/HTTPS endpoint that receives carved content after session creation"); /// Size of blocks used for POSTing data back to remote endpoints CLI_FLAG(uint32, carver_block_size, 8192, "Size of blocks used for POSTing data back to remote endpoints"); CLI_FLAG(bool, disable_carver, true, "Disable the osquery file carver (default true)"); CLI_FLAG(bool, carver_disable_function, FLAGS_disable_carver, "Disable the osquery file carver function (default true)"); CLI_FLAG(bool, carver_compression, false, "Compress archives using zstd prior to upload (default false)"); DECLARE_uint64(read_max); /// Helper function to update values related to a carve void updateCarveValue(const std::string& guid, const std::string& key, const std::string& value) { std::string carve; auto s = getDatabaseValue(kCarveDbDomain, kCarverDBPrefix + guid, carve); if (!s.ok()) { VLOG(1) << "Failed to update status of carve in database " << guid; return; } JSON tree; s = tree.fromString(carve); if (!s.ok()) { VLOG(1) << "Failed to parse carve entries: " << s.what(); return; } tree.add(key, value); std::string out; s = tree.toString(out); if (!s.ok()) { VLOG(1) << "Failed to serialize carve entries: " << s.what(); } s = setDatabaseValue(kCarveDbDomain, kCarverDBPrefix + guid, out); if (!s.ok()) { VLOG(1) << "Failed to update status of carve in database " << guid; } } Carver::Carver(const std::set<std::string>& paths, const std::string& guid, const std::string& requestId) : InternalRunnable("Carver") { status_ = Status(0, "Ok"); for (const auto& p : paths) { carvePaths_.insert(fs::path(p)); } // Construct the uri we post our data back to: startUri_ = TLSRequestHelper::makeURI(FLAGS_carver_start_endpoint); contUri_ = TLSRequestHelper::makeURI(FLAGS_carver_continue_endpoint); // Generate a unique identifier for this carve carveGuid_ = guid; // Stash the work ID to be POSTed with the carve initial request requestId_ = requestId; // TODO: Adding in a manifest file of all carved files might be nice. carveDir_ = fs::temp_directory_path() / fs::path(kCarvePathPrefix + carveGuid_); auto ret = fs::create_directory(carveDir_); if (!ret) { status_ = Status(1, "Failed to create carve file store"); return; } // Store the path to our archive for later exfiltration archivePath_ = carveDir_ / fs::path(kCarveNamePrefix + carveGuid_ + ".tar"); compressPath_ = carveDir_ / fs::path(kCarveNamePrefix + carveGuid_ + ".tar.zst"); // Update the DB to reflect that the carve is pending. updateCarveValue(carveGuid_, "status", "PENDING"); }; Carver::~Carver() { fs::remove_all(carveDir_); } void Carver::start() { // If status_ is not Ok, the creation of our tmp FS failed if (!status_.ok()) { LOG(WARNING) << "Carver has not been properly constructed"; return; } for (const auto& p : carvePaths_) { // Ensure the file is a flat file on disk before carving PlatformFile pFile(p, PF_OPEN_EXISTING | PF_READ); if (!pFile.isValid() || isDirectory(p)) { VLOG(1) << "File does not exist on disk or is subdirectory: " << p; continue; } Status s = carve(p); if (!s.ok()) { VLOG(1) << "Failed to carve file " << p << " " << s.getMessage(); } } std::set<fs::path> carvedFiles; for (const auto& p : platformGlob((carveDir_ / "*").string())) { carvedFiles.insert(fs::path(p)); } auto s = archive(carvedFiles, archivePath_, FLAGS_carver_block_size); if (!s.ok()) { VLOG(1) << "Failed to create carve archive: " << s.getMessage(); updateCarveValue(carveGuid_, "status", "ARCHIVE FAILED"); return; } fs::path uploadPath; if (FLAGS_carver_compression) { uploadPath = compressPath_; s = compress(archivePath_, compressPath_); if (!s.ok()) { VLOG(1) << "Failed to compress carve archive: " << s.getMessage(); updateCarveValue(carveGuid_, "status", "COMPRESS FAILED"); return; } } else { uploadPath = archivePath_; } PlatformFile uploadFile(uploadPath, PF_OPEN_EXISTING | PF_READ); updateCarveValue(carveGuid_, "size", std::to_string(uploadFile.size())); std::string uploadHash = (uploadFile.size() > FLAGS_read_max) ? "-1" : hashFromFile(HashType::HASH_TYPE_SHA256, uploadPath.string()); if (uploadHash == "-1") { VLOG(1) << "Archive file size exceeds read max, skipping integrity computation"; } updateCarveValue(carveGuid_, "sha256", uploadHash); s = postCarve(uploadPath); if (!s.ok()) { VLOG(1) << "Failed to post carve: " << s.getMessage(); updateCarveValue(carveGuid_, "status", "DATA POST FAILED"); return; } }; Status Carver::carve(const boost::filesystem::path& path) { PlatformFile src(path, PF_OPEN_EXISTING | PF_READ); PlatformFile dst(carveDir_ / path.leaf(), PF_CREATE_NEW | PF_WRITE); if (!dst.isValid()) { return Status(1, "Destination tmp FS is not valid."); } auto blkCount = ceil(static_cast<double>(src.size()) / static_cast<double>(FLAGS_carver_block_size)); std::vector<char> inBuff(FLAGS_carver_block_size, 0); for (size_t i = 0; i < blkCount; i++) { auto bytesRead = src.read(inBuff.data(), FLAGS_carver_block_size); if (bytesRead > 0) { auto bytesWritten = dst.write(inBuff.data(), bytesRead); if (bytesWritten < 0) { return Status(1, "Error writing bytes to tmp fs"); } } } return Status::success(); }; Status Carver::postCarve(const boost::filesystem::path& path) { Request<TLSTransport, JSONSerializer> startRequest(startUri_); startRequest.setOption("hostname", FLAGS_tls_hostname); // Perform the start request to get the session id PlatformFile pFile(path, PF_OPEN_EXISTING | PF_READ); auto blkCount = static_cast<size_t>(ceil(static_cast<double>(pFile.size()) / static_cast<double>(FLAGS_carver_block_size))); JSON startParams; startParams.add("block_count", blkCount); startParams.add("block_size", size_t(FLAGS_carver_block_size)); startParams.add("carve_size", pFile.size()); startParams.add("carve_id", carveGuid_); startParams.add("request_id", requestId_); startParams.add("node_key", getNodeKey("tls")); auto status = startRequest.call(startParams); if (!status.ok()) { return status; } // The call succeeded, store the session id for future posts JSON startRecv; status = startRequest.getResponse(startRecv); if (!status.ok()) { return status; } auto it = startRecv.doc().FindMember("session_id"); if (it == startRecv.doc().MemberEnd()) { return Status(1, "No session_id received from remote endpoint"); } if (!it->value.IsString()) { return Status(1, "Invalid session_id received from remote endpoint"); } std::string session_id = it->value.GetString(); if (session_id.empty()) { return Status(1, "Empty session_id received from remote endpoint"); } Request<TLSTransport, JSONSerializer> contRequest(contUri_); contRequest.setOption("hostname", FLAGS_tls_hostname); for (size_t i = 0; i < blkCount; i++) { std::vector<char> block(FLAGS_carver_block_size, 0); auto r = pFile.read(block.data(), FLAGS_carver_block_size); if (r != FLAGS_carver_block_size && r > 0) { // resize the buffer to size we read as last block is likely smaller block.resize(r); } JSON params; params.add("block_id", i); params.add("session_id", session_id); params.add("request_id", requestId_); params.add("data", base64::encode(std::string(block.begin(), block.end()))); // TODO: Error sending files. status = contRequest.call(params); if (!status.ok()) { VLOG(1) << "Post of carved block " << i << " failed: " << status.getMessage(); continue; } } updateCarveValue(carveGuid_, "status", "SUCCESS"); return Status::success(); }; Status carvePaths(const std::set<std::string>& paths) { Status s; auto guid = generateNewUUID(); JSON tree; tree.add("carve_guid", guid); tree.add("time", getUnixTime()); tree.add("status", "STARTING"); tree.add("sha256", ""); tree.add("size", -1); if (paths.size() > 1) { tree.add("path", boost::algorithm::join(paths, ",")); } else { tree.add("path", *(paths.begin())); } std::string out; s = tree.toString(out); if (!s.ok()) { VLOG(1) << "Failed to serialize carve paths: " << s.what(); return s; } s = setDatabaseValue(kCarveDbDomain, kCarverDBPrefix + guid, out); if (!s.ok()) { return s; } else { auto requestId = Distributed::getCurrentRequestId(); Dispatcher::addService(std::make_shared<Carver>(paths, guid, requestId)); } return s; } } // namespace osquery <|endoftext|>
<commit_before>// Copyright (C) 2016 Elviss Strazdins // This file is part of the Ouzel engine. #include "Component.h" #include "utils/Utils.h" #include "math/MathUtils.h" namespace ouzel { namespace scene { Component::~Component() { } void Component::draw(const Matrix4&, const Matrix4&, const graphics::Color&, const graphics::RenderTargetPtr&) { } void Component::drawWireframe(const Matrix4& projectionMatrix, const Matrix4& transformMatrix, const graphics::Color& drawColor, const graphics::RenderTargetPtr& renderTarget) { } bool Component::pointOn(const Vector2& position) const { return boundingBox.containsPoint(position); } bool Component::shapeOverlaps(const std::vector<Vector2>& edges) const { uint8_t inCorners = 0; for (const Vector2& corner : edges) { if (corner.x >= boundingBox.min.x && corner.x <= boundingBox.max.x && corner.y >= boundingBox.min.y && corner.y <= boundingBox.max.y) { return true; } if (corner.x < boundingBox.min.x && corner.y < boundingBox.min.y) inCorners |= 0x01; if (corner.x > boundingBox.max.x && corner.y < boundingBox.min.y) inCorners |= 0x02; if (corner.x > boundingBox.max.x && corner.y > boundingBox.max.y) inCorners |= 0x04; if (corner.x < boundingBox.min.x && corner.y > boundingBox.max.y) inCorners |= 0x08; } // bounding box is bigger than rectangle if (inCorners == 0x0F) { return true; } Vector2 boundingBoxCorners[4] = { Vector2(boundingBox.min), Vector2(boundingBox.max.x, boundingBox.min.y), Vector2(boundingBox.max), Vector2(boundingBox.min.x, boundingBox.max.y) }; for (uint32_t current = 0; current < edges.size(); ++current) { uint32_t next = (current == (edges.size() -1)) ? 0 : current + 1; if (linesIntersect(Vector2(edges[current].x, edges[current].y), Vector2(edges[next].x, edges[next].y), boundingBoxCorners[0], boundingBoxCorners[1]) || // left linesIntersect(Vector2(edges[current].x, edges[current].y), Vector2(edges[next].x, edges[next].y), boundingBoxCorners[1], boundingBoxCorners[2]) || // top linesIntersect(Vector2(edges[current].x, edges[current].y), Vector2(edges[next].x, edges[next].y), boundingBoxCorners[2], boundingBoxCorners[3]) || // right linesIntersect(Vector2(edges[current].x, edges[current].y), Vector2(edges[next].x, edges[next].y), boundingBoxCorners[3], boundingBoxCorners[0])) // bottom { return true; } } return false; } } // namespace scene } // namespace ouzel <commit_msg>Remove unused attributes<commit_after>// Copyright (C) 2016 Elviss Strazdins // This file is part of the Ouzel engine. #include "Component.h" #include "utils/Utils.h" #include "math/MathUtils.h" namespace ouzel { namespace scene { Component::~Component() { } void Component::draw(const Matrix4&, const Matrix4&, const graphics::Color&, const graphics::RenderTargetPtr&) { } void Component::drawWireframe(const Matrix4&, const Matrix4&, const graphics::Color&, const graphics::RenderTargetPtr&) { } bool Component::pointOn(const Vector2& position) const { return boundingBox.containsPoint(position); } bool Component::shapeOverlaps(const std::vector<Vector2>& edges) const { uint8_t inCorners = 0; for (const Vector2& corner : edges) { if (corner.x >= boundingBox.min.x && corner.x <= boundingBox.max.x && corner.y >= boundingBox.min.y && corner.y <= boundingBox.max.y) { return true; } if (corner.x < boundingBox.min.x && corner.y < boundingBox.min.y) inCorners |= 0x01; if (corner.x > boundingBox.max.x && corner.y < boundingBox.min.y) inCorners |= 0x02; if (corner.x > boundingBox.max.x && corner.y > boundingBox.max.y) inCorners |= 0x04; if (corner.x < boundingBox.min.x && corner.y > boundingBox.max.y) inCorners |= 0x08; } // bounding box is bigger than rectangle if (inCorners == 0x0F) { return true; } Vector2 boundingBoxCorners[4] = { Vector2(boundingBox.min), Vector2(boundingBox.max.x, boundingBox.min.y), Vector2(boundingBox.max), Vector2(boundingBox.min.x, boundingBox.max.y) }; for (uint32_t current = 0; current < edges.size(); ++current) { uint32_t next = (current == (edges.size() -1)) ? 0 : current + 1; if (linesIntersect(Vector2(edges[current].x, edges[current].y), Vector2(edges[next].x, edges[next].y), boundingBoxCorners[0], boundingBoxCorners[1]) || // left linesIntersect(Vector2(edges[current].x, edges[current].y), Vector2(edges[next].x, edges[next].y), boundingBoxCorners[1], boundingBoxCorners[2]) || // top linesIntersect(Vector2(edges[current].x, edges[current].y), Vector2(edges[next].x, edges[next].y), boundingBoxCorners[2], boundingBoxCorners[3]) || // right linesIntersect(Vector2(edges[current].x, edges[current].y), Vector2(edges[next].x, edges[next].y), boundingBoxCorners[3], boundingBoxCorners[0])) // bottom { return true; } } return false; } } // namespace scene } // namespace ouzel <|endoftext|>
<commit_before>#pragma once /* MIT License Copyright (c) 2017 Blockchain-VCS Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "platform.hpp" // Platform Specific Stuff NOTE: Must Always be the first include in a file #define MAX_BLOCK_SIZE (2 << 20 - 1) // 1 MEBIBYTE #define BLOCK_HEADER_SIZE = 4 const unsigned char BLOCK_HEADER[4] = {'B', 'L', 'K', 0}; const unsigned char TRANSACTION_INPUT_HEADER[4] = {'I', 'N', 0, 0}; const unsigned char TRANSACTION_HEADER[4] = {'T', 'R', 'A', 0}; const char chars[] = "0123456789" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz";<commit_msg>Add Transaction Output Header<commit_after>#pragma once /* MIT License Copyright (c) 2017 Blockchain-VCS Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "platform.hpp" // Platform Specific Stuff NOTE: Must Always be the first include in a file #define MAX_BLOCK_SIZE (2 << 20 - 1) // 1 MEBIBYTE #define BLOCK_HEADER_SIZE = 4 const unsigned char BLOCK_HEADER[4] = {'B', 'L', 'K', 0}; const unsigned char TRANSACTION_OUTPUT_HEADER[4] = {'O', 'U', 'T', 0}; const unsigned char TRANSACTION_INPUT_HEADER[4] = {'I', 'N', 0, 0}; const unsigned char TRANSACTION_HEADER[4] = {'T', 'R', 'A', 0}; const char chars[] = "0123456789" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz";<|endoftext|>
<commit_before>/* An Environment is the toplevel class for Rubinius. It manages multiple * VMs, as well as imports C data from the process into Rubyland. */ #include "prelude.hpp" #include "environment.hpp" #include "config.hpp" // HACK rename to config_parser.hpp #include "compiled_file.hpp" #include "probes.hpp" #include "builtin/array.hpp" #include "builtin/class.hpp" #include "builtin/string.hpp" #include "builtin/symbol.hpp" #include "builtin/module.hpp" #include "builtin/task.hpp" #include "builtin/exception.hpp" #include <iostream> #include <fstream> #include <string> namespace rubinius { Environment::Environment() { state = new VM(); state->probe = new TaskProbe; } Environment::~Environment() { delete state; } void Environment::load_argv(int argc, char** argv) { state->set_const("ARG0", String::create(state, argv[0])); Array* ary = Array::create(state, argc - 1); for(int i = 0; i < argc - 1; i++) { ary->set(state, i, String::create(state, argv[i + 1])); } state->set_const("ARGV", ary); } void Environment::load_directory(std::string dir) { std::string path = dir + "/.load_order.txt"; std::ifstream stream(path.c_str()); if(!stream) { throw std::runtime_error("Unable to load directory, .load_order.txt is missing"); } while(!stream.eof()) { std::string line; stream >> line; stream.get(); // eat newline // skip empty lines if(line.size() == 0) continue; std::cout << "Loading: " << line << std::endl; run_file(dir + "/" + line); } } void Environment::load_platform_conf(std::string dir) { std::string path = dir + "/platform.conf"; std::ifstream stream(path.c_str()); if(!stream) { std::string error = "Unable to load " + path + ", it is missing"; throw std::runtime_error(error); } state->user_config->import_stream(stream); } void Environment::run_file(std::string file) { std::ifstream stream(file.c_str()); if(!stream) throw std::runtime_error("Unable to open file to run"); CompiledFile* cf = CompiledFile::load(stream); if(cf->magic != "!RBIX") throw std::runtime_error("Invalid file"); // TODO check version number cf->execute(state); if(!G(current_task)->exception->nil_p()) { // Reset the context so we can show the backtrace // HACK need to use write barrier aware stuff? Exception* exc = G(current_task)->exception; G(current_task)->active = exc->context; String* message = String::create(state, "exception detected at toplevel: "); if(!exc->message->nil_p()) { message->append(state, exc->message); } message->append(state, " ("); message->append(state, exc->klass->name->to_str(state)); message->append(state, ")"); Assertion::raise(message->byte_address()); } } /* * HACK hook this up to a config file */ void Environment::set_rubinius_constants() { Module* rubinius = GO(rubinius).get(); String* ruby_version = String::create(state, "1.8.6"); rubinius->set_const(state, "RUBY_VERSION", ruby_version); String* ruby_patchlevel = String::create(state, "111"); rubinius->set_const(state, "RUBY_PATCHLEVEL", ruby_patchlevel); String* ruby_engine = String::create(state, "rbx"); rubinius->set_const(state, "RUBY_ENGINE", ruby_engine); String* rbx_version = String::create(state, "0.9.0"); rubinius->set_const(state, "RBX_VERSION", rbx_version); } } <commit_msg>Hack in RUBY_PLATFORM<commit_after>/* An Environment is the toplevel class for Rubinius. It manages multiple * VMs, as well as imports C data from the process into Rubyland. */ #include "prelude.hpp" #include "environment.hpp" #include "config.hpp" // HACK rename to config_parser.hpp #include "compiled_file.hpp" #include "probes.hpp" #include "builtin/array.hpp" #include "builtin/class.hpp" #include "builtin/string.hpp" #include "builtin/symbol.hpp" #include "builtin/module.hpp" #include "builtin/task.hpp" #include "builtin/exception.hpp" #include <iostream> #include <fstream> #include <string> namespace rubinius { Environment::Environment() { state = new VM(); state->probe = new TaskProbe; } Environment::~Environment() { delete state; } void Environment::load_argv(int argc, char** argv) { state->set_const("ARG0", String::create(state, argv[0])); Array* ary = Array::create(state, argc - 1); for(int i = 0; i < argc - 1; i++) { ary->set(state, i, String::create(state, argv[i + 1])); } state->set_const("ARGV", ary); } void Environment::load_directory(std::string dir) { std::string path = dir + "/.load_order.txt"; std::ifstream stream(path.c_str()); if(!stream) { throw std::runtime_error("Unable to load directory, .load_order.txt is missing"); } while(!stream.eof()) { std::string line; stream >> line; stream.get(); // eat newline // skip empty lines if(line.size() == 0) continue; std::cout << "Loading: " << line << std::endl; run_file(dir + "/" + line); } } void Environment::load_platform_conf(std::string dir) { std::string path = dir + "/platform.conf"; std::ifstream stream(path.c_str()); if(!stream) { std::string error = "Unable to load " + path + ", it is missing"; throw std::runtime_error(error); } state->user_config->import_stream(stream); } void Environment::run_file(std::string file) { std::ifstream stream(file.c_str()); if(!stream) throw std::runtime_error("Unable to open file to run"); CompiledFile* cf = CompiledFile::load(stream); if(cf->magic != "!RBIX") throw std::runtime_error("Invalid file"); // TODO check version number cf->execute(state); if(!G(current_task)->exception->nil_p()) { // Reset the context so we can show the backtrace // HACK need to use write barrier aware stuff? Exception* exc = G(current_task)->exception; G(current_task)->active = exc->context; String* message = String::create(state, "exception detected at toplevel: "); if(!exc->message->nil_p()) { message->append(state, exc->message); } message->append(state, " ("); message->append(state, exc->klass->name->to_str(state)); message->append(state, ")"); Assertion::raise(message->byte_address()); } } /* * HACK hook this up to a config file */ void Environment::set_rubinius_constants() { Module* rubinius = GO(rubinius).get(); String* ruby_version = String::create(state, "1.8.6"); rubinius->set_const(state, "RUBY_VERSION", ruby_version); String* ruby_patchlevel = String::create(state, "111"); rubinius->set_const(state, "RUBY_PATCHLEVEL", ruby_patchlevel); String* ruby_engine = String::create(state, "rbx"); rubinius->set_const(state, "RUBY_ENGINE", ruby_engine); String* rbx_version = String::create(state, "0.9.0"); rubinius->set_const(state, "RBX_VERSION", rbx_version); // HACK no reason to set this in C++ String* ruby_platform = String::create(state, ""); GO(object).get()->set_const(state, "RUBY_PLATFORM", ruby_platform); } } <|endoftext|>
<commit_before>#ifdef ENABLE_LLVM #include "llvm/passes.hpp" #include <llvm/Attributes.h> #include <llvm/BasicBlock.h> #include <llvm/Function.h> #include <llvm/Instructions.h> #include <llvm/Transforms/Utils/Cloning.h> #include <llvm/Support/CallSite.h> #include <llvm/ADT/APInt.h> #include <llvm/Constants.h> #include <llvm/Module.h> #include <iostream> namespace { using namespace llvm; namespace Attribute = llvm::Attribute; using llvm::BasicBlock; using llvm::CallInst; using llvm::Function; using llvm::FunctionPass; using llvm::InvokeInst; using llvm::dyn_cast; using llvm::isa; class OverflowConstantFolder : public FunctionPass { Function* sadd_; public: static char ID; OverflowConstantFolder() : FunctionPass(&ID) , sadd_(0) {} bool try_to_fold_addition(CallInst* call) { CallSite cs(call); Value* lhs = cs.getArgument(0); Value* rhs = cs.getArgument(1); bool changed = false; if(ConstantInt* lc = dyn_cast<ConstantInt>(lhs)) { if(ConstantInt* rc = dyn_cast<ConstantInt>(rhs)) { APInt zero(31, 0, true); const APInt& lval = lc->getValue(); const APInt& rval = rc->getValue(); APInt res = lval + rval; ConstantInt* overflow = ConstantInt::getFalse(); if(lval.sgt(zero) && res.slt(rval)) { overflow = ConstantInt::getTrue(); } else if(rval.sgt(zero) && res.slt(lval)) { overflow = ConstantInt::getTrue(); } // Now, update the extracts for(Value::use_iterator i = call->use_begin(); i != call->use_end(); i++) { if(ExtractValueInst* extract = dyn_cast<ExtractValueInst>(*i)) { Value* result = 0; ExtractValueInst::idx_iterator idx = extract->idx_begin(); if(*idx == 0) { result = ConstantInt::get(res); } else if(*idx == 1) { result = overflow; } else { std::cout << "unknown index on sadd.overflow extract\n"; } if(result) { extract->replaceAllUsesWith(result); result->takeName(extract); extract->eraseFromParent(); } } } changed = true; } } return changed; } virtual bool doInitialization(Module& m) { std::vector<const Type*> types; types.push_back(IntegerType::get(31)); types.push_back(IntegerType::get(31)); std::vector<const Type*> struct_types; struct_types.push_back(IntegerType::get(31)); struct_types.push_back(Type::Int1Ty); StructType* st = StructType::get(struct_types); FunctionType* ft = FunctionType::get(st, types, false); sadd_ = cast<Function>( m.getOrInsertFunction("llvm.sadd.with.overflow.i31", ft)); return true; } virtual bool runOnFunction(Function& f) { bool changed = false; std::vector<CallInst*> to_remove; for(Function::iterator bb = f.begin(), e = f.end(); bb != e; bb++) { for(BasicBlock::iterator inst = bb->begin(); inst != bb->end(); inst++) { CallInst *call = dyn_cast<CallInst>(inst); if(call == NULL) continue; // This may miss inlining indirect calls that become // direct after inlining something else. Function *called_function = call->getCalledFunction(); if(called_function == sadd_) { if(try_to_fold_addition(call)) { if(call->use_empty()) { to_remove.push_back(call); changed = true; } } } } } for(std::vector<CallInst*>::iterator i = to_remove.begin(); i != to_remove.end(); i++) { (*i)->eraseFromParent(); } return changed; } }; // The address of this variable identifies the pass. See // http://llvm.org/docs/WritingAnLLVMPass.html#basiccode. char OverflowConstantFolder::ID = 0; } // anonymous namespace namespace rubinius { llvm::FunctionPass* create_overflow_folding_pass() { return new OverflowConstantFolder(); } } #endif <commit_msg>Use Function::getIntrinsicID() to detect sadd.overflow<commit_after>#ifdef ENABLE_LLVM #include "llvm/passes.hpp" #include <llvm/Attributes.h> #include <llvm/BasicBlock.h> #include <llvm/Function.h> #include <llvm/Instructions.h> #include <llvm/Transforms/Utils/Cloning.h> #include <llvm/Support/CallSite.h> #include <llvm/ADT/APInt.h> #include <llvm/Constants.h> #include <llvm/Module.h> #include <llvm/Intrinsics.h> #include <iostream> namespace { using namespace llvm; class OverflowConstantFolder : public FunctionPass { public: static char ID; OverflowConstantFolder() : FunctionPass(&ID) {} bool try_to_fold_addition(CallInst* call) { CallSite cs(call); Value* lhs = cs.getArgument(0); Value* rhs = cs.getArgument(1); bool changed = false; if(ConstantInt* lc = dyn_cast<ConstantInt>(lhs)) { if(ConstantInt* rc = dyn_cast<ConstantInt>(rhs)) { const APInt& lval = lc->getValue(); const APInt& rval = rc->getValue(); APInt zero(lval.getBitWidth(), 0, true); APInt res = lval + rval; ConstantInt* overflow = ConstantInt::getFalse(); if(lval.sgt(zero) && res.slt(rval)) { overflow = ConstantInt::getTrue(); } else if(rval.sgt(zero) && res.slt(lval)) { overflow = ConstantInt::getTrue(); } // Now, update the extracts for(Value::use_iterator i = call->use_begin(); i != call->use_end(); i++) { if(ExtractValueInst* extract = dyn_cast<ExtractValueInst>(*i)) { Value* result = 0; ExtractValueInst::idx_iterator idx = extract->idx_begin(); if(*idx == 0) { result = ConstantInt::get(res); } else if(*idx == 1) { result = overflow; } else { std::cout << "unknown index on sadd.overflow extract\n"; } if(result) { extract->replaceAllUsesWith(result); result->takeName(extract); extract->eraseFromParent(); } } } changed = true; } } return changed; } virtual bool runOnFunction(Function& f) { bool changed = false; std::vector<CallInst*> to_remove; for(Function::iterator bb = f.begin(), e = f.end(); bb != e; bb++) { for(BasicBlock::iterator inst = bb->begin(); inst != bb->end(); inst++) { CallInst *call = dyn_cast<CallInst>(inst); if(call == NULL) continue; // This may miss inlining indirect calls that become // direct after inlining something else. Function *called_function = call->getCalledFunction(); if(called_function->getIntrinsicID() == Intrinsic::sadd_with_overflow) { if(try_to_fold_addition(call)) { if(call->use_empty()) { to_remove.push_back(call); changed = true; } } } } } for(std::vector<CallInst*>::iterator i = to_remove.begin(); i != to_remove.end(); i++) { (*i)->eraseFromParent(); } return changed; } }; // The address of this variable identifies the pass. See // http://llvm.org/docs/WritingAnLLVMPass.html#basiccode. char OverflowConstantFolder::ID = 0; } // anonymous namespace namespace rubinius { llvm::FunctionPass* create_overflow_folding_pass() { return new OverflowConstantFolder(); } } #endif <|endoftext|>
<commit_before>/** * @file backtrace.cpp * @author Grzegorz Krajewski * * Implementation of the Backtrace class. * * This file is part of mlpack 2.0.1. * * mlpack is free software; you may redstribute it and/or modify it under the * terms of the 3-clause BSD license. You should have received a copy of the * 3-clause BSD license along with mlpack. If not, see * http://www.opensource.org/licenses/BSD-3-Clause for more information. */ #include <sstream> #ifdef HAS_BFD_DL #include <execinfo.h> #include <signal.h> #include <unistd.h> #include <cxxabi.h> #include <bfd.h> #include <dlfcn.h> #endif #include "prefixedoutstream.hpp" #include "backtrace.hpp" #include "log.hpp" // Easier to read Backtrace::DecodeAddress(). #ifdef HAS_BFD_DL #define TRACE_CONDITION_1 (!dladdr(trace[i], &addressHandler)) #define FIND_LINE (bfd_find_nearest_line(abfd, text, syms, offset, &frame.file, &frame.function, &frame.line) && frame.file) #endif using namespace mlpack; // Initialize Backtrace static inctances. Backtrace::Frames Backtrace::frame; std::vector<Backtrace::Frames> Backtrace::stack; // Binary File Descriptor objects. bfd* abfd = 0; // Descriptor datastructure. asymbol **syms = 0; // Symbols datastructure. asection *text = 0; // Strings datastructure. Backtrace::Backtrace(int maxDepth) { frame.address = NULL; frame.function = "0"; frame.file = "0"; frame.line = 0; stack.clear(); #ifdef HAS_BFD_DL GetAddress(maxDepth); #endif } #ifdef HAS_BFD_DL void Backtrace::GetAddress(int maxDepth) { void* trace[maxDepth]; int stackDepth = backtrace(trace, maxDepth); // Skip first stack frame (points to Backtrace::Backtrace). for (int i = 1; i < stackDepth; i++) { Dl_info addressHandler; //No backtrace will be printed if no compile flags: -g -rdynamic if(TRACE_CONDITION_1) { return ; } frame.address = addressHandler.dli_saddr; DecodeAddress((long)frame.address); } } void Backtrace::DecodeAddress(long addr) { // Check to see if there is anything to descript. If it doesn't, we'll // dump running program. if (!abfd) { char ename[1024]; int l = readlink("/proc/self/exe",ename,sizeof(ename)); if (l == -1) { perror("Failed to open executable!\n"); return; } ename[l] = 0; bfd_init(); abfd = bfd_openr(ename, 0); if (!abfd) { perror("bfd_openr failed: "); return; } bfd_check_format(abfd,bfd_object); unsigned storage_needed = bfd_get_symtab_upper_bound(abfd); syms = (asymbol **) malloc(storage_needed); text = bfd_get_section_by_name(abfd, ".text"); } long offset = addr - text->vma; if (offset > 0) { if(FIND_LINE) { DemangleFunction(); // Save retrieved informations. stack.push_back(frame); } } } void Backtrace::DemangleFunction() { int status; char* tmp = abi::__cxa_demangle(frame.function, 0, 0, &status); // If demangling is successful, reallocate 'frame.function' pointer to // demangled name. Else if 'status != 0', leave 'frame.function as it is. if (status == 0) { frame.function = tmp; } } #else void Backtrace::GetAddress(int /* maxDepth */) { } void Backtrace::DecodeAddress(long /* address */) { } void Backtrace::DemangleFunction() { } #endif std::string Backtrace::ToString() { std::string stackStr; #ifdef HAS_BFD_DL std::ostringstream lineOss; std::ostringstream it; if(stack.size() <= 0) { stackStr = "Cannot give backtrace because program was compiled"; stackStr += " without: -g -rdynamic\nFor a backtrace,"; stackStr += " recompile with: -g -rdynamic.\n"; return stackStr; } for(unsigned int i = 0; i < stack.size(); i++) { frame = stack[i]; lineOss << frame.line; it << i + 1; stackStr += "[bt]: (" + it.str() + ") " + frame.file + ":" + frame.function + ":" + lineOss.str() + "\n"; lineOss.str(""); it.str(""); } #else stackStr = "[bt]: No backtrace for this OS. Work in progress."; #endif return stackStr; }<commit_msg>Dummy constructor<commit_after>/** * @file backtrace.cpp * @author Grzegorz Krajewski * * Implementation of the Backtrace class. * * This file is part of mlpack 2.0.1. * * mlpack is free software; you may redstribute it and/or modify it under the * terms of the 3-clause BSD license. You should have received a copy of the * 3-clause BSD license along with mlpack. If not, see * http://www.opensource.org/licenses/BSD-3-Clause for more information. */ #include <sstream> #ifdef HAS_BFD_DL #include <execinfo.h> #include <signal.h> #include <unistd.h> #include <cxxabi.h> #include <bfd.h> #include <dlfcn.h> #endif #include "prefixedoutstream.hpp" #include "backtrace.hpp" #include "log.hpp" // Easier to read Backtrace::DecodeAddress(). #ifdef HAS_BFD_DL #define TRACE_CONDITION_1 (!dladdr(trace[i], &addressHandler)) #define FIND_LINE (bfd_find_nearest_line(abfd, text, syms, offset, &frame.file, &frame.function, &frame.line) && frame.file) #endif using namespace mlpack; // Initialize Backtrace static inctances. Backtrace::Frames Backtrace::frame; std::vector<Backtrace::Frames> Backtrace::stack; #ifdef HAS_BFD_DL // Binary File Descriptor objects. bfd* abfd = 0; // Descriptor datastructure. asymbol **syms = 0; // Symbols datastructure. asection *text = 0; // Strings datastructure. #endif #ifdef HAS_BFD_DL Backtrace::Backtrace(int maxDepth) { frame.address = NULL; frame.function = "0"; frame.file = "0"; frame.line = 0; stack.clear(); GetAddress(maxDepth); } #else Backtrace::Backtrace() { // Dummy constructor } #endif #ifdef HAS_BFD_DL void Backtrace::GetAddress(int maxDepth) { void* trace[maxDepth]; int stackDepth = backtrace(trace, maxDepth); // Skip first stack frame (points to Backtrace::Backtrace). for (int i = 1; i < stackDepth; i++) { Dl_info addressHandler; //No backtrace will be printed if no compile flags: -g -rdynamic if(TRACE_CONDITION_1) { return ; } frame.address = addressHandler.dli_saddr; DecodeAddress((long)frame.address); } } void Backtrace::DecodeAddress(long addr) { // Check to see if there is anything to descript. If it doesn't, we'll // dump running program. if (!abfd) { char ename[1024]; int l = readlink("/proc/self/exe",ename,sizeof(ename)); if (l == -1) { perror("Failed to open executable!\n"); return; } ename[l] = 0; bfd_init(); abfd = bfd_openr(ename, 0); if (!abfd) { perror("bfd_openr failed: "); return; } bfd_check_format(abfd,bfd_object); unsigned storage_needed = bfd_get_symtab_upper_bound(abfd); syms = (asymbol **) malloc(storage_needed); text = bfd_get_section_by_name(abfd, ".text"); } long offset = addr - text->vma; if (offset > 0) { if(FIND_LINE) { DemangleFunction(); // Save retrieved informations. stack.push_back(frame); } } } void Backtrace::DemangleFunction() { int status; char* tmp = abi::__cxa_demangle(frame.function, 0, 0, &status); // If demangling is successful, reallocate 'frame.function' pointer to // demangled name. Else if 'status != 0', leave 'frame.function as it is. if (status == 0) { frame.function = tmp; } } #else void Backtrace::GetAddress(int /* maxDepth */) { } void Backtrace::DecodeAddress(long /* address */) { } void Backtrace::DemangleFunction() { } #endif std::string Backtrace::ToString() { std::string stackStr; #ifdef HAS_BFD_DL std::ostringstream lineOss; std::ostringstream it; if(stack.size() <= 0) { stackStr = "Cannot give backtrace because program was compiled"; stackStr += " without: -g -rdynamic\nFor a backtrace,"; stackStr += " recompile with: -g -rdynamic.\n"; return stackStr; } for(unsigned int i = 0; i < stack.size(); i++) { frame = stack[i]; lineOss << frame.line; it << i + 1; stackStr += "[bt]: (" + it.str() + ") " + frame.file + ":" + frame.function + ":" + lineOss.str() + "\n"; lineOss.str(""); it.str(""); } #else stackStr = "[bt]: No backtrace for this OS. Work in progress."; #endif return stackStr; } <|endoftext|>
<commit_before>/**************************************************************************** * * Copyright (C) 2014 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * 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 OWNER 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. * ****************************************************************************/ /** * @author Pavel Kirienko <pavel.kirienko@gmail.com> */ #include "mag.hpp" UavcanMagnetometerBridge::UavcanMagnetometerBridge(uavcan::INode& node) : device::CDev("uavcan_mag", "/dev/uavcan/mag"), _sub_mag(node) { _scale.x_scale = 1.0F; _scale.y_scale = 1.0F; _scale.z_scale = 1.0F; } UavcanMagnetometerBridge::~UavcanMagnetometerBridge() { if (_class_instance > 0) { (void)unregister_class_devname(MAG_DEVICE_PATH, _class_instance); } } const char *UavcanMagnetometerBridge::get_name() const { return "mag"; } int UavcanMagnetometerBridge::init() { // Init the libuavcan subscription int res = _sub_mag.start(MagCbBinder(this, &UavcanMagnetometerBridge::mag_sub_cb)); if (res < 0) { log("failed to start uavcan sub: %d", res); return res; } // Detect our device class _class_instance = register_class_devname(MAG_DEVICE_PATH); switch (_class_instance) { case CLASS_DEVICE_PRIMARY: { _orb_id = ORB_ID(sensor_mag0); break; } case CLASS_DEVICE_SECONDARY: { _orb_id = ORB_ID(sensor_mag1); break; } case CLASS_DEVICE_TERTIARY: { _orb_id = ORB_ID(sensor_mag2); break; } default: { log("invalid class instance: %d", _class_instance); (void)unregister_class_devname(MAG_DEVICE_PATH, _class_instance); return -1; } } log("inited with class instance %d", _class_instance); return 0; } int UavcanMagnetometerBridge::ioctl(struct file *filp, int cmd, unsigned long arg) { switch (cmd) { case MAGIOCSSAMPLERATE: case MAGIOCGSAMPLERATE: case MAGIOCSRANGE: case MAGIOCGRANGE: case MAGIOCSLOWPASS: case MAGIOCGLOWPASS: { return -EINVAL; } case MAGIOCSSCALE: { std::memcpy(&_scale, reinterpret_cast<const void*>(arg), sizeof(_scale)); log("new scale/offset: x: %f/%f y: %f/%f z: %f/%f", double(_scale.x_scale), double(_scale.x_offset), double(_scale.y_scale), double(_scale.y_offset), double(_scale.z_scale), double(_scale.z_offset)); return 0; } case MAGIOCGSCALE: { std::memcpy(reinterpret_cast<void*>(arg), &_scale, sizeof(_scale)); return 0; } case MAGIOCCALIBRATE: case MAGIOCEXSTRAP: case MAGIOCSELFTEST: { return -EINVAL; } case MAGIOCGEXTERNAL: { return 1; } default: { return CDev::ioctl(filp, cmd, arg); } } } void UavcanMagnetometerBridge::mag_sub_cb(const uavcan::ReceivedDataStructure<uavcan::equipment::ahrs::Magnetometer> &msg) { auto report = ::mag_report(); report.range_ga = 1.3F; // Arbitrary number, doesn't really mean anything report.timestamp = msg.getUtcTimestamp().toUSec(); if (report.timestamp == 0) { report.timestamp = msg.getMonotonicTimestamp().toUSec(); } report.x = (msg.magnetic_field[0] - _scale.x_offset) * _scale.x_scale; report.y = (msg.magnetic_field[1] - _scale.x_offset) * _scale.x_scale; report.z = (msg.magnetic_field[2] - _scale.x_offset) * _scale.x_scale; if (_orb_advert >= 0) { orb_publish(_orb_id, _orb_advert, &report); } else { _orb_advert = orb_advertise(_orb_id, &report); if (_orb_advert < 0) { log("ADVERT FAIL"); } else { log("advertised"); } } } <commit_msg>UAVCAN mag driver fix<commit_after>/**************************************************************************** * * Copyright (C) 2014 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * 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 OWNER 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. * ****************************************************************************/ /** * @author Pavel Kirienko <pavel.kirienko@gmail.com> */ #include "mag.hpp" UavcanMagnetometerBridge::UavcanMagnetometerBridge(uavcan::INode& node) : device::CDev("uavcan_mag", "/dev/uavcan/mag"), _sub_mag(node) { _scale.x_scale = 1.0F; _scale.y_scale = 1.0F; _scale.z_scale = 1.0F; } UavcanMagnetometerBridge::~UavcanMagnetometerBridge() { if (_class_instance > 0) { (void)unregister_class_devname(MAG_DEVICE_PATH, _class_instance); } } const char *UavcanMagnetometerBridge::get_name() const { return "mag"; } int UavcanMagnetometerBridge::init() { // Init the libuavcan subscription int res = _sub_mag.start(MagCbBinder(this, &UavcanMagnetometerBridge::mag_sub_cb)); if (res < 0) { log("failed to start uavcan sub: %d", res); return res; } // Detect our device class _class_instance = register_class_devname(MAG_DEVICE_PATH); switch (_class_instance) { case CLASS_DEVICE_PRIMARY: { _orb_id = ORB_ID(sensor_mag0); break; } case CLASS_DEVICE_SECONDARY: { _orb_id = ORB_ID(sensor_mag1); break; } case CLASS_DEVICE_TERTIARY: { _orb_id = ORB_ID(sensor_mag2); break; } default: { log("invalid class instance: %d", _class_instance); (void)unregister_class_devname(MAG_DEVICE_PATH, _class_instance); return -1; } } log("inited with class instance %d", _class_instance); return 0; } int UavcanMagnetometerBridge::ioctl(struct file *filp, int cmd, unsigned long arg) { switch (cmd) { case MAGIOCSSCALE: { std::memcpy(&_scale, reinterpret_cast<const void*>(arg), sizeof(_scale)); return 0; } case MAGIOCGSCALE: { std::memcpy(reinterpret_cast<void*>(arg), &_scale, sizeof(_scale)); return 0; } case MAGIOCSELFTEST: { return 0; // Nothing to do } case MAGIOCGEXTERNAL: { return 0; // We don't want anyone to transform the coordinate frame, so we declare it onboard } case MAGIOCSSAMPLERATE: { return 0; // Pretend that this stuff is supported to keep the sensor app happy } case MAGIOCCALIBRATE: case MAGIOCGSAMPLERATE: case MAGIOCSRANGE: case MAGIOCGRANGE: case MAGIOCSLOWPASS: case MAGIOCEXSTRAP: case MAGIOCGLOWPASS: { return -EINVAL; } default: { return CDev::ioctl(filp, cmd, arg); } } } void UavcanMagnetometerBridge::mag_sub_cb(const uavcan::ReceivedDataStructure<uavcan::equipment::ahrs::Magnetometer> &msg) { auto report = ::mag_report(); report.range_ga = 1.3F; // Arbitrary number, doesn't really mean anything report.timestamp = msg.getUtcTimestamp().toUSec(); if (report.timestamp == 0) { report.timestamp = msg.getMonotonicTimestamp().toUSec(); } report.x = (msg.magnetic_field[0] - _scale.x_offset) * _scale.x_scale; report.y = (msg.magnetic_field[1] - _scale.x_offset) * _scale.x_scale; report.z = (msg.magnetic_field[2] - _scale.x_offset) * _scale.x_scale; if (_orb_advert >= 0) { orb_publish(_orb_id, _orb_advert, &report); } else { _orb_advert = orb_advertise(_orb_id, &report); if (_orb_advert < 0) { log("ADVERT FAIL"); } else { log("advertised"); } } } <|endoftext|>