text
stringlengths
54
60.6k
<commit_before>/****************************************************************/ /* DO NOT MODIFY THIS HEADER */ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* */ /* (c) 2010 Battelle Energy Alliance, LLC */ /* ALL RIGHTS RESERVED */ /* */ /* Prepared by Battelle Energy Alliance, LLC */ /* Under Contract No. DE-AC07-05ID14517 */ /* With the U. S. Department of Energy */ /* */ /* See COPYRIGHT for full restrictions */ /****************************************************************/ #include "MaterialPropertyIO.h" #include "MaterialPropertyStorage.h" #include "MooseMesh.h" #include "FEProblem.h" #include <cstring> const unsigned int MaterialPropertyIO::file_version = 2; struct MSMPHeader { char _id[4]; // 4 letter ID unsigned int _file_version; // file version }; MaterialPropertyIO::MaterialPropertyIO(FEProblem & fe_problem) : _fe_problem(fe_problem), _mesh(_fe_problem.mesh()), _material_props(_fe_problem._material_props), _bnd_material_props(_fe_problem._bnd_material_props) { } MaterialPropertyIO::~MaterialPropertyIO() { } void MaterialPropertyIO::write(const std::string & file_name) { HashMap<const Elem *, HashMap<unsigned int, MaterialProperties> > & props = _material_props.props(); HashMap<const Elem *, HashMap<unsigned int, MaterialProperties> > & propsOld = _material_props.propsOld(); HashMap<const Elem *, HashMap<unsigned int, MaterialProperties> > & propsOlder = _material_props.propsOlder(); HashMap<const Elem *, HashMap<unsigned int, MaterialProperties> > & bnd_props = _bnd_material_props.props(); HashMap<const Elem *, HashMap<unsigned int, MaterialProperties> > & bnd_propsOld = _bnd_material_props.propsOld(); HashMap<const Elem *, HashMap<unsigned int, MaterialProperties> > & bnd_propsOlder = _bnd_material_props.propsOlder(); std::vector<unsigned int> & prop_ids = _material_props.statefulProps(); unsigned int n_props = prop_ids.size(); // number of properties in this block std::ofstream out; // head node writes the header if (libMesh::processor_id() == 0) { out.open(file_name.c_str(), std::ios::out | std::ios::binary); // header MSMPHeader head; std::memcpy(head._id, "MSMP", 4); head._file_version = file_version; out.write((const char *) &head, sizeof(head)); // save the number of elements in this block (since we do only 1 block right now, we store everything) unsigned int n_elems = props.size(); //_mesh.nElem(); out.write((const char *) &n_elems, sizeof(n_elems)); // properties out.write((const char *) &n_props, sizeof(n_props)); // property names for (unsigned int i = 0; i < n_props; i++) { unsigned int pid = prop_ids[i]; std::string prop_name = _material_props.statefulPropNames()[pid]; out.write(prop_name.c_str(), prop_name.length() + 1); // do not forget the trailing zero ;-) } out.close(); } libMesh::Parallel::barrier(libMesh::CommWorld); // now each process dump its part, appending into the file for (unsigned int proc = 0; proc < libMesh::n_processors(); proc++) { if (libMesh::processor_id() == proc) { out.open(file_name.c_str(), std::ios::app | std::ios::binary); // save current material properties for (HashMap<const Elem *, HashMap<unsigned int, MaterialProperties> >::iterator props_it=props.begin(); props_it != props.end(); ++props_it) { const Elem * elem = props_it->first; if (elem && elem->processor_id() == proc) { unsigned int elem_id = elem->id(); out.write((const char *) &elem_id, sizeof(elem_id)); // write out the properties into mem buffer std::ostringstream prop_blk; for (unsigned int i = 0; i < n_props; i++) { props[elem][0][i]->store(prop_blk); propsOld[elem][0][i]->store(prop_blk); if (_material_props.hasOlderProperties()) propsOlder[elem][0][i]->store(prop_blk); } unsigned int prop_blk_size = prop_blk.tellp(); out.write((const char *) &prop_blk_size, sizeof(prop_blk_size)); out << prop_blk.str(); } } out.close(); } libMesh::Parallel::barrier(libMesh::CommWorld); } // again, each process dumps its part, appending into the file for (unsigned int proc = 0; proc < libMesh::n_processors(); proc++) { if (libMesh::processor_id() == proc) { out.open(file_name.c_str(), std::ios::app | std::ios::binary); // save current material properties for (HashMap<const Elem *, HashMap<unsigned int, MaterialProperties> >::iterator props_it=props.begin(); props_it != props.end(); ++props_it) { const Elem * elem = props_it->first; if (elem && elem->processor_id() == proc) { unsigned int elem_id = elem->id(); out.write((const char *) &elem_id, sizeof(elem_id)); // save the material props on sides unsigned int n_sides = bnd_props[elem].size(); out.write((const char *) &n_sides, sizeof(n_sides)); for (HashMap<unsigned int, MaterialProperties>::iterator side_it = bnd_props[elem].begin(); side_it != bnd_props[elem].end(); ++side_it) { unsigned int s = side_it->first; out.write((const char *) &s, sizeof(s)); // write out the properties into mem buffer std::ostringstream prop_blk; for (unsigned int i = 0; i < n_props; i++) { bnd_props[elem][s][i]->store(prop_blk); bnd_propsOld[elem][s][i]->store(prop_blk); if (_material_props.hasOlderProperties()) bnd_propsOlder[elem][s][i]->store(prop_blk); } unsigned int prop_blk_size = prop_blk.tellp(); out.write((const char *) &prop_blk_size, sizeof(prop_blk_size)); out << prop_blk.str(); } } } out.close(); } libMesh::Parallel::barrier(libMesh::CommWorld); } } void MaterialPropertyIO::read(const std::string & file_name) { std::ifstream in(file_name.c_str(), std::ios::in | std::ios::binary); // header MSMPHeader head; in.read((char *) &head, sizeof(head)); // check the header if (!(head._id[0] == 'M' && head._id[1] == 'S' && head._id[2] == 'M' && head._id[3] == 'P')) mooseError("Corrupted material properties file"); // check the file version if (head._file_version > file_version) mooseError("Trying to restart from a newer file version - you need to update MOOSE"); // grab some references we will need to later HashMap<const Elem *, HashMap<unsigned int, MaterialProperties> > & props = _material_props.props(); HashMap<const Elem *, HashMap<unsigned int, MaterialProperties> > & propsOld = _material_props.propsOld(); HashMap<const Elem *, HashMap<unsigned int, MaterialProperties> > & propsOlder = _material_props.propsOlder(); HashMap<const Elem *, HashMap<unsigned int, MaterialProperties> > & bnd_props = _bnd_material_props.props(); HashMap<const Elem *, HashMap<unsigned int, MaterialProperties> > & bnd_propsOld = _bnd_material_props.propsOld(); HashMap<const Elem *, HashMap<unsigned int, MaterialProperties> > & bnd_propsOlder = _bnd_material_props.propsOlder(); std::map<unsigned int, std::string> stateful_prop_names = _material_props.statefulPropNames(); std::map<std::string, unsigned int> stateful_prop_ids; // inverse map of stateful_prop_names for (std::map<unsigned int, std::string>::iterator it = stateful_prop_names.begin(); it != stateful_prop_names.end(); ++it) stateful_prop_ids[it->second] = it->first; // number of elements unsigned int n_elems = props.size(); in.read((char *) &n_elems, sizeof(n_elems)); // number of properties in this block unsigned int n_props = 0; in.read((char *) &n_props, sizeof(n_props)); // property names std::vector<std::string> prop_names(n_props); for (unsigned int i = 0; i < n_props; i++) { std::string prop_name; char ch = 0; do { in.read(&ch, 1); if (ch != '\0') prop_name += ch; } while (ch != '\0'); prop_names[i] = prop_name; } for (unsigned int i = 0; i < n_elems; i++) { unsigned int elem_id = 0; in.read((char *) &elem_id, sizeof(elem_id)); unsigned int blk_size = 0; in.read((char *) &blk_size, sizeof(blk_size)); const Elem * elem = _mesh.elem(elem_id); if (elem && (elem->processor_id() == libMesh::processor_id())) { // read in the properties themselves for (unsigned int i = 0; i < n_props; i++) { if (props[elem][0][i] != NULL) props[elem][0][i]->load(in); if (propsOld[elem][0][i] != NULL) propsOld[elem][0][i]->load(in); if (_material_props.hasOlderProperties()) // this should actually check if the value is stored in the file (we do not store it right now) if (propsOlder[elem][0][i] != NULL) propsOlder[elem][0][i]->load(in); } } else in.seekg(blk_size, std::ios_base::cur); } // load in the material props on sides for (unsigned int i = 0; i < n_elems; i++) { unsigned int elem_id = 0; in.read((char *) &elem_id, sizeof(elem_id)); unsigned int n_sides = 0; in.read((char *) &n_sides, sizeof(n_sides)); for (unsigned int s = 0; s < n_sides; s++) { unsigned int side = 0; in.read((char *) &side, sizeof(side)); unsigned int blk_size = 0; in.read((char *) &blk_size, sizeof(blk_size)); const Elem * elem = _mesh.elem(elem_id); if (elem && (elem->processor_id() == libMesh::processor_id())) { // read in the properties themselves for (unsigned int i = 0; i < n_props; i++) { if (bnd_props[elem][side][i] != NULL) bnd_props[elem][side][i]->load(in); if (bnd_propsOld[elem][side][i] != NULL) bnd_propsOld[elem][side][i]->load(in); if (_material_props.hasOlderProperties()) // this should actually check if the value is stored in the file (we do not store it right now) if (bnd_propsOlder[elem][side][i] != NULL) bnd_propsOlder[elem][side][i]->load(in); } } else in.seekg(blk_size, std::ios_base::cur); } } in.close(); } <commit_msg>undo change refs #1169<commit_after>/****************************************************************/ /* DO NOT MODIFY THIS HEADER */ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* */ /* (c) 2010 Battelle Energy Alliance, LLC */ /* ALL RIGHTS RESERVED */ /* */ /* Prepared by Battelle Energy Alliance, LLC */ /* Under Contract No. DE-AC07-05ID14517 */ /* With the U. S. Department of Energy */ /* */ /* See COPYRIGHT for full restrictions */ /****************************************************************/ #include "MaterialPropertyIO.h" #include "MaterialPropertyStorage.h" #include "MooseMesh.h" #include "FEProblem.h" #include <cstring> const unsigned int MaterialPropertyIO::file_version = 2; struct MSMPHeader { char _id[4]; // 4 letter ID unsigned int _file_version; // file version }; MaterialPropertyIO::MaterialPropertyIO(FEProblem & fe_problem) : _fe_problem(fe_problem), _mesh(_fe_problem.mesh()), _material_props(_fe_problem._material_props), _bnd_material_props(_fe_problem._bnd_material_props) { } MaterialPropertyIO::~MaterialPropertyIO() { } void MaterialPropertyIO::write(const std::string & file_name) { HashMap<const Elem *, HashMap<unsigned int, MaterialProperties> > & props = _material_props.props(); HashMap<const Elem *, HashMap<unsigned int, MaterialProperties> > & propsOld = _material_props.propsOld(); HashMap<const Elem *, HashMap<unsigned int, MaterialProperties> > & propsOlder = _material_props.propsOlder(); HashMap<const Elem *, HashMap<unsigned int, MaterialProperties> > & bnd_props = _bnd_material_props.props(); HashMap<const Elem *, HashMap<unsigned int, MaterialProperties> > & bnd_propsOld = _bnd_material_props.propsOld(); HashMap<const Elem *, HashMap<unsigned int, MaterialProperties> > & bnd_propsOlder = _bnd_material_props.propsOlder(); std::vector<unsigned int> & prop_ids = _material_props.statefulProps(); unsigned int n_props = prop_ids.size(); // number of properties in this block std::ofstream out; // head node writes the header if (libMesh::processor_id() == 0) { out.open(file_name.c_str(), std::ios::out | std::ios::binary); // header MSMPHeader head; std::memcpy(head._id, "MSMP", 4); head._file_version = file_version; out.write((const char *) &head, sizeof(head)); // save the number of elements in this block (since we do only 1 block right now, we store everything) unsigned int n_elems = _mesh.nElem(); out.write((const char *) &n_elems, sizeof(n_elems)); // properties out.write((const char *) &n_props, sizeof(n_props)); // property names for (unsigned int i = 0; i < n_props; i++) { unsigned int pid = prop_ids[i]; std::string prop_name = _material_props.statefulPropNames()[pid]; out.write(prop_name.c_str(), prop_name.length() + 1); // do not forget the trailing zero ;-) } out.close(); } libMesh::Parallel::barrier(libMesh::CommWorld); // now each process dump its part, appending into the file for (unsigned int proc = 0; proc < libMesh::n_processors(); proc++) { if (libMesh::processor_id() == proc) { out.open(file_name.c_str(), std::ios::app | std::ios::binary); // save current material properties for (HashMap<const Elem *, HashMap<unsigned int, MaterialProperties> >::iterator props_it=props.begin(); props_it != props.end(); ++props_it) { const Elem * elem = props_it->first; if (elem && elem->processor_id() == proc) { unsigned int elem_id = elem->id(); out.write((const char *) &elem_id, sizeof(elem_id)); // write out the properties into mem buffer std::ostringstream prop_blk; for (unsigned int i = 0; i < n_props; i++) { props[elem][0][i]->store(prop_blk); propsOld[elem][0][i]->store(prop_blk); if (_material_props.hasOlderProperties()) propsOlder[elem][0][i]->store(prop_blk); } unsigned int prop_blk_size = prop_blk.tellp(); out.write((const char *) &prop_blk_size, sizeof(prop_blk_size)); out << prop_blk.str(); } } out.close(); } libMesh::Parallel::barrier(libMesh::CommWorld); } // again, each process dumps its part, appending into the file for (unsigned int proc = 0; proc < libMesh::n_processors(); proc++) { if (libMesh::processor_id() == proc) { out.open(file_name.c_str(), std::ios::app | std::ios::binary); // save current material properties for (HashMap<const Elem *, HashMap<unsigned int, MaterialProperties> >::iterator props_it=props.begin(); props_it != props.end(); ++props_it) { const Elem * elem = props_it->first; if (elem && elem->processor_id() == proc) { unsigned int elem_id = elem->id(); out.write((const char *) &elem_id, sizeof(elem_id)); // save the material props on sides unsigned int n_sides = bnd_props[elem].size(); out.write((const char *) &n_sides, sizeof(n_sides)); for (HashMap<unsigned int, MaterialProperties>::iterator side_it = bnd_props[elem].begin(); side_it != bnd_props[elem].end(); ++side_it) { unsigned int s = side_it->first; out.write((const char *) &s, sizeof(s)); // write out the properties into mem buffer std::ostringstream prop_blk; for (unsigned int i = 0; i < n_props; i++) { bnd_props[elem][s][i]->store(prop_blk); bnd_propsOld[elem][s][i]->store(prop_blk); if (_material_props.hasOlderProperties()) bnd_propsOlder[elem][s][i]->store(prop_blk); } unsigned int prop_blk_size = prop_blk.tellp(); out.write((const char *) &prop_blk_size, sizeof(prop_blk_size)); out << prop_blk.str(); } } } out.close(); } libMesh::Parallel::barrier(libMesh::CommWorld); } } void MaterialPropertyIO::read(const std::string & file_name) { std::ifstream in(file_name.c_str(), std::ios::in | std::ios::binary); // header MSMPHeader head; in.read((char *) &head, sizeof(head)); // check the header if (!(head._id[0] == 'M' && head._id[1] == 'S' && head._id[2] == 'M' && head._id[3] == 'P')) mooseError("Corrupted material properties file"); // check the file version if (head._file_version > file_version) mooseError("Trying to restart from a newer file version - you need to update MOOSE"); // grab some references we will need to later HashMap<const Elem *, HashMap<unsigned int, MaterialProperties> > & props = _material_props.props(); HashMap<const Elem *, HashMap<unsigned int, MaterialProperties> > & propsOld = _material_props.propsOld(); HashMap<const Elem *, HashMap<unsigned int, MaterialProperties> > & propsOlder = _material_props.propsOlder(); HashMap<const Elem *, HashMap<unsigned int, MaterialProperties> > & bnd_props = _bnd_material_props.props(); HashMap<const Elem *, HashMap<unsigned int, MaterialProperties> > & bnd_propsOld = _bnd_material_props.propsOld(); HashMap<const Elem *, HashMap<unsigned int, MaterialProperties> > & bnd_propsOlder = _bnd_material_props.propsOlder(); std::map<unsigned int, std::string> stateful_prop_names = _material_props.statefulPropNames(); std::map<std::string, unsigned int> stateful_prop_ids; // inverse map of stateful_prop_names for (std::map<unsigned int, std::string>::iterator it = stateful_prop_names.begin(); it != stateful_prop_names.end(); ++it) stateful_prop_ids[it->second] = it->first; // number of elements unsigned int n_elems = props.size(); in.read((char *) &n_elems, sizeof(n_elems)); // number of properties in this block unsigned int n_props = 0; in.read((char *) &n_props, sizeof(n_props)); // property names std::vector<std::string> prop_names(n_props); for (unsigned int i = 0; i < n_props; i++) { std::string prop_name; char ch = 0; do { in.read(&ch, 1); if (ch != '\0') prop_name += ch; } while (ch != '\0'); prop_names[i] = prop_name; } for (unsigned int i = 0; i < n_elems; i++) { unsigned int elem_id = 0; in.read((char *) &elem_id, sizeof(elem_id)); unsigned int blk_size = 0; in.read((char *) &blk_size, sizeof(blk_size)); const Elem * elem = _mesh.elem(elem_id); if (elem && (elem->processor_id() == libMesh::processor_id())) { // read in the properties themselves for (unsigned int i = 0; i < n_props; i++) { if (props[elem][0][i] != NULL) props[elem][0][i]->load(in); if (propsOld[elem][0][i] != NULL) propsOld[elem][0][i]->load(in); if (_material_props.hasOlderProperties()) // this should actually check if the value is stored in the file (we do not store it right now) if (propsOlder[elem][0][i] != NULL) propsOlder[elem][0][i]->load(in); } } else in.seekg(blk_size, std::ios_base::cur); } // load in the material props on sides for (unsigned int i = 0; i < n_elems; i++) { unsigned int elem_id = 0; in.read((char *) &elem_id, sizeof(elem_id)); unsigned int n_sides = 0; in.read((char *) &n_sides, sizeof(n_sides)); for (unsigned int s = 0; s < n_sides; s++) { unsigned int side = 0; in.read((char *) &side, sizeof(side)); unsigned int blk_size = 0; in.read((char *) &blk_size, sizeof(blk_size)); const Elem * elem = _mesh.elem(elem_id); if (elem && (elem->processor_id() == libMesh::processor_id())) { // read in the properties themselves for (unsigned int i = 0; i < n_props; i++) { if (bnd_props[elem][side][i] != NULL) bnd_props[elem][side][i]->load(in); if (bnd_propsOld[elem][side][i] != NULL) bnd_propsOld[elem][side][i]->load(in); if (_material_props.hasOlderProperties()) // this should actually check if the value is stored in the file (we do not store it right now) if (bnd_propsOlder[elem][side][i] != NULL) bnd_propsOlder[elem][side][i]->load(in); } } else in.seekg(blk_size, std::ios_base::cur); } } in.close(); } <|endoftext|>
<commit_before>// Filename: test_physics.cxx // Created by: charles (13Jun00) // //////////////////////////////////////////////////////////////////// // // PANDA 3D SOFTWARE // Copyright (c) 2001 - 2004, Disney Enterprises, Inc. All rights reserved // // All use of this software is subject to the terms of the Panda 3d // Software license. You should have received a copy of this license // along with this source code; you will also find a current copy of // the license at http://etc.cmu.edu/panda3d/docs/license/ . // // To contact the maintainers of this program write to // panda3d-general@lists.sourceforge.net . // //////////////////////////////////////////////////////////////////// #include <iostream> #include "physical.h" #include "physicsManager.h" #include "forces.h" class Baseball : public Physical { public: int ttl_balls; int color; Baseball(int tb = 1) : ttl_balls(tb), Physical(tb, true) {} }; int main(int, char **) { PhysicsManager physics_manager; Baseball b(8); // test the noise force Baseball nf_b; nf_b.get_phys_body()->set_position(0.0f, 0.0f, 0.0f); nf_b.get_phys_body()->set_velocity(1.0f / 16.0f, 0.0f, 0.0f); nf_b.get_phys_body()->set_active(true); nf_b.get_phys_body()->set_mass(1.0f); LinearNoiseForce nf(1.0, false); physics_manager.attach_physical(&nf_b); int steps=16; float delta_time=1.0f/(float)steps; while (steps--) { cout << "ball: " << nf_b.get_phys_body()->get_position() << endl; cout << "nf: " << nf.get_vector(nf_b.get_phys_body()) << endl; physics_manager.do_physics(delta_time); } physics_manager.remove_physical(&nf_b); // get on with life b.add_linear_force(new LinearJitterForce(0.1f)); int i=0; for (PhysicsObject::Vector::const_iterator co=b.get_object_vector().begin(); co != b.get_object_vector().end(); ++i, ++co) { (*co)->set_position(i * 2.0f, float(i), 0.0f); (*co)->set_velocity(5.0f, 0.0f, 30.0f); (*co)->set_active(true); (*co)->set_mass(1.0f); } physics_manager.attach_physical(&b); physics_manager.add_linear_force(new LinearVectorForce(0.0f, 0.0f, -9.8f, 1.0f, false)); cout << "Object vector:" << endl; for (PhysicsObject::Vector::const_iterator co=b.get_object_vector().begin(); co != b.get_object_vector().end(); ++co) { cout << "vel: " << (*co)->get_velocity() << " "; cout << "pos: " << (*co)->get_position() << endl; } physics_manager.do_physics(1.0f); cout << "Physics have been applied." << endl; for (PhysicsObject::Vector::const_iterator co=b.get_object_vector().begin(); co != b.get_object_vector().end(); ++co) { cout << "vel: " << (*co)->get_velocity() << " "; cout << "pos: " << (*co)->get_position() << endl; } } <commit_msg>*** empty log message ***<commit_after>// Filename: test_physics.cxx // Created by: charles (13Jun00) // //////////////////////////////////////////////////////////////////// // // PANDA 3D SOFTWARE // Copyright (c) 2001 - 2004, Disney Enterprises, Inc. All rights reserved // // All use of this software is subject to the terms of the Panda 3d // Software license. You should have received a copy of this license // along with this source code; you will also find a current copy of // the license at http://etc.cmu.edu/panda3d/docs/license/ . // // To contact the maintainers of this program write to // panda3d-general@lists.sourceforge.net . // //////////////////////////////////////////////////////////////////// #include <iostream> #include "physical.h" #include "physicsManager.h" #include "forces.h" class Baseball : public Physical { public: int ttl_balls; //int color; Baseball(int tb = 1) : ttl_balls(tb), Physical(tb, true) {} }; int main(int argc, char **argv) { PhysicsManager physics_manager; Baseball b(8); // test the noise force Baseball nf_b; nf_b.get_phys_body()->set_position(0.0f, 0.0f, 0.0f); nf_b.get_phys_body()->set_velocity(1.0f / 16.0f, 0.0f, 0.0f); nf_b.get_phys_body()->set_active(true); nf_b.get_phys_body()->set_mass(1.0f); LinearNoiseForce nf(1.0, false); physics_manager.attach_physical(&nf_b); int steps=16; float delta_time=1.0f/(float)steps; while (steps--) { cout << "ball: " << nf_b.get_phys_body()->get_position() << endl; cout << "nf: " << nf.get_vector(nf_b.get_phys_body()) << endl; physics_manager.do_physics(delta_time); } physics_manager.remove_physical(&nf_b); // get on with life b.add_linear_force(new LinearJitterForce(0.1f)); int i=0; for (PhysicsObject::Vector::const_iterator co=b.get_object_vector().begin(); co != b.get_object_vector().end(); ++i, ++co) { (*co)->set_position(i * 2.0f, float(i), 0.0f); (*co)->set_velocity(5.0f, 0.0f, 30.0f); (*co)->set_active(true); (*co)->set_mass(1.0f); } physics_manager.attach_physical(&b); physics_manager.add_linear_force(new LinearVectorForce(0.0f, 0.0f, -9.8f, 1.0f, false)); cout << "Object vector:" << endl; for (PhysicsObject::Vector::const_iterator co=b.get_object_vector().begin(); co != b.get_object_vector().end(); ++co) { cout << "vel: " << (*co)->get_velocity() << " "; cout << "pos: " << (*co)->get_position() << endl; } physics_manager.do_physics(1.0f); cout << "Physics have been applied." << endl; for (PhysicsObject::Vector::const_iterator co=b.get_object_vector().begin(); co != b.get_object_vector().end(); ++co) { cout << "vel: " << (*co)->get_velocity() << " "; cout << "pos: " << (*co)->get_position() << endl; } return 0; } <|endoftext|>
<commit_before>// Copyright (C) 2019 - 2020 by Pedro Mendes, Rector and Visitors of the // University of Virginia, University of Heidelberg, and University // of Connecticut School of Medicine. // All rights reserved. // Copyright (C) 2017 - 2018 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and University of // of Connecticut School of Medicine. // All rights reserved. // Copyright (C) 2010 - 2016 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and The University // of Manchester. // All rights reserved. // Copyright (C) 2009 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., EML Research, gGmbH, University of Heidelberg, // and The University of Manchester. // All rights reserved. #include "CQEFMListWidget.h" #include "copasi/elementaryFluxModes/CEFMTask.h" #include <copasi/core/CRootContainer.h> #include <copasi/commandline/CConfigurationFile.h> CQEFMListWidget::CQEFMListWidget(QWidget *parent, const char *name) : QWidget(parent), mpTask(NULL), mpProxyModel(NULL), mpFluxModeDM(NULL) { setObjectName(QString::fromUtf8(name)); setupUi(this); mpEFMTable->verticalHeader()->hide(); #if QT_VERSION >= 0x050000 mpEFMTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Interactive); #endif if (CRootContainer::getConfiguration()->resizeToContents()) { #if QT_VERSION >= 0x050000 mpEFMTable->verticalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents); #else mpEFMTable->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents); #endif } mpEFMTable->sortByColumn(COL_ROW_NUMBER, Qt::AscendingOrder); //Create Source Data Model. mpFluxModeDM = new CQFluxModeDM(this); //Create the Proxy Model for sorting/filtering and set its properties. mpProxyModel = new CQSortFilterProxyModel(); mpProxyModel->setSortCaseSensitivity(Qt::CaseInsensitive); mpProxyModel->setFilterKeyColumn(-1); mpProxyModel->setSourceModel(mpFluxModeDM); //Set Model for the TableView mpEFMTable->setModel(NULL); mpEFMTable->setModel(mpProxyModel); if (CRootContainer::getConfiguration()->resizeToContents()) { mpEFMTable->resizeColumnsToContents(); } connect(this, SIGNAL(initFilter()), this, SLOT(slotFilterChanged())); connect(mpLEFilter, SIGNAL(textChanged(const QString &)), this, SLOT(slotFilterChanged())); } CQEFMListWidget::~CQEFMListWidget() { // TODO Auto-generated destructor stub pdelete(mpProxyModel); } bool CQEFMListWidget::loadResult(const CEFMTask *pTask) { QByteArray State = mpEFMTable->horizontalHeader()->saveState(); blockSignals(true); mpTask = pTask; mpFluxModeDM->setTask(mpTask); mpProxyModel->setSourceModel(mpFluxModeDM); //Set Model for the TableView mpEFMTable->setModel(NULL); mpEFMTable->setModel(mpProxyModel); mpEFMTable->horizontalHeader()->restoreState(State); blockSignals(false); if (CRootContainer::getConfiguration()->resizeToContents()) { mpEFMTable->resizeColumnsToContents(); } emit initFilter(); return true; } void CQEFMListWidget::slotFilterChanged() { QString Filter = mpLEFilter->text(); if (Filter.isEmpty()) { mpProxyModel->setFilterRegExp(QRegExp()); return; } QRegExp regExp(Filter, Qt::CaseInsensitive, QRegExp::RegExp); mpProxyModel->setFilterRegExp(regExp); while (mpProxyModel->canFetchMore(QModelIndex())) mpProxyModel->fetchMore(QModelIndex()); } <commit_msg>Bug 2946: Vertical height is always adjusted in the EFM results.<commit_after>// Copyright (C) 2019 - 2020 by Pedro Mendes, Rector and Visitors of the // University of Virginia, University of Heidelberg, and University // of Connecticut School of Medicine. // All rights reserved. // Copyright (C) 2017 - 2018 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and University of // of Connecticut School of Medicine. // All rights reserved. // Copyright (C) 2010 - 2016 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and The University // of Manchester. // All rights reserved. // Copyright (C) 2009 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., EML Research, gGmbH, University of Heidelberg, // and The University of Manchester. // All rights reserved. #include "CQEFMListWidget.h" #include "copasi/elementaryFluxModes/CEFMTask.h" #include <copasi/core/CRootContainer.h> #include <copasi/commandline/CConfigurationFile.h> CQEFMListWidget::CQEFMListWidget(QWidget *parent, const char *name) : QWidget(parent), mpTask(NULL), mpProxyModel(NULL), mpFluxModeDM(NULL) { setObjectName(QString::fromUtf8(name)); setupUi(this); mpEFMTable->verticalHeader()->hide(); #if QT_VERSION >= 0x050000 mpEFMTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Interactive); #endif #if QT_VERSION >= 0x050000 mpEFMTable->verticalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents); #else mpEFMTable->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents); #endif mpEFMTable->sortByColumn(COL_ROW_NUMBER, Qt::AscendingOrder); //Create Source Data Model. mpFluxModeDM = new CQFluxModeDM(this); //Create the Proxy Model for sorting/filtering and set its properties. mpProxyModel = new CQSortFilterProxyModel(); mpProxyModel->setSortCaseSensitivity(Qt::CaseInsensitive); mpProxyModel->setFilterKeyColumn(-1); mpProxyModel->setSourceModel(mpFluxModeDM); //Set Model for the TableView mpEFMTable->setModel(NULL); mpEFMTable->setModel(mpProxyModel); if (CRootContainer::getConfiguration()->resizeToContents()) { mpEFMTable->resizeColumnsToContents(); } connect(this, SIGNAL(initFilter()), this, SLOT(slotFilterChanged())); connect(mpLEFilter, SIGNAL(textChanged(const QString &)), this, SLOT(slotFilterChanged())); } CQEFMListWidget::~CQEFMListWidget() { // TODO Auto-generated destructor stub pdelete(mpProxyModel); } bool CQEFMListWidget::loadResult(const CEFMTask *pTask) { QByteArray State = mpEFMTable->horizontalHeader()->saveState(); blockSignals(true); mpTask = pTask; mpFluxModeDM->setTask(mpTask); mpProxyModel->setSourceModel(mpFluxModeDM); //Set Model for the TableView mpEFMTable->setModel(NULL); mpEFMTable->setModel(mpProxyModel); mpEFMTable->horizontalHeader()->restoreState(State); blockSignals(false); if (CRootContainer::getConfiguration()->resizeToContents()) { mpEFMTable->resizeColumnsToContents(); } emit initFilter(); return true; } void CQEFMListWidget::slotFilterChanged() { QString Filter = mpLEFilter->text(); if (Filter.isEmpty()) { mpProxyModel->setFilterRegExp(QRegExp()); return; } QRegExp regExp(Filter, Qt::CaseInsensitive, QRegExp::RegExp); mpProxyModel->setFilterRegExp(regExp); while (mpProxyModel->canFetchMore(QModelIndex())) mpProxyModel->fetchMore(QModelIndex()); } <|endoftext|>
<commit_before>/* Copyright 2020 The TensorFlow 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. ==============================================================================*/ #include "absl/container/flat_hash_map.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/op_requires.h" #include "tensorflow/core/framework/register_types.h" #include "tensorflow/core/framework/tensor.h" #include "tensorflow/core/platform/errors.h" #include "tensorflow/core/platform/types.h" namespace tensorflow { template <class T> using BatchedMap = std::vector<absl::flat_hash_map<int64, T>>; namespace { // TODO(momernick): Extend this function to work with outputs of rank > 2. template <class T> Status OutputSparse(const BatchedMap<T>& per_batch_counts, int num_values, bool is_1d, OpKernelContext* context) { int total_values = 0; int num_batches = per_batch_counts.size(); for (const auto& per_batch_count : per_batch_counts) { total_values += per_batch_count.size(); } Tensor* indices; int inner_dim = is_1d ? 1 : 2; TF_RETURN_IF_ERROR(context->allocate_output( 0, TensorShape({total_values, inner_dim}), &indices)); Tensor* values; TF_RETURN_IF_ERROR( context->allocate_output(1, TensorShape({total_values}), &values)); auto output_indices = indices->matrix<int64>(); auto output_values = values->flat<T>(); int64 value_loc = 0; for (int b = 0; b < num_batches; ++b) { const auto& per_batch_count = per_batch_counts[b]; std::vector<std::pair<int, T>> pairs(per_batch_count.begin(), per_batch_count.end()); std::sort(pairs.begin(), pairs.end()); for (const auto& x : pairs) { if (is_1d) { output_indices(value_loc, 0) = x.first; } else { output_indices(value_loc, 0) = b; output_indices(value_loc, 1) = x.first; } output_values(value_loc) = x.second; ++value_loc; } } Tensor* dense_shape; if (is_1d) { TF_RETURN_IF_ERROR( context->allocate_output(2, TensorShape({1}), &dense_shape)); dense_shape->flat<int64>().data()[0] = num_values; } else { TF_RETURN_IF_ERROR( context->allocate_output(2, TensorShape({2}), &dense_shape)); dense_shape->flat<int64>().data()[0] = num_batches; dense_shape->flat<int64>().data()[1] = num_values; } return Status::OK(); } int GetOutputSize(int max_seen, int max_length, int min_length) { return max_length > 0 ? max_length : std::max((max_seen + 1), min_length); } } // namespace template <class T, class W> class DenseCount : public OpKernel { public: explicit DenseCount(OpKernelConstruction* context) : OpKernel(context) { OP_REQUIRES_OK(context, context->GetAttr("minlength", &minlength_)); OP_REQUIRES_OK(context, context->GetAttr("maxlength", &maxlength_)); OP_REQUIRES_OK(context, context->GetAttr("binary_output", &binary_output_)); } void Compute(OpKernelContext* context) override { const Tensor& data = context->input(0); const Tensor& weights = context->input(1); bool use_weights = weights.NumElements() > 0; OP_REQUIRES(context, TensorShapeUtils::IsVector(data.shape()) || TensorShapeUtils::IsMatrix(data.shape()), errors::InvalidArgument( "Input must be a 1 or 2-dimensional tensor. Got: ", data.shape().DebugString())); if (use_weights) { OP_REQUIRES( context, weights.shape() == data.shape(), errors::InvalidArgument( "Weights and data must have the same shape. Weight shape: ", weights.shape().DebugString(), "; data shape: ", data.shape().DebugString())); } bool is_1d = TensorShapeUtils::IsVector(data.shape()); int negative_valued_axis = -1; int num_batch_dimensions = (data.shape().dims() + negative_valued_axis); int num_batch_elements = 1; for (int i = 0; i < num_batch_dimensions; ++i) { OP_REQUIRES(context, data.shape().dim_size(i) != 0, errors::InvalidArgument( "Invalid input: Shapes dimension cannot be 0.")); num_batch_elements *= data.shape().dim_size(i); } int num_value_elements = data.shape().num_elements() / num_batch_elements; auto per_batch_counts = BatchedMap<W>(num_batch_elements); T max_value = 0; const auto data_values = data.flat<T>(); const auto weight_values = weights.flat<W>(); int i = 0; for (int b = 0; b < num_batch_elements; ++b) { for (int v = 0; v < num_value_elements; ++v) { const auto& value = data_values(i); if (value >= 0 && (maxlength_ <= 0 || value < maxlength_)) { if (binary_output_) { per_batch_counts[b][value] = 1; } else if (use_weights) { per_batch_counts[b][value] += weight_values(i); } else { per_batch_counts[b][value]++; } if (value > max_value) { max_value = value; } } ++i; } } int num_output_values = GetOutputSize(max_value, maxlength_, minlength_); OP_REQUIRES_OK(context, OutputSparse<W>(per_batch_counts, num_output_values, is_1d, context)); } private: int maxlength_; int minlength_; bool binary_output_; }; template <class T, class W> class SparseCount : public OpKernel { public: explicit SparseCount(OpKernelConstruction* context) : OpKernel(context) { OP_REQUIRES_OK(context, context->GetAttr("minlength", &minlength_)); OP_REQUIRES_OK(context, context->GetAttr("maxlength", &maxlength_)); OP_REQUIRES_OK(context, context->GetAttr("binary_output", &binary_output_)); } void Compute(OpKernelContext* context) override { const Tensor& indices = context->input(0); const Tensor& values = context->input(1); const Tensor& shape = context->input(2); const Tensor& weights = context->input(3); bool use_weights = weights.NumElements() > 0; OP_REQUIRES(context, TensorShapeUtils::IsMatrix(indices.shape()), errors::InvalidArgument( "Input indices must be a 2-dimensional tensor. Got: ", indices.shape().DebugString())); if (use_weights) { OP_REQUIRES( context, weights.shape() == values.shape(), errors::InvalidArgument( "Weights and values must have the same shape. Weight shape: ", weights.shape().DebugString(), "; values shape: ", values.shape().DebugString())); } OP_REQUIRES(context, shape.NumElements() != 0, errors::InvalidArgument( "The shape argument requires at least one element.")); bool is_1d = shape.NumElements() == 1; auto shape_vector = shape.flat<int64>(); int num_batches = is_1d ? 1 : shape_vector(0); int num_values = values.NumElements(); for (int b = 0; b < shape_vector.size(); b++) { OP_REQUIRES(context, shape_vector(b) >= 0, errors::InvalidArgument( "Elements in dense_shape must be >= 0. Instead got:", shape.DebugString())); } OP_REQUIRES(context, num_values == indices.shape().dim_size(0), errors::InvalidArgument( "Number of values must match first dimension of indices.", "Got ", num_values, " values, indices shape: ", indices.shape().DebugString())); const auto indices_values = indices.matrix<int64>(); const auto values_values = values.flat<T>(); const auto weight_values = weights.flat<W>(); auto per_batch_counts = BatchedMap<W>(num_batches); T max_value = 0; for (int idx = 0; idx < num_values; ++idx) { int batch = is_1d ? 0 : indices_values(idx, 0); if (batch >= num_batches) { OP_REQUIRES(context, batch < num_batches, errors::InvalidArgument( "Indices value along the first dimension must be ", "lower than the first index of the shape.", "Got ", batch, " as batch and ", num_batches, " as the first dimension of the shape.")); } const auto& value = values_values(idx); if (value >= 0 && (maxlength_ <= 0 || value < maxlength_)) { if (binary_output_) { per_batch_counts[batch][value] = 1; } else if (use_weights) { per_batch_counts[batch][value] += weight_values(idx); } else { per_batch_counts[batch][value]++; } if (value > max_value) { max_value = value; } } } int num_output_values = GetOutputSize(max_value, maxlength_, minlength_); OP_REQUIRES_OK(context, OutputSparse<W>(per_batch_counts, num_output_values, is_1d, context)); } private: int maxlength_; int minlength_; bool binary_output_; bool validate_; }; template <class T, class W> class RaggedCount : public OpKernel { public: explicit RaggedCount(OpKernelConstruction* context) : OpKernel(context) { OP_REQUIRES_OK(context, context->GetAttr("minlength", &minlength_)); OP_REQUIRES_OK(context, context->GetAttr("maxlength", &maxlength_)); OP_REQUIRES_OK(context, context->GetAttr("binary_output", &binary_output_)); } void Compute(OpKernelContext* context) override { const Tensor& splits = context->input(0); const Tensor& values = context->input(1); const Tensor& weights = context->input(2); bool use_weights = weights.NumElements() > 0; bool is_1d = false; if (use_weights) { OP_REQUIRES( context, weights.shape() == values.shape(), errors::InvalidArgument( "Weights and values must have the same shape. Weight shape: ", weights.shape().DebugString(), "; values shape: ", values.shape().DebugString())); } const auto splits_values = splits.flat<int64>(); const auto values_values = values.flat<T>(); const auto weight_values = weights.flat<W>(); int num_batches = splits.NumElements() - 1; int num_values = values.NumElements(); OP_REQUIRES( context, num_batches > 0, errors::InvalidArgument( "Must provide at least 2 elements for the splits argument")); OP_REQUIRES(context, splits_values(0) == 0, errors::InvalidArgument("Splits must start with 0, not with ", splits_values(0))); OP_REQUIRES(context, splits_values(num_batches) == num_values, errors::InvalidArgument( "Splits must end with the number of values, got ", splits_values(num_batches), " instead of ", num_values)); auto per_batch_counts = BatchedMap<W>(num_batches); T max_value = 0; int batch_idx = 0; for (int idx = 0; idx < num_values; ++idx) { while (idx >= splits_values(batch_idx)) { batch_idx++; } const auto& value = values_values(idx); if (value >= 0 && (maxlength_ <= 0 || value < maxlength_)) { if (binary_output_) { per_batch_counts[batch_idx - 1][value] = 1; } else if (use_weights) { per_batch_counts[batch_idx - 1][value] += weight_values(idx); } else { per_batch_counts[batch_idx - 1][value]++; } if (value > max_value) { max_value = value; } } } int num_output_values = GetOutputSize(max_value, maxlength_, minlength_); OP_REQUIRES_OK(context, OutputSparse<W>(per_batch_counts, num_output_values, is_1d, context)); } private: int maxlength_; int minlength_; bool binary_output_; bool validate_; }; #define REGISTER_W(W_TYPE) \ REGISTER(int32, W_TYPE) \ REGISTER(int64, W_TYPE) #define REGISTER(I_TYPE, W_TYPE) \ \ REGISTER_KERNEL_BUILDER(Name("DenseCountSparseOutput") \ .TypeConstraint<I_TYPE>("T") \ .TypeConstraint<W_TYPE>("output_type") \ .Device(DEVICE_CPU), \ DenseCount<I_TYPE, W_TYPE>) \ \ REGISTER_KERNEL_BUILDER(Name("SparseCountSparseOutput") \ .TypeConstraint<I_TYPE>("T") \ .TypeConstraint<W_TYPE>("output_type") \ .Device(DEVICE_CPU), \ SparseCount<I_TYPE, W_TYPE>) \ \ REGISTER_KERNEL_BUILDER(Name("RaggedCountSparseOutput") \ .TypeConstraint<I_TYPE>("T") \ .TypeConstraint<W_TYPE>("output_type") \ .Device(DEVICE_CPU), \ RaggedCount<I_TYPE, W_TYPE>) TF_CALL_INTEGRAL_TYPES(REGISTER_W); TF_CALL_float(REGISTER_W); TF_CALL_double(REGISTER_W); #undef REGISTER_W #undef REGISTER } // namespace tensorflow <commit_msg>Fix for a null-dereference READ in tensorflow::SparseCount.<commit_after>/* Copyright 2020 The TensorFlow 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. ==============================================================================*/ #include "absl/container/flat_hash_map.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/op_requires.h" #include "tensorflow/core/framework/register_types.h" #include "tensorflow/core/framework/tensor.h" #include "tensorflow/core/platform/errors.h" #include "tensorflow/core/platform/types.h" namespace tensorflow { template <class T> using BatchedMap = std::vector<absl::flat_hash_map<int64, T>>; namespace { // TODO(momernick): Extend this function to work with outputs of rank > 2. template <class T> Status OutputSparse(const BatchedMap<T>& per_batch_counts, int num_values, bool is_1d, OpKernelContext* context) { int total_values = 0; int num_batches = per_batch_counts.size(); for (const auto& per_batch_count : per_batch_counts) { total_values += per_batch_count.size(); } Tensor* indices; int inner_dim = is_1d ? 1 : 2; TF_RETURN_IF_ERROR(context->allocate_output( 0, TensorShape({total_values, inner_dim}), &indices)); Tensor* values; TF_RETURN_IF_ERROR( context->allocate_output(1, TensorShape({total_values}), &values)); auto output_indices = indices->matrix<int64>(); auto output_values = values->flat<T>(); int64 value_loc = 0; for (int b = 0; b < num_batches; ++b) { const auto& per_batch_count = per_batch_counts[b]; std::vector<std::pair<int, T>> pairs(per_batch_count.begin(), per_batch_count.end()); std::sort(pairs.begin(), pairs.end()); for (const auto& x : pairs) { if (is_1d) { output_indices(value_loc, 0) = x.first; } else { output_indices(value_loc, 0) = b; output_indices(value_loc, 1) = x.first; } output_values(value_loc) = x.second; ++value_loc; } } Tensor* dense_shape; if (is_1d) { TF_RETURN_IF_ERROR( context->allocate_output(2, TensorShape({1}), &dense_shape)); dense_shape->flat<int64>().data()[0] = num_values; } else { TF_RETURN_IF_ERROR( context->allocate_output(2, TensorShape({2}), &dense_shape)); dense_shape->flat<int64>().data()[0] = num_batches; dense_shape->flat<int64>().data()[1] = num_values; } return Status::OK(); } int GetOutputSize(int max_seen, int max_length, int min_length) { return max_length > 0 ? max_length : std::max((max_seen + 1), min_length); } } // namespace template <class T, class W> class DenseCount : public OpKernel { public: explicit DenseCount(OpKernelConstruction* context) : OpKernel(context) { OP_REQUIRES_OK(context, context->GetAttr("minlength", &minlength_)); OP_REQUIRES_OK(context, context->GetAttr("maxlength", &maxlength_)); OP_REQUIRES_OK(context, context->GetAttr("binary_output", &binary_output_)); } void Compute(OpKernelContext* context) override { const Tensor& data = context->input(0); const Tensor& weights = context->input(1); bool use_weights = weights.NumElements() > 0; OP_REQUIRES(context, TensorShapeUtils::IsVector(data.shape()) || TensorShapeUtils::IsMatrix(data.shape()), errors::InvalidArgument( "Input must be a 1 or 2-dimensional tensor. Got: ", data.shape().DebugString())); if (use_weights) { OP_REQUIRES( context, weights.shape() == data.shape(), errors::InvalidArgument( "Weights and data must have the same shape. Weight shape: ", weights.shape().DebugString(), "; data shape: ", data.shape().DebugString())); } bool is_1d = TensorShapeUtils::IsVector(data.shape()); int negative_valued_axis = -1; int num_batch_dimensions = (data.shape().dims() + negative_valued_axis); int num_batch_elements = 1; for (int i = 0; i < num_batch_dimensions; ++i) { OP_REQUIRES(context, data.shape().dim_size(i) != 0, errors::InvalidArgument( "Invalid input: Shapes dimension cannot be 0.")); num_batch_elements *= data.shape().dim_size(i); } int num_value_elements = data.shape().num_elements() / num_batch_elements; auto per_batch_counts = BatchedMap<W>(num_batch_elements); T max_value = 0; const auto data_values = data.flat<T>(); const auto weight_values = weights.flat<W>(); int i = 0; for (int b = 0; b < num_batch_elements; ++b) { for (int v = 0; v < num_value_elements; ++v) { const auto& value = data_values(i); if (value >= 0 && (maxlength_ <= 0 || value < maxlength_)) { if (binary_output_) { per_batch_counts[b][value] = 1; } else if (use_weights) { per_batch_counts[b][value] += weight_values(i); } else { per_batch_counts[b][value]++; } if (value > max_value) { max_value = value; } } ++i; } } int num_output_values = GetOutputSize(max_value, maxlength_, minlength_); OP_REQUIRES_OK(context, OutputSparse<W>(per_batch_counts, num_output_values, is_1d, context)); } private: int maxlength_; int minlength_; bool binary_output_; }; template <class T, class W> class SparseCount : public OpKernel { public: explicit SparseCount(OpKernelConstruction* context) : OpKernel(context) { OP_REQUIRES_OK(context, context->GetAttr("minlength", &minlength_)); OP_REQUIRES_OK(context, context->GetAttr("maxlength", &maxlength_)); OP_REQUIRES_OK(context, context->GetAttr("binary_output", &binary_output_)); } void Compute(OpKernelContext* context) override { const Tensor& indices = context->input(0); const Tensor& values = context->input(1); const Tensor& shape = context->input(2); const Tensor& weights = context->input(3); bool use_weights = weights.NumElements() > 0; OP_REQUIRES(context, TensorShapeUtils::IsMatrix(indices.shape()), errors::InvalidArgument( "Input indices must be a 2-dimensional tensor. Got: ", indices.shape().DebugString())); if (use_weights) { OP_REQUIRES( context, weights.shape() == values.shape(), errors::InvalidArgument( "Weights and values must have the same shape. Weight shape: ", weights.shape().DebugString(), "; values shape: ", values.shape().DebugString())); } OP_REQUIRES(context, shape.NumElements() != 0, errors::InvalidArgument( "The shape argument requires at least one element.")); bool is_1d = shape.NumElements() == 1; auto shape_vector = shape.flat<int64>(); int num_batches = is_1d ? 1 : shape_vector(0); int num_values = values.NumElements(); for (int b = 0; b < shape_vector.size(); b++) { OP_REQUIRES(context, shape_vector(b) >= 0, errors::InvalidArgument( "Elements in dense_shape must be >= 0. Instead got:", shape.DebugString())); } OP_REQUIRES(context, num_values == indices.shape().dim_size(0), errors::InvalidArgument( "Number of values must match first dimension of indices.", "Got ", num_values, " values, indices shape: ", indices.shape().DebugString())); const auto indices_values = indices.matrix<int64>(); const auto values_values = values.flat<T>(); const auto weight_values = weights.flat<W>(); auto per_batch_counts = BatchedMap<W>(num_batches); T max_value = 0; OP_REQUIRES(context, num_values <= indices.shape().dim_size(0), errors::InvalidArgument( "The first dimension of indices must be equal to or " "greather than number of values. ( ", indices.shape().dim_size(0), " vs. ", num_values, " )")); OP_REQUIRES(context, indices.shape().dim_size(1) > 0, errors::InvalidArgument("The second dimension of indices must " "be greater than 0. Received: ", indices.shape().dim_size(1))); for (int idx = 0; idx < num_values; ++idx) { int batch = is_1d ? 0 : indices_values(idx, 0); if (batch >= num_batches) { OP_REQUIRES(context, batch < num_batches, errors::InvalidArgument( "Indices value along the first dimension must be ", "lower than the first index of the shape.", "Got ", batch, " as batch and ", num_batches, " as the first dimension of the shape.")); } const auto& value = values_values(idx); if (value >= 0 && (maxlength_ <= 0 || value < maxlength_)) { if (binary_output_) { per_batch_counts[batch][value] = 1; } else if (use_weights) { per_batch_counts[batch][value] += weight_values(idx); } else { per_batch_counts[batch][value]++; } if (value > max_value) { max_value = value; } } } int num_output_values = GetOutputSize(max_value, maxlength_, minlength_); OP_REQUIRES_OK(context, OutputSparse<W>(per_batch_counts, num_output_values, is_1d, context)); } private: int maxlength_; int minlength_; bool binary_output_; bool validate_; }; template <class T, class W> class RaggedCount : public OpKernel { public: explicit RaggedCount(OpKernelConstruction* context) : OpKernel(context) { OP_REQUIRES_OK(context, context->GetAttr("minlength", &minlength_)); OP_REQUIRES_OK(context, context->GetAttr("maxlength", &maxlength_)); OP_REQUIRES_OK(context, context->GetAttr("binary_output", &binary_output_)); } void Compute(OpKernelContext* context) override { const Tensor& splits = context->input(0); const Tensor& values = context->input(1); const Tensor& weights = context->input(2); bool use_weights = weights.NumElements() > 0; bool is_1d = false; if (use_weights) { OP_REQUIRES( context, weights.shape() == values.shape(), errors::InvalidArgument( "Weights and values must have the same shape. Weight shape: ", weights.shape().DebugString(), "; values shape: ", values.shape().DebugString())); } const auto splits_values = splits.flat<int64>(); const auto values_values = values.flat<T>(); const auto weight_values = weights.flat<W>(); int num_batches = splits.NumElements() - 1; int num_values = values.NumElements(); OP_REQUIRES( context, num_batches > 0, errors::InvalidArgument( "Must provide at least 2 elements for the splits argument")); OP_REQUIRES(context, splits_values(0) == 0, errors::InvalidArgument("Splits must start with 0, not with ", splits_values(0))); OP_REQUIRES(context, splits_values(num_batches) == num_values, errors::InvalidArgument( "Splits must end with the number of values, got ", splits_values(num_batches), " instead of ", num_values)); auto per_batch_counts = BatchedMap<W>(num_batches); T max_value = 0; int batch_idx = 0; for (int idx = 0; idx < num_values; ++idx) { while (idx >= splits_values(batch_idx)) { batch_idx++; } const auto& value = values_values(idx); if (value >= 0 && (maxlength_ <= 0 || value < maxlength_)) { if (binary_output_) { per_batch_counts[batch_idx - 1][value] = 1; } else if (use_weights) { per_batch_counts[batch_idx - 1][value] += weight_values(idx); } else { per_batch_counts[batch_idx - 1][value]++; } if (value > max_value) { max_value = value; } } } int num_output_values = GetOutputSize(max_value, maxlength_, minlength_); OP_REQUIRES_OK(context, OutputSparse<W>(per_batch_counts, num_output_values, is_1d, context)); } private: int maxlength_; int minlength_; bool binary_output_; bool validate_; }; #define REGISTER_W(W_TYPE) \ REGISTER(int32, W_TYPE) \ REGISTER(int64, W_TYPE) #define REGISTER(I_TYPE, W_TYPE) \ \ REGISTER_KERNEL_BUILDER(Name("DenseCountSparseOutput") \ .TypeConstraint<I_TYPE>("T") \ .TypeConstraint<W_TYPE>("output_type") \ .Device(DEVICE_CPU), \ DenseCount<I_TYPE, W_TYPE>) \ \ REGISTER_KERNEL_BUILDER(Name("SparseCountSparseOutput") \ .TypeConstraint<I_TYPE>("T") \ .TypeConstraint<W_TYPE>("output_type") \ .Device(DEVICE_CPU), \ SparseCount<I_TYPE, W_TYPE>) \ \ REGISTER_KERNEL_BUILDER(Name("RaggedCountSparseOutput") \ .TypeConstraint<I_TYPE>("T") \ .TypeConstraint<W_TYPE>("output_type") \ .Device(DEVICE_CPU), \ RaggedCount<I_TYPE, W_TYPE>) TF_CALL_INTEGRAL_TYPES(REGISTER_W); TF_CALL_float(REGISTER_W); TF_CALL_double(REGISTER_W); #undef REGISTER_W #undef REGISTER } // namespace tensorflow <|endoftext|>
<commit_before>#include <phypp.hpp> int phypp_main(int argc, char* argv[]) { if (argc < 2) { print("usage: cube2slit <cube.fits> [out=... slit_width=... verbose]"); return 0; } double slit_width = 0.7; // [arcsec] bool verbose = false; std::string out_file; read_args(argc-1, argv+1, arg_list(slit_width, verbose, name(out_file, "out"))); std::string infile = argv[1]; if (out_file.empty()) { out_file = file::remove_extension(infile)+"_slit.fits"; } fits::input_image fimg(infile); fimg.reach_hdu(1); // Read wavelength/frequency axis WCS uint_t nlam = 0; std::string cunit; double cdelt = 1, crpix = 1, crval = 1; vec1s missing; fimg.read_keyword("CUNIT3", cunit); // optional if (!fimg.read_keyword("NAXIS3", nlam)) missing.push_back("NAXIS3"); if (!fimg.read_keyword("CDELT3", cdelt)) missing.push_back("CDELT3"); if (!fimg.read_keyword("CRPIX3", crpix)) missing.push_back("CRPIX3"); if (!fimg.read_keyword("CRVAL3", crval)) missing.push_back("CRVAL3"); if (!missing.empty()) { error("could not read WCS information for wavelength axis (axis 3)"); note("missing keyword", missing.size() > 1 ? "s " : " ", collapse(missing, ", ")); return 1; } bool frequency = false; std::string ctype; if (fimg.read_keyword("CTYPE3", ctype)) { if (ctype == "FREQ") { // Cube in frequency units, assuming in Hz frequency = true; } else if (ctype == "WAVE") { // Cube in wavelength units, assuming in micron frequency = false; } } if (verbose) { double l0 = crval + cdelt*(1 - crpix); double l1 = crval + cdelt*(nlam - crpix); if (l0 > l1) std::swap(l0, l1); std::string unit = cunit.empty() ? "[unknown unit?]" : cunit; note("cube is covering ", l0, " to ", l1, " ", unit); } // Find pixel scale double aspix = 0; if (!fimg.read_keyword("CDELT1", aspix)) { if (!fimg.read_keyword("CD1_1", aspix)) { error("could not read WCS information for sky axis (axis 1)"); note("missing keyword CDELT1 or CD1_1"); return 1; } } aspix = abs(aspix*3600); if (verbose) note("cube has a pixel scale of ", aspix, "\""); uint_t navg = ceil(slit_width/aspix)/2; if (verbose) note("using a slit of width ", 2*navg + 1, " pixels"); fits::output_image foimg(out_file); foimg.write_empty(); vec3d flx3d, err3d; fimg.reach_hdu(1); fimg.read(flx3d); fimg.reach_hdu(2); fimg.read(err3d); uint_t nslit = flx3d.dims[1]; if (2*navg+1 > flx3d.dims[2]) { error("slit would be larger than data cube (", 2*navg+1, " pixels)"); note("please choose a smaller value for 'slit_width' (currently ", slit_width, "\")"); return 1; } uint_t i0 = flx3d.dims[2]/2 - navg; uint_t i1 = flx3d.dims[2]/2 + navg; vec2d flx2d(nslit, flx3d.dims[0]); vec2d err2d(nslit, flx3d.dims[0]); for (uint_t l : range(flx3d.dims[0])) for (uint_t p : range(flx3d.dims[1])) { vec1d lflx = flx3d(l,p,i0-_-i1); vec1d lerr = err3d(l,p,i0-_-i1); vec1u idl = where(is_finite(lflx) && is_finite(lerr) && lerr > 0); auto pp = optimal_mean(lflx[idl], lerr[idl]); flx2d(p,l) = pp.first; err2d(p,l) = pp.second; } foimg.reach_hdu(1); foimg.write(flx2d); auto write_wcs = [&]() { if (!cunit.empty()) foimg.write_keyword("CUNIT1", cunit); if (!ctype.empty()) foimg.write_keyword("CTYPE1", ctype); foimg.write_keyword("CDELT1", cdelt); foimg.write_keyword("CRPIX1", crpix); foimg.write_keyword("CRVAL1", crval); foimg.write_keyword("CTYPE2", "SLIT"); foimg.write_keyword("CUNIT2", "arcsec"); foimg.write_keyword("CDELT2", aspix); foimg.write_keyword("CRPIX2", flx2d.dims[0]/2 + 1); foimg.write_keyword("CRVAL2", 0.0); }; write_wcs(); foimg.reach_hdu(2); foimg.write(err2d); return 0; } <commit_msg>cube2slit can now create 2D spectrum from offset position<commit_after>#include <phypp.hpp> int phypp_main(int argc, char* argv[]) { if (argc < 2) { print("usage: cube2slit <cube.fits> [out=... slit_width=... verbose]"); return 0; } double slit_width = 0.7; // [arcsec] bool verbose = false; uint_t hdu = 1; uint_t error_hdu = 2; double center_x = dnan; double center_y = dnan; std::string out_file; read_args(argc-1, argv+1, arg_list( slit_width, verbose, name(out_file, "out"), hdu, error_hdu, center_x, center_y )); std::string infile = argv[1]; if (out_file.empty()) { out_file = file::remove_extension(file::get_basename(infile))+"_slit.fits"; } fits::input_image fimg(infile); fimg.reach_hdu(hdu); // Read wavelength/frequency axis WCS uint_t nlam = 0; std::string cunit; double cdelt = 1, crpix = 1, crval = 1; vec1s missing; fimg.read_keyword("CUNIT3", cunit); // optional if (!fimg.read_keyword("NAXIS3", nlam)) missing.push_back("NAXIS3"); if (!fimg.read_keyword("CDELT3", cdelt)) { if (!fimg.read_keyword("CD3_3", cdelt)) { missing.push_back("CDELT3 or CD3_3"); } } if (!fimg.read_keyword("CRPIX3", crpix)) missing.push_back("CRPIX3"); if (!fimg.read_keyword("CRVAL3", crval)) missing.push_back("CRVAL3"); if (!missing.empty()) { error("could not read WCS information for wavelength axis (axis 3)"); note("missing keyword", missing.size() > 1 ? "s " : " ", collapse(missing, ", ")); return 1; } bool frequency = false; std::string ctype; if (fimg.read_keyword("CTYPE3", ctype)) { if (ctype == "FREQ") { // Cube in frequency units, assuming in Hz frequency = true; } else if (ctype == "WAVE") { // Cube in wavelength units, assuming in micron frequency = false; } } if (verbose) { double l0 = crval + cdelt*(1 - crpix); double l1 = crval + cdelt*(nlam - crpix); if (l0 > l1) std::swap(l0, l1); std::string unit = cunit.empty() ? "[unknown unit?]" : cunit; note("cube is covering ", l0, " to ", l1, " ", unit); } // Find pixel scale double aspix = 0; if (!fimg.read_keyword("CDELT1", aspix)) { if (!fimg.read_keyword("CD1_1", aspix)) { error("could not read WCS information for sky axis (axis 1)"); note("missing keyword CDELT1 or CD1_1"); return 1; } } aspix = abs(aspix*3600); if (verbose) note("cube has a pixel scale of ", aspix, "\""); uint_t navg = ceil(slit_width/aspix)/2; if (verbose) note("using a slit of width ", 2*navg + 1, " pixels"); fits::output_image foimg(out_file); foimg.write_empty(); vec3d flx3d, err3d; fimg.reach_hdu(hdu); fimg.read(flx3d); fimg.reach_hdu(error_hdu); fimg.read(err3d); uint_t nslit = flx3d.dims[1]; if (2*navg+1 > flx3d.dims[2]) { error("slit would be larger than data cube (", flx3d.dims[2], " pixels, or ", flx3d.dims[2]*aspix, "\")"); note("please choose a smaller value for 'slit_width'"); return 1; } uint_t i0, i1; if (!is_finite(center_x)) { i0 = flx3d.dims[2]/2 - navg; i1 = flx3d.dims[2]/2 + navg; } else { double cp = round(center_x); if (cp-navg < 0 || cp+navg > flx3d.dims[2]-1) { error("slit position reaches the edge of the data cube"); return 1; } i0 = uint_t(cp) - navg; i1 = uint_t(cp) + navg; } vec2d flx2d(nslit, flx3d.dims[0]); vec2d err2d(nslit, flx3d.dims[0]); for (uint_t l : range(flx3d.dims[0])) for (uint_t p : range(flx3d.dims[1])) { vec1d lflx = flx3d(l,p,i0-_-i1); vec1d lerr = err3d(l,p,i0-_-i1); vec1u idl = where(is_finite(lflx) && is_finite(lerr) && lerr > 0); auto pp = optimal_mean(lflx[idl], lerr[idl]); flx2d(p,l) = pp.first; err2d(p,l) = pp.second; } foimg.reach_hdu(1); foimg.write(flx2d); auto write_wcs = [&]() { if (!cunit.empty()) foimg.write_keyword("CUNIT1", cunit); if (!ctype.empty()) foimg.write_keyword("CTYPE1", ctype); foimg.write_keyword("CDELT1", cdelt); foimg.write_keyword("CRPIX1", crpix); foimg.write_keyword("CRVAL1", crval); foimg.write_keyword("CTYPE2", "SLIT"); foimg.write_keyword("CUNIT2", "arcsec"); foimg.write_keyword("CDELT2", aspix); foimg.write_keyword("CRPIX2", flx2d.dims[0]/2 + 1); foimg.write_keyword("CRVAL2", 0.0); }; write_wcs(); foimg.reach_hdu(2); foimg.write(err2d); return 0; } <|endoftext|>
<commit_before>#include "execute_request_message.h" using namespace std; // See interface (header file). ExecuteSuccessMessage::ExecuteSuccessMessage(string name, int *argTypes, void **args) : Message(), name(name), argTypes(argTypes), args(args) {} // Constructor // See interface (header file). ExecuteSuccessMessage::~ExecuteSuccessMessage() {} // Destructor // See interface (header file). string ExecuteSuccessMessage::getName() const { return name; } // See interface (header file). int *ExecuteSuccessMessage::getArgTypes() const { return argTypes; } // See interface (header file). void **ExecuteSuccessMessage::getArgs() const { return args; } // See interface (header file). int ExecuteSuccessMessage::send(int dataTransferSocket, unsigned int length) { return 1; } // See interface (header file). int ExecuteSuccessMessage::receive(int dataTransferSocket, Message *parsedMessage, unsigned int length) { return 1; } <commit_msg>More work<commit_after>#include "execute_success_message.h" using namespace std; // See interface (header file). ExecuteSuccessMessage::ExecuteSuccessMessage(string name, int *argTypes, void **args) : Message(), name(name), argTypes(argTypes), args(args) {} // Constructor // See interface (header file). ExecuteSuccessMessage::~ExecuteSuccessMessage() {} // Destructor // See interface (header file). string ExecuteSuccessMessage::getName() const { return name; } // See interface (header file). int *ExecuteSuccessMessage::getArgTypes() const { return argTypes; } // See interface (header file). void **ExecuteSuccessMessage::getArgs() const { return args; } // See interface (header file). int ExecuteSuccessMessage::send(int dataTransferSocket, unsigned int length) { return 1; } // See interface (header file). int ExecuteSuccessMessage::receive(int dataTransferSocket, Message *parsedMessage, unsigned int length) { return 1; } <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999 The Apache Software Foundation. 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. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ #if !defined(FUNCTIONLOCALNAME_HEADER_GUARD_1357924680) #define FUNCTIONLOCALNAME_HEADER_GUARD_1357924680 // Base header file. Must be first. #include <XPath/XPathDefinitions.hpp> #include <vector> #include <PlatformSupport/DOMStringHelper.hpp> // Base class header file... #include <XPath/Function.hpp> #include <XPath/NodeRefListBase.hpp> #include <XPath/XObject.hpp> #include <XPath/XObjectFactory.hpp> #include <XPath/XPathExecutionContext.hpp> /** * XPath implementation of "local-name" function. */ // // These are all inline, even though // there are virtual functions, because we expect that they will only be // needed by the XPath class. class XALAN_XPATH_EXPORT FunctionLocalName : public Function { public: // These methods are inherited from Function ... virtual XObject* execute( XPathExecutionContext& executionContext, XalanNode* context, int /* opPos */, const XObjectArgVectorType& args) { if(args.size() != 1) { executionContext.error("The local-name() function takes one argument!", context); } assert(args[0] != 0); const NodeRefListBase& theNodeList = args[0]->nodeset(); XalanDOMString theData; if (theNodeList.getLength() > 0) { theData = executionContext.getLocalNameOfNode(*theNodeList.item(0)); } return executionContext.getXObjectFactory().createString(theData); } #if defined(XALAN_NO_COVARIANT_RETURN_TYPE) virtual Function* #else virtual FunctionLocalName* #endif clone() const { return new FunctionLocalName(*this); } private: // Not implemented... FunctionLocalName& operator=(const FunctionLocalName&); bool operator==(const FunctionLocalName&) const; }; #endif // FUNCTIONLOCALNAME_HEADER_GUARD_1357924680 <commit_msg>Allow no arguments.<commit_after>/* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999 The Apache Software Foundation. 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. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ #if !defined(FUNCTIONLOCALNAME_HEADER_GUARD_1357924680) #define FUNCTIONLOCALNAME_HEADER_GUARD_1357924680 // Base header file. Must be first. #include <XPath/XPathDefinitions.hpp> #include <vector> #include <PlatformSupport/DOMStringHelper.hpp> // Base class header file... #include <XPath/Function.hpp> #include <XPath/NodeRefListBase.hpp> #include <XPath/XObject.hpp> #include <XPath/XObjectFactory.hpp> #include <XPath/XPathExecutionContext.hpp> /** * XPath implementation of "local-name" function. */ // // These are all inline, even though // there are virtual functions, because we expect that they will only be // needed by the XPath class. class XALAN_XPATH_EXPORT FunctionLocalName : public Function { public: // These methods are inherited from Function ... virtual XObject* execute( XPathExecutionContext& executionContext, XalanNode* context, int /* opPos */, const XObjectArgVectorType& args) { const XObjectArgVectorType::size_type theSize = args.size(); if(theSize > 1) { executionContext.error("The local-name() function takes zero or one arguments!", context); } XalanDOMString theData; if (theSize == 0) { assert(context != 0); theData = executionContext.getLocalNameOfNode(*context); } else { assert(args[0] != 0); const NodeRefListBase& theNodeList = args[0]->nodeset(); if (theNodeList.getLength() > 0) { theData = executionContext.getLocalNameOfNode(*theNodeList.item(0)); } } return executionContext.getXObjectFactory().createString(theData); } #if defined(XALAN_NO_COVARIANT_RETURN_TYPE) virtual Function* #else virtual FunctionLocalName* #endif clone() const { return new FunctionLocalName(*this); } private: // Not implemented... FunctionLocalName& operator=(const FunctionLocalName&); bool operator==(const FunctionLocalName&) const; }; #endif // FUNCTIONLOCALNAME_HEADER_GUARD_1357924680 <|endoftext|>
<commit_before>#include <QCoreApplication> #include <QtWidgets/QAction> #include "interpreter.h" #include "details/autoconfigurer.h" #include "details/robotImplementations/unrealRobotModelImplementation.h" #include "details/robotCommunication/bluetoothRobotCommunicationThread.h" #include "details/robotCommunication/usbRobotCommunicationThread.h" #include "details/tracer.h" #include "details/debugHelper.h" using namespace qReal; using namespace interpreters::robots; using namespace interpreters::robots::details; const Id startingElementType = Id("RobotsMetamodel", "RobotsDiagram", "InitialNode"); const Id startingElementType1 = Id("RobotsMetamodel", "RobotsDiagram", "InitialBlock"); Interpreter::Interpreter() : mGraphicalModelApi(NULL) , mLogicalModelApi(NULL) , mInterpretersInterface(NULL) , mState(idle) , mRobotModel(new RobotModel()) , mBlocksTable(NULL) , mRobotCommunication(new RobotCommunicator(SettingsManager::value("valueOfCommunication").toString())) , mImplementationType(robotModelType::null) , mWatchListWindow(NULL) , mActionConnectToRobot(NULL) { Tracer::enableAll(); Tracer::setTarget(tracer::logFile); mParser = NULL; mBlocksTable = NULL; mTimer = new QTimer(); mD2RobotModel = new d2Model::D2RobotModel(); mD2ModelWidget = mD2RobotModel->createModelWidget(); connect(mRobotModel, SIGNAL(disconnected()), this, SLOT(disconnectSlot())); connect(mRobotModel, SIGNAL(sensorsConfigured()), this, SLOT(sensorsConfiguredSlot())); connect(mRobotModel, SIGNAL(connected(bool)), this, SLOT(connectedSlot(bool))); connect(mD2ModelWidget, SIGNAL(d2WasClosed()), this, SLOT(stopRobot())); connect(mRobotCommunication, SIGNAL(errorOccured(QString)), this, SLOT(reportError(QString))); } void Interpreter::init(GraphicalModelAssistInterface const &graphicalModelApi , LogicalModelAssistInterface const &logicalModelApi , qReal::gui::MainWindowInterpretersInterface &interpretersInterface) { mGraphicalModelApi = &graphicalModelApi; mLogicalModelApi = &logicalModelApi; mInterpretersInterface = &interpretersInterface; mParser = new RobotsBlockParser(mInterpretersInterface->errorReporter()); mBlocksTable = new BlocksTable(graphicalModelApi, logicalModelApi, mRobotModel, mInterpretersInterface->errorReporter(), mParser); robotModelType::robotModelTypeEnum const modelType = static_cast<robotModelType::robotModelTypeEnum>(SettingsManager::value("robotModel").toInt()); Tracer::debug(tracer::initialization, "Interpreter::init", "Going to set robot implementation, model type is " + DebugHelper::toString(modelType)); setRobotImplementation(modelType); mWatchListWindow = new utils::WatchListWindow(mParser, mInterpretersInterface->windowWidget()); } Interpreter::~Interpreter() { foreach (Thread * const thread, mThreads) { delete thread; } delete mBlocksTable; } void Interpreter::interpret() { Tracer::debug(tracer::initialization, "Interpreter::interpret", "Preparing for interpretation"); mInterpretersInterface->errorReporter()->clear(); Id const &currentDiagramId = mInterpretersInterface->activeDiagram(); if (!mConnected) { mInterpretersInterface->errorReporter()->addInformation(tr("No connection to robot")); return; } if (mState != idle) { mInterpretersInterface->errorReporter()->addInformation(tr("Interpreter is already running")); return; } mBlocksTable->clear(); mState = waitingForSensorsConfiguredToLaunch; mBlocksTable->setIdleForBlocks(); Id const startingElement = findStartingElement(currentDiagramId); if (startingElement == Id()) { mInterpretersInterface->errorReporter()->addError(tr("No entry point found, please add Initial Node to a diagram")); mState = idle; return; } Autoconfigurer configurer(*mGraphicalModelApi, mBlocksTable, mInterpretersInterface->errorReporter(), mRobotModel); if (!configurer.configure(currentDiagramId)) { return; } } void Interpreter::stopRobot() { mTimer->stop(); mRobotModel->stopRobot(); mState = idle; foreach (Thread *thread, mThreads) { delete thread; mThreads.removeAll(thread); } mBlocksTable->setFailure(); } void Interpreter::showWatchList() { mWatchListWindow->show(); } void Interpreter::closeWatchList() { if (mWatchListWindow) { mWatchListWindow->setVisible(false); } } void Interpreter::closeD2ModelWidget() { if (mD2ModelWidget) { mD2ModelWidget->close(); } } void Interpreter::showD2ModelWidget(bool isVisible) { mD2ModelWidget->init(isVisible); if (isVisible) { mD2ModelWidget->activateWindow(); mD2ModelWidget->showNormal(); } } void Interpreter::setD2ModelWidgetActions(QAction *runAction, QAction *stopAction) { mD2ModelWidget->setD2ModelWidgetActions(runAction, stopAction); } void Interpreter::enableD2ModelWidgetRunStopButtons() { mD2ModelWidget->enableRunStopButtons(); } void Interpreter::disableD2ModelWidgetRunStopButtons() { mD2ModelWidget->disableRunStopButtons(); } void Interpreter::setRobotImplementation(robotModelType::robotModelTypeEnum implementationType) { mConnected = false; robotImplementations::AbstractRobotModelImplementation *robotImpl = robotImplementations::AbstractRobotModelImplementation::robotModel(implementationType, mRobotCommunication, mD2RobotModel); setRobotImplementation(robotImpl); mImplementationType = implementationType; if (mImplementationType != robotModelType::real) { mRobotModel->init(); } } void Interpreter::connectedSlot(bool success) { if (success) { if (mRobotModel->needsConnection()) { mInterpretersInterface->errorReporter()->addInformation(tr("Connected successfully")); } } else { Tracer::debug(tracer::initialization, "Interpreter::connectedSlot", "Robot connection status: " + QString::number(success)); mInterpretersInterface->errorReporter()->addError(tr("Can't connect to a robot.")); } mConnected = success; mActionConnectToRobot->setChecked(success); } void Interpreter::sensorsConfiguredSlot() { Tracer::debug(tracer::initialization, "Interpreter::sensorsConfiguredSlot", "Sensors are configured"); mConnected = true; mActionConnectToRobot->setChecked(mConnected); resetVariables(); mRobotModel->nextBlockAfterInitial(mConnected); if (mState == waitingForSensorsConfiguredToLaunch) { mState = interpreting; runTimer(); Tracer::debug(tracer::initialization, "Interpreter::sensorsConfiguredSlot", "Starting interpretation"); mRobotModel->startInterpretation(); Id const &currentDiagramId = mInterpretersInterface->activeDiagram(); Id const startingElement = findStartingElement(currentDiagramId); Thread * const initialThread = new Thread(*mInterpretersInterface, *mBlocksTable, startingElement); addThread(initialThread); } } Id const Interpreter::findStartingElement(Id const &diagram) const { IdList const children = mGraphicalModelApi->graphicalRepoApi().children(diagram); foreach (Id const child, children) { if (child.type() == startingElementType || child.type() == startingElementType1) { return child; } } return Id(); } void Interpreter::threadStopped() { Thread *thread = static_cast<Thread *>(sender()); mThreads.removeAll(thread); delete thread; if (mThreads.isEmpty()) { stopRobot(); } } void Interpreter::newThread(details::blocks::Block * const startBlock) { Thread * const thread = new Thread(*mInterpretersInterface, *mBlocksTable, startBlock->id()); addThread(thread); } void Interpreter::configureSensors(sensorType::SensorTypeEnum const &port1 , sensorType::SensorTypeEnum const &port2 , sensorType::SensorTypeEnum const &port3 , sensorType::SensorTypeEnum const &port4) { if (mConnected) { mRobotModel->configureSensors(port1, port2, port3, port4); } } void Interpreter::addThread(details::Thread * const thread) { mThreads.append(thread); connect(thread, SIGNAL(stopped()), this, SLOT(threadStopped())); connect(thread, SIGNAL(newThread(details::blocks::Block*const)), this, SLOT(newThread(details::blocks::Block*const))); QCoreApplication::processEvents(); thread->interpret(); } interpreters::robots::details::RobotModel *Interpreter::robotModel() { return mRobotModel; } void Interpreter::setRobotModel(details::RobotModel * const robotModel) { mRobotModel = robotModel; } void Interpreter::setRobotImplementation(details::robotImplementations::AbstractRobotModelImplementation *robotImpl) { mRobotModel->setRobotImplementation(robotImpl); if (robotImpl) { connect(mRobotModel, SIGNAL(connected(bool)), this, SLOT(runTimer())); } } void Interpreter::runTimer() { if (!mTimer->isActive()) { mTimer->start(10); connect(mTimer, SIGNAL(timeout()), this, SLOT(readSensorValues()), Qt::UniqueConnection); } if (mRobotModel->sensor(inputPort::port1)) { connect(mRobotModel->sensor(inputPort::port1)->sensorImpl(), SIGNAL(response(int)), this, SLOT(responseSlot1(int))); connect(mRobotModel->sensor(inputPort::port1)->sensorImpl(), SIGNAL(failure()), this, SLOT(slotFailure())); } if (mRobotModel->sensor(inputPort::port2)) { connect(mRobotModel->sensor(inputPort::port2)->sensorImpl(), SIGNAL(response(int)), this, SLOT(responseSlot2(int))); connect(mRobotModel->sensor(inputPort::port2)->sensorImpl(), SIGNAL(failure()), this, SLOT(slotFailure())); } if (mRobotModel->sensor(inputPort::port3)) { connect(mRobotModel->sensor(inputPort::port3)->sensorImpl(), SIGNAL(response(int)), this, SLOT(responseSlot3(int))); connect(mRobotModel->sensor(inputPort::port3)->sensorImpl(), SIGNAL(failure()), this, SLOT(slotFailure())); } if (mRobotModel->sensor(inputPort::port4)) { connect(mRobotModel->sensor(inputPort::port4)->sensorImpl(), SIGNAL(response(int)), this, SLOT(responseSlot4(int))); connect(mRobotModel->sensor(inputPort::port4)->sensorImpl(), SIGNAL(failure()), this, SLOT(slotFailure())); } } void Interpreter::readSensorValues() { if (mState == idle) { return; } if (mRobotModel->sensor(inputPort::port1)) { mRobotModel->sensor(inputPort::port1)->read(); } if (mRobotModel->sensor(inputPort::port2)) { mRobotModel->sensor(inputPort::port2)->read(); } if (mRobotModel->sensor(inputPort::port3)) { mRobotModel->sensor(inputPort::port3)->read(); } if (mRobotModel->sensor(inputPort::port4)) { mRobotModel->sensor(inputPort::port4)->read(); } } void Interpreter::slotFailure() { Tracer::debug(tracer::autoupdatedSensorValues, "Interpreter::slotFailure", ""); } void Interpreter::responseSlot1(int sensorValue) { updateSensorValues("Sensor1", sensorValue); } void Interpreter::responseSlot2(int sensorValue) { updateSensorValues("Sensor2", sensorValue); } void Interpreter::responseSlot3(int sensorValue) { updateSensorValues("Sensor3", sensorValue); } void Interpreter::responseSlot4(int sensorValue) { updateSensorValues("Sensor4", sensorValue); } void Interpreter::updateSensorValues(QString const &sensorVariableName, int sensorValue) { (*(mParser->getVariables()))[sensorVariableName] = utils::Number(sensorValue, utils::Number::intType); Tracer::debug(tracer::autoupdatedSensorValues, "Interpreter::updateSensorValues", sensorVariableName + QString::number(sensorValue)); } void Interpreter::resetVariables() { int const resetValue = 0; responseSlot1(resetValue); responseSlot2(resetValue); responseSlot3(resetValue); responseSlot4(resetValue); } void Interpreter::connectToRobot() { if (mConnected) { mRobotModel->stopRobot(); mRobotModel->disconnectFromRobot(); } else { mRobotModel->init(); configureSensors(static_cast<sensorType::SensorTypeEnum>(SettingsManager::instance()->value("port1SensorType").toInt()) , static_cast<sensorType::SensorTypeEnum>(SettingsManager::instance()->value("port2SensorType").toInt()) , static_cast<sensorType::SensorTypeEnum>(SettingsManager::instance()->value("port3SensorType").toInt()) , static_cast<sensorType::SensorTypeEnum>(SettingsManager::instance()->value("port4SensorType").toInt())); } mActionConnectToRobot->setChecked(mConnected); } void Interpreter::disconnectSlot() { mActionConnectToRobot->setChecked(false); mConnected = false; } void Interpreter::setRobotModelType(robotModelType::robotModelTypeEnum robotModelType) { setRobotImplementation(robotModelType); } void Interpreter::setCommunicator(QString const &valueOfCommunication, QString const &portName) { if (valueOfCommunication == mLastCommunicationValue) { return; } RobotCommunicationThreadInterface *communicator = NULL; if (valueOfCommunication == "bluetooth") { communicator = new BluetoothRobotCommunicationThread(); } else { communicator = new UsbRobotCommunicationThread(); } mLastCommunicationValue = valueOfCommunication; mRobotCommunication->setRobotCommunicationThreadObject(communicator); mRobotCommunication->setPortName(portName); connectToRobot(); } void Interpreter::setConnectRobotAction(QAction *actionConnect) { mActionConnectToRobot = actionConnect; } void Interpreter::reportError(QString const &message) { mInterpretersInterface->errorReporter()->addError(message); } utils::WatchListWindow *Interpreter::watchWindow() const { return mWatchListWindow; } void Interpreter::connectSensorConfigurer(details::SensorsConfigurationWidget *configurer) const { connect(configurer, SIGNAL(saved()), mD2ModelWidget, SLOT(syncronizeSensors())); } <commit_msg>Fixed fault when disconnecting during interpretation<commit_after>#include <QCoreApplication> #include <QtWidgets/QAction> #include "interpreter.h" #include "details/autoconfigurer.h" #include "details/robotImplementations/unrealRobotModelImplementation.h" #include "details/robotCommunication/bluetoothRobotCommunicationThread.h" #include "details/robotCommunication/usbRobotCommunicationThread.h" #include "details/tracer.h" #include "details/debugHelper.h" using namespace qReal; using namespace interpreters::robots; using namespace interpreters::robots::details; const Id startingElementType = Id("RobotsMetamodel", "RobotsDiagram", "InitialNode"); const Id startingElementType1 = Id("RobotsMetamodel", "RobotsDiagram", "InitialBlock"); Interpreter::Interpreter() : mGraphicalModelApi(NULL) , mLogicalModelApi(NULL) , mInterpretersInterface(NULL) , mState(idle) , mRobotModel(new RobotModel()) , mBlocksTable(NULL) , mRobotCommunication(new RobotCommunicator(SettingsManager::value("valueOfCommunication").toString())) , mImplementationType(robotModelType::null) , mWatchListWindow(NULL) , mActionConnectToRobot(NULL) { Tracer::enableAll(); Tracer::setTarget(tracer::logFile); mParser = NULL; mBlocksTable = NULL; mTimer = new QTimer(); mD2RobotModel = new d2Model::D2RobotModel(); mD2ModelWidget = mD2RobotModel->createModelWidget(); connect(mRobotModel, SIGNAL(disconnected()), this, SLOT(disconnectSlot())); connect(mRobotModel, SIGNAL(sensorsConfigured()), this, SLOT(sensorsConfiguredSlot())); connect(mRobotModel, SIGNAL(connected(bool)), this, SLOT(connectedSlot(bool))); connect(mD2ModelWidget, SIGNAL(d2WasClosed()), this, SLOT(stopRobot())); connect(mRobotCommunication, SIGNAL(errorOccured(QString)), this, SLOT(reportError(QString))); } void Interpreter::init(GraphicalModelAssistInterface const &graphicalModelApi , LogicalModelAssistInterface const &logicalModelApi , qReal::gui::MainWindowInterpretersInterface &interpretersInterface) { mGraphicalModelApi = &graphicalModelApi; mLogicalModelApi = &logicalModelApi; mInterpretersInterface = &interpretersInterface; mParser = new RobotsBlockParser(mInterpretersInterface->errorReporter()); mBlocksTable = new BlocksTable(graphicalModelApi, logicalModelApi, mRobotModel, mInterpretersInterface->errorReporter(), mParser); robotModelType::robotModelTypeEnum const modelType = static_cast<robotModelType::robotModelTypeEnum>(SettingsManager::value("robotModel").toInt()); Tracer::debug(tracer::initialization, "Interpreter::init", "Going to set robot implementation, model type is " + DebugHelper::toString(modelType)); setRobotImplementation(modelType); mWatchListWindow = new utils::WatchListWindow(mParser, mInterpretersInterface->windowWidget()); } Interpreter::~Interpreter() { foreach (Thread * const thread, mThreads) { delete thread; } delete mBlocksTable; } void Interpreter::interpret() { Tracer::debug(tracer::initialization, "Interpreter::interpret", "Preparing for interpretation"); mInterpretersInterface->errorReporter()->clear(); Id const &currentDiagramId = mInterpretersInterface->activeDiagram(); if (!mConnected) { mInterpretersInterface->errorReporter()->addInformation(tr("No connection to robot")); return; } if (mState != idle) { mInterpretersInterface->errorReporter()->addInformation(tr("Interpreter is already running")); return; } mBlocksTable->clear(); mState = waitingForSensorsConfiguredToLaunch; mBlocksTable->setIdleForBlocks(); Id const startingElement = findStartingElement(currentDiagramId); if (startingElement == Id()) { mInterpretersInterface->errorReporter()->addError(tr("No entry point found, please add Initial Node to a diagram")); mState = idle; return; } Autoconfigurer configurer(*mGraphicalModelApi, mBlocksTable, mInterpretersInterface->errorReporter(), mRobotModel); if (!configurer.configure(currentDiagramId)) { return; } } void Interpreter::stopRobot() { mTimer->stop(); mRobotModel->stopRobot(); mState = idle; foreach (Thread *thread, mThreads) { delete thread; mThreads.removeAll(thread); } mBlocksTable->setFailure(); } void Interpreter::showWatchList() { mWatchListWindow->show(); } void Interpreter::closeWatchList() { if (mWatchListWindow) { mWatchListWindow->setVisible(false); } } void Interpreter::closeD2ModelWidget() { if (mD2ModelWidget) { mD2ModelWidget->close(); } } void Interpreter::showD2ModelWidget(bool isVisible) { mD2ModelWidget->init(isVisible); if (isVisible) { mD2ModelWidget->activateWindow(); mD2ModelWidget->showNormal(); } } void Interpreter::setD2ModelWidgetActions(QAction *runAction, QAction *stopAction) { mD2ModelWidget->setD2ModelWidgetActions(runAction, stopAction); } void Interpreter::enableD2ModelWidgetRunStopButtons() { mD2ModelWidget->enableRunStopButtons(); } void Interpreter::disableD2ModelWidgetRunStopButtons() { mD2ModelWidget->disableRunStopButtons(); } void Interpreter::setRobotImplementation(robotModelType::robotModelTypeEnum implementationType) { mConnected = false; robotImplementations::AbstractRobotModelImplementation *robotImpl = robotImplementations::AbstractRobotModelImplementation::robotModel(implementationType, mRobotCommunication, mD2RobotModel); setRobotImplementation(robotImpl); mImplementationType = implementationType; if (mImplementationType != robotModelType::real) { mRobotModel->init(); } } void Interpreter::connectedSlot(bool success) { if (success) { if (mRobotModel->needsConnection()) { mInterpretersInterface->errorReporter()->addInformation(tr("Connected successfully")); } } else { Tracer::debug(tracer::initialization, "Interpreter::connectedSlot", "Robot connection status: " + QString::number(success)); mInterpretersInterface->errorReporter()->addError(tr("Can't connect to a robot.")); } mConnected = success; mActionConnectToRobot->setChecked(success); } void Interpreter::sensorsConfiguredSlot() { Tracer::debug(tracer::initialization, "Interpreter::sensorsConfiguredSlot", "Sensors are configured"); mConnected = true; mActionConnectToRobot->setChecked(mConnected); resetVariables(); mRobotModel->nextBlockAfterInitial(mConnected); if (mState == waitingForSensorsConfiguredToLaunch) { mState = interpreting; runTimer(); Tracer::debug(tracer::initialization, "Interpreter::sensorsConfiguredSlot", "Starting interpretation"); mRobotModel->startInterpretation(); Id const &currentDiagramId = mInterpretersInterface->activeDiagram(); Id const startingElement = findStartingElement(currentDiagramId); Thread * const initialThread = new Thread(*mInterpretersInterface, *mBlocksTable, startingElement); addThread(initialThread); } } Id const Interpreter::findStartingElement(Id const &diagram) const { IdList const children = mGraphicalModelApi->graphicalRepoApi().children(diagram); foreach (Id const child, children) { if (child.type() == startingElementType || child.type() == startingElementType1) { return child; } } return Id(); } void Interpreter::threadStopped() { Thread *thread = static_cast<Thread *>(sender()); mThreads.removeAll(thread); delete thread; if (mThreads.isEmpty()) { stopRobot(); } } void Interpreter::newThread(details::blocks::Block * const startBlock) { Thread * const thread = new Thread(*mInterpretersInterface, *mBlocksTable, startBlock->id()); addThread(thread); } void Interpreter::configureSensors(sensorType::SensorTypeEnum const &port1 , sensorType::SensorTypeEnum const &port2 , sensorType::SensorTypeEnum const &port3 , sensorType::SensorTypeEnum const &port4) { if (mConnected) { mRobotModel->configureSensors(port1, port2, port3, port4); } } void Interpreter::addThread(details::Thread * const thread) { mThreads.append(thread); connect(thread, SIGNAL(stopped()), this, SLOT(threadStopped())); connect(thread, SIGNAL(newThread(details::blocks::Block*const)), this, SLOT(newThread(details::blocks::Block*const))); QCoreApplication::processEvents(); thread->interpret(); } interpreters::robots::details::RobotModel *Interpreter::robotModel() { return mRobotModel; } void Interpreter::setRobotModel(details::RobotModel * const robotModel) { mRobotModel = robotModel; } void Interpreter::setRobotImplementation(details::robotImplementations::AbstractRobotModelImplementation *robotImpl) { mRobotModel->setRobotImplementation(robotImpl); if (robotImpl) { connect(mRobotModel, SIGNAL(connected(bool)), this, SLOT(runTimer())); } } void Interpreter::runTimer() { if (!mTimer->isActive()) { mTimer->start(10); connect(mTimer, SIGNAL(timeout()), this, SLOT(readSensorValues()), Qt::UniqueConnection); } if (mRobotModel->sensor(inputPort::port1)) { connect(mRobotModel->sensor(inputPort::port1)->sensorImpl(), SIGNAL(response(int)), this, SLOT(responseSlot1(int))); connect(mRobotModel->sensor(inputPort::port1)->sensorImpl(), SIGNAL(failure()), this, SLOT(slotFailure())); } if (mRobotModel->sensor(inputPort::port2)) { connect(mRobotModel->sensor(inputPort::port2)->sensorImpl(), SIGNAL(response(int)), this, SLOT(responseSlot2(int))); connect(mRobotModel->sensor(inputPort::port2)->sensorImpl(), SIGNAL(failure()), this, SLOT(slotFailure())); } if (mRobotModel->sensor(inputPort::port3)) { connect(mRobotModel->sensor(inputPort::port3)->sensorImpl(), SIGNAL(response(int)), this, SLOT(responseSlot3(int))); connect(mRobotModel->sensor(inputPort::port3)->sensorImpl(), SIGNAL(failure()), this, SLOT(slotFailure())); } if (mRobotModel->sensor(inputPort::port4)) { connect(mRobotModel->sensor(inputPort::port4)->sensorImpl(), SIGNAL(response(int)), this, SLOT(responseSlot4(int))); connect(mRobotModel->sensor(inputPort::port4)->sensorImpl(), SIGNAL(failure()), this, SLOT(slotFailure())); } } void Interpreter::readSensorValues() { if (mState == idle) { return; } if (mRobotModel->sensor(inputPort::port1)) { mRobotModel->sensor(inputPort::port1)->read(); } if (mRobotModel->sensor(inputPort::port2)) { mRobotModel->sensor(inputPort::port2)->read(); } if (mRobotModel->sensor(inputPort::port3)) { mRobotModel->sensor(inputPort::port3)->read(); } if (mRobotModel->sensor(inputPort::port4)) { mRobotModel->sensor(inputPort::port4)->read(); } } void Interpreter::slotFailure() { Tracer::debug(tracer::autoupdatedSensorValues, "Interpreter::slotFailure", ""); } void Interpreter::responseSlot1(int sensorValue) { updateSensorValues("Sensor1", sensorValue); } void Interpreter::responseSlot2(int sensorValue) { updateSensorValues("Sensor2", sensorValue); } void Interpreter::responseSlot3(int sensorValue) { updateSensorValues("Sensor3", sensorValue); } void Interpreter::responseSlot4(int sensorValue) { updateSensorValues("Sensor4", sensorValue); } void Interpreter::updateSensorValues(QString const &sensorVariableName, int sensorValue) { (*(mParser->getVariables()))[sensorVariableName] = utils::Number(sensorValue, utils::Number::intType); Tracer::debug(tracer::autoupdatedSensorValues, "Interpreter::updateSensorValues", sensorVariableName + QString::number(sensorValue)); } void Interpreter::resetVariables() { int const resetValue = 0; responseSlot1(resetValue); responseSlot2(resetValue); responseSlot3(resetValue); responseSlot4(resetValue); } void Interpreter::connectToRobot() { if (mState == interpreting) { return; } if (mConnected) { mRobotModel->stopRobot(); mRobotModel->disconnectFromRobot(); } else { mRobotModel->init(); configureSensors(static_cast<sensorType::SensorTypeEnum>(SettingsManager::instance()->value("port1SensorType").toInt()) , static_cast<sensorType::SensorTypeEnum>(SettingsManager::instance()->value("port2SensorType").toInt()) , static_cast<sensorType::SensorTypeEnum>(SettingsManager::instance()->value("port3SensorType").toInt()) , static_cast<sensorType::SensorTypeEnum>(SettingsManager::instance()->value("port4SensorType").toInt())); } mActionConnectToRobot->setChecked(mConnected); } void Interpreter::disconnectSlot() { mActionConnectToRobot->setChecked(false); mConnected = false; } void Interpreter::setRobotModelType(robotModelType::robotModelTypeEnum robotModelType) { setRobotImplementation(robotModelType); } void Interpreter::setCommunicator(QString const &valueOfCommunication, QString const &portName) { if (valueOfCommunication == mLastCommunicationValue) { return; } RobotCommunicationThreadInterface *communicator = NULL; if (valueOfCommunication == "bluetooth") { communicator = new BluetoothRobotCommunicationThread(); } else { communicator = new UsbRobotCommunicationThread(); } mLastCommunicationValue = valueOfCommunication; mRobotCommunication->setRobotCommunicationThreadObject(communicator); mRobotCommunication->setPortName(portName); connectToRobot(); } void Interpreter::setConnectRobotAction(QAction *actionConnect) { mActionConnectToRobot = actionConnect; } void Interpreter::reportError(QString const &message) { mInterpretersInterface->errorReporter()->addError(message); } utils::WatchListWindow *Interpreter::watchWindow() const { return mWatchListWindow; } void Interpreter::connectSensorConfigurer(details::SensorsConfigurationWidget *configurer) const { connect(configurer, SIGNAL(saved()), mD2ModelWidget, SLOT(syncronizeSensors())); } <|endoftext|>
<commit_before> #include <algorithm> #include <iomanip> #include <iostream> #include <iterator> #include <fc/io/json.hpp> #include <fc/io/stdio.hpp> #include <fc/network/http/websocket.hpp> #include <fc/rpc/cli.hpp> #include <fc/rpc/websocket_api.hpp> #include <bts/app/api.hpp> #include <bts/chain/address.hpp> #include <bts/utilities/key_conversion.hpp> #include <bts/wallet/wallet.hpp> using namespace bts::app; using namespace bts::chain; using namespace bts::utilities; using namespace bts::wallet; using namespace std; int main( int argc, char** argv ) { try { FC_ASSERT( argc > 1, "usage: ${cmd} WALLET_FILE", ("cmd",argv[0]) ); fc::ecc::private_key genesis_private_key = fc::ecc::private_key::regenerate(fc::sha256::hash(string("genesis"))); idump( (key_to_wif( genesis_private_key ) ) ); idump( (account_id_type()) ); wallet_data wallet; fc::path wallet_file(argv[1]); if( fc::exists( wallet_file ) ) wallet = fc::json::from_file( wallet_file ).as<wallet_data>(); fc::http::websocket_client client; auto con = client.connect( wallet.ws_server ); auto apic = std::make_shared<fc::rpc::websocket_api_connection>(*con); con->closed.connect( [&](){ elog( "connection closed" ); } ); auto remote_api = apic->get_remote_api< login_api >(); FC_ASSERT( remote_api->login( wallet.ws_user, wallet.ws_password ) ); auto wapiptr = std::make_shared<wallet_api>(remote_api); wapiptr->_wallet = wallet; wapiptr->_start_resync_loop(); fc::api<wallet_api> wapi(wapiptr); auto wallet_cli = std::make_shared<fc::rpc::cli>(); for( auto& name_formatter : wapiptr->_get_result_formatters() ) wallet_cli->format_result( name_formatter.first, name_formatter.second ); wallet_cli->register_api( wapi ); wallet_cli->start(); wallet_cli->wait(); } catch ( const fc::exception& e ) { std::cout << e.to_detail_string() << "\n"; } return -1; } <commit_msg>cli_wallet: Dump key in startup<commit_after> #include <algorithm> #include <iomanip> #include <iostream> #include <iterator> #include <fc/io/json.hpp> #include <fc/io/stdio.hpp> #include <fc/network/http/websocket.hpp> #include <fc/rpc/cli.hpp> #include <fc/rpc/websocket_api.hpp> #include <bts/app/api.hpp> #include <bts/chain/address.hpp> #include <bts/utilities/key_conversion.hpp> #include <bts/wallet/wallet.hpp> using namespace bts::app; using namespace bts::chain; using namespace bts::utilities; using namespace bts::wallet; using namespace std; int main( int argc, char** argv ) { try { FC_ASSERT( argc > 1, "usage: ${cmd} WALLET_FILE", ("cmd",argv[0]) ); fc::ecc::private_key genesis_private_key = fc::ecc::private_key::regenerate(fc::sha256::hash(string("genesis"))); idump( (key_to_wif( genesis_private_key ) ) ); idump( (account_id_type()) ); fc::ecc::private_key nathan_private_key = fc::ecc::private_key::regenerate(fc::sha256::hash(string("nathan"))); idump( (key_to_wif( nathan_private_key ) ) ); wallet_data wallet; fc::path wallet_file(argv[1]); if( fc::exists( wallet_file ) ) wallet = fc::json::from_file( wallet_file ).as<wallet_data>(); fc::http::websocket_client client; auto con = client.connect( wallet.ws_server ); auto apic = std::make_shared<fc::rpc::websocket_api_connection>(*con); con->closed.connect( [&](){ elog( "connection closed" ); } ); auto remote_api = apic->get_remote_api< login_api >(); FC_ASSERT( remote_api->login( wallet.ws_user, wallet.ws_password ) ); auto wapiptr = std::make_shared<wallet_api>(remote_api); wapiptr->_wallet = wallet; wapiptr->_start_resync_loop(); fc::api<wallet_api> wapi(wapiptr); auto wallet_cli = std::make_shared<fc::rpc::cli>(); for( auto& name_formatter : wapiptr->_get_result_formatters() ) wallet_cli->format_result( name_formatter.first, name_formatter.second ); wallet_cli->register_api( wapi ); wallet_cli->start(); wallet_cli->wait(); } catch ( const fc::exception& e ) { std::cout << e.to_detail_string() << "\n"; } return -1; } <|endoftext|>
<commit_before><commit_msg>Use reference when looping over real data in TProtoClass #7426<commit_after><|endoftext|>
<commit_before>#include "stdafx.h" #include "asdf_defs.h" #include "texture_bank.h" #include <glm/gtc/matrix_transform.hpp> #include "main/asdf_multiplat.h" #include "data/content_manager.h" #include "data/gl_state.h" #include "utilities/utilities.h" #include "utilities/cjson_utils.hpp" using namespace std; using namespace glm; namespace stdfs = std::experimental::filesystem; using path = stdfs::path; namespace asdf { using namespace util; namespace data { texture_bank_t::texture_bank_t(string _name) : name(_name) , atlas_texture(_name + string(" atlas"), nullptr, atlas_dim, atlas_dim) { glBindTexture(GL_TEXTURE_2D, atlas_texture.texture_id); GL_State->init_render_target(atlas_fbo, atlas_texture); ASSERT(!CheckGLError(), "GL Error Initializing texture_bank_t"); } path hunt_for_file(path const& _p) { constexpr size_t num_upwards_attempts = 3; //if relative path, look upwards a bit if(_p.is_relative()) { path p = _p; for(size_t i = 0; i < num_upwards_attempts; ++i) { path up_p = "../"; up_p += p; if(stdfs::exists(p)) return p; } } //do a more detailed search path start_point = _p.parent_path().parent_path(); path search = asdf::util::find_file(_p.filename(), start_point); if(!search.empty()) return search; return path(); } void texture_bank_t::load_from_file(path const& filepath) { ASSERT(is_regular_file(filepath), "Not a valid file"); std::string json_str = read_text_file(filepath.string()); cJSON* root = cJSON_Parse(json_str.c_str()); ASSERT(root, "Error loading imported textures json file"); vector<saved_texture_t> terrain; //CJSON_GET_ITEM_VECTOR(terrain); ASSERT(root && root->child, "invalid texture bank json;"); cJSON* terrain_json = root->child; name = terrain_json->string; for(cJSON* arr_item = terrain_json->child; arr_item; arr_item = arr_item->next) { terrain.push_back(saved_texture_t()); terrain.back().from_JSON(arr_item); } auto parent_path = filepath.parent_path(); for(auto& t : terrain) { //filepaths in json are relative to the json document itself if(!t.filepath.is_absolute()) t.local_filepath = parent_path / t.filepath; else t.local_filepath = t.filepath; try{ t.local_filepath = stdfs::canonical(t.local_filepath); } catch (stdfs::filesystem_error const& fs_e) { ///try to hunt around for the file auto p = hunt_for_file(t.local_filepath); if(stdfs::exists(p)) t.local_filepath = p; else throw fs_e; //just rethrow } } add_textures(terrain); cJSON_Delete(root); } void texture_bank_t::save_to_file(std::experimental::filesystem::path const& filepath) { /// FIXME: I dislike that this is a side effect. Should rename this func somehwat? for(auto& t : saved_textures) { ///t.filepath = std::filesystem::relative(t.filepath, filepath); /// MSVC Y U NO SUPPORT FULL C++17 FILESYSTEM!! t.filepath = asdf::util::relative(t.local_filepath, filepath); } write_text_file(filepath.string(), save_to_string()); } cJSON* texture_bank_t::to_JSON() const { CJSON_CREATE_ROOT(); cJSON* textures_json = cJSON_CreateArray(); for(auto const& t : saved_textures) cJSON_AddItemToArray(textures_json, t.to_JSON()); cJSON_AddItemToObject(root, name.c_str(), textures_json); return root; } std::string texture_bank_t::save_to_string() const { char* cjson_cstr = cJSON_Print(to_JSON()); std::string str(cjson_cstr); free(cjson_cstr); return str; } std::string texture_bank_t::save_to_string_unformatted() const { char* cjson_cstr = cJSON_PrintUnformatted(to_JSON()); std::string str(cjson_cstr); free(cjson_cstr); return str; } void texture_bank_t::add_texture(saved_texture_t const& added_texture) { path const& texture_path = added_texture.local_filepath; ASSERT(is_regular_file(texture_path), "File not found %s", texture_path.c_str()); texture_t new_texture(texture_path.string(), SOIL_LOAD_RGBA); //force RGBA, since that's what the atlas uses. Might not be neccesary now that I'm rendering to a framebuffer //ASSERT(new_texture.format == atlas_texture.format, "Color format of texture must match the atlas (GL_RGBA) %s", filepath.c_str()); //ASSERT(new_texture.types[0] == atlas_texture.types[0], ""); int64_t dest_loc_x = (saved_textures.size() % max_saved_textures_1d) * saved_texture_dim; int64_t dest_loc_y = (saved_textures.size() / max_saved_textures_1d) * saved_texture_dim; dest_loc_x += saved_texture_dim_d2; //dest_loc_y += saved_texture_dim_d2; scoped_fbo_t scoped(atlas_fbo, 0,0,atlas_texture.width, atlas_texture.height); ASSERT(!CheckGLError(), ""); auto& screen_shader = app.renderer->screen_shader; GL_State->bind(screen_shader); screen_shader->world_matrix = mat4(); screen_shader->world_matrix = translate(screen_shader->world_matrix, vec3(static_cast<float>(dest_loc_x), static_cast<float>(dest_loc_y + 64), 0.0f)); screen_shader->world_matrix = scale(screen_shader->world_matrix, vec3(saved_texture_dim, saved_texture_dim, 1.0f)); screen_shader->projection_matrix = glm::ortho<float>(0, atlas_texture.width, 0, atlas_texture.height/*, -1.0f, 1.0f*/); screen_shader->update_wvp_uniform(); glUniform4f(screen_shader->uniform("Color"), 1.0f, 1.0f, 1.0f, 1.0f); glBindTexture(GL_TEXTURE_2D, new_texture.texture_id); // app.renderer->quad.render(); app.renderer->quad.render_without_vao(screen_shader); saved_textures.push_back(added_texture); LOG("Added texture '%s' to '%s'", texture_path.c_str(), atlas_texture.name.c_str()); ASSERT(!CheckGLError(), "GL Error in texture_bank_t::add_texture() for \'%s\'", texture_path.c_str()); } void texture_bank_t::add_textures(std::vector<saved_texture_t> const& added_textures) { for(auto const& t : added_textures) add_texture(t); } void texture_bank_t::add_texture(path const& texture_path) { add_texture(saved_texture_t{texture_path.stem().string() , texture_path , std::experimental::filesystem::canonical(texture_path) }); } void texture_bank_t::add_textures(std::vector<path> const& filepaths, path const& relative_dir) { ASSERT(relative_dir.empty() || is_directory(relative_dir), "relative directory is not a directory at all!"); for(path p : filepaths) { if(!relative_dir.empty()) { ASSERT(p.is_relative(), "Texture path is absolute, even though it should be relative to %s", relative_dir.c_str()); p = relative_dir / p; } if(is_regular_file(p)) { add_texture(p); } else { LOG("Texture not found: %s", p.c_str()); } } } void texture_bank_t::add_textures_from_asset_dir(std::vector<path> const& filepaths) { add_textures(filepaths, path(Content.asset_path)); } void texture_bank_t::clear() { saved_textures.clear(); } cJSON* saved_texture_t::to_JSON() const { CJSON_CREATE_ROOT(); CJSON_ADD_STR(name); ASSERT(filepath.string().size() > 0, "Unexpected empty filepath"); cJSON_AddStringToObject(root, "filepath", filepath.string().c_str()); return root; } void saved_texture_t::from_JSON(cJSON* root) { CJSON_GET_STR(name); auto path_str = string(cJSON_GetObjectItem(root, "filepath")->valuestring); asdf::util::replace(path_str, "\\", "/"); filepath = std::experimental::filesystem::path(path_str); } } } <commit_msg>minor refactor<commit_after>#include "stdafx.h" #include "asdf_defs.h" #include "texture_bank.h" #include <glm/gtc/matrix_transform.hpp> #include "main/asdf_multiplat.h" #include "data/content_manager.h" #include "data/gl_state.h" #include "utilities/utilities.h" #include "utilities/cjson_utils.hpp" using namespace std; using namespace glm; namespace stdfs = std::experimental::filesystem; using path = stdfs::path; namespace asdf { using namespace util; namespace data { texture_bank_t::texture_bank_t(string _name) : name(_name) , atlas_texture(_name + string(" atlas"), nullptr, atlas_dim, atlas_dim) { glBindTexture(GL_TEXTURE_2D, atlas_texture.texture_id); GL_State->init_render_target(atlas_fbo, atlas_texture); ASSERT(!CheckGLError(), "GL Error Initializing texture_bank_t"); } path hunt_for_file(path const& _p) { constexpr size_t num_upwards_attempts = 3; //if relative path, look upwards a bit if(_p.is_relative()) { path p = _p; for(size_t i = 0; i < num_upwards_attempts; ++i) { path up_p = "../"; up_p += p; if(stdfs::exists(p)) return p; } } //do a more detailed search path start_point = _p.parent_path().parent_path(); path search = asdf::util::find_file(_p.filename(), start_point); if(!search.empty()) return search; return path(); } void texture_bank_t::load_from_file(path const& filepath) { ASSERT(is_regular_file(filepath), "Not a valid file"); std::string json_str = read_text_file(filepath.string()); cJSON* root = cJSON_Parse(json_str.c_str()); ASSERT(root, "Error loading imported textures json file"); vector<saved_texture_t> terrain; //CJSON_GET_ITEM_VECTOR(terrain); ASSERT(root && root->child, "invalid texture bank json;"); cJSON* terrain_json = root->child; name = terrain_json->string; for(cJSON* arr_item = terrain_json->child; arr_item; arr_item = arr_item->next) { terrain.push_back(saved_texture_t()); terrain.back().from_JSON(arr_item); } auto parent_path = filepath.parent_path(); for(auto& t : terrain) { //filepaths in json are relative to the json document itself if(!t.filepath.is_absolute()) t.local_filepath = parent_path / t.filepath; else t.local_filepath = t.filepath; try{ t.local_filepath = stdfs::canonical(t.local_filepath); } catch (stdfs::filesystem_error const& fs_e) { ///try to hunt around for the file auto p = hunt_for_file(t.local_filepath); if(stdfs::exists(p)) t.local_filepath = p; else throw fs_e; //just rethrow } } add_textures(terrain); cJSON_Delete(root); } void texture_bank_t::save_to_file(std::experimental::filesystem::path const& filepath) { /// FIXME: I dislike that this is a side effect. Should rename this func somehwat? for(auto& t : saved_textures) { ///t.filepath = std::filesystem::relative(t.filepath, filepath); /// MSVC Y U NO SUPPORT FULL C++17 FILESYSTEM!! t.filepath = asdf::util::relative(t.local_filepath, filepath); } write_text_file(filepath.string(), save_to_string()); } cJSON* texture_bank_t::to_JSON() const { CJSON_CREATE_ROOT(); cJSON* textures_json = cJSON_CreateArray(); for(auto const& t : saved_textures) cJSON_AddItemToArray(textures_json, t.to_JSON()); cJSON_AddItemToObject(root, name.c_str(), textures_json); return root; } std::string texture_bank_t::save_to_string() const { return asdf::json_to_string(to_JSON()); } std::string texture_bank_t::save_to_string_unformatted() const { return json_to_string_unformatted(to_JSON()); } void texture_bank_t::add_texture(saved_texture_t const& added_texture) { path const& texture_path = added_texture.local_filepath; ASSERT(is_regular_file(texture_path), "File not found %s", texture_path.c_str()); texture_t new_texture(texture_path.string(), SOIL_LOAD_RGBA); //force RGBA, since that's what the atlas uses. Might not be neccesary now that I'm rendering to a framebuffer //ASSERT(new_texture.format == atlas_texture.format, "Color format of texture must match the atlas (GL_RGBA) %s", filepath.c_str()); //ASSERT(new_texture.types[0] == atlas_texture.types[0], ""); int64_t dest_loc_x = (saved_textures.size() % max_saved_textures_1d) * saved_texture_dim; int64_t dest_loc_y = (saved_textures.size() / max_saved_textures_1d) * saved_texture_dim; dest_loc_x += saved_texture_dim_d2; //dest_loc_y += saved_texture_dim_d2; scoped_fbo_t scoped(atlas_fbo, 0,0,atlas_texture.width, atlas_texture.height); ASSERT(!CheckGLError(), ""); auto& screen_shader = app.renderer->screen_shader; GL_State->bind(screen_shader); screen_shader->world_matrix = mat4(); screen_shader->world_matrix = translate(screen_shader->world_matrix, vec3(static_cast<float>(dest_loc_x), static_cast<float>(dest_loc_y + 64), 0.0f)); screen_shader->world_matrix = scale(screen_shader->world_matrix, vec3(saved_texture_dim, saved_texture_dim, 1.0f)); screen_shader->projection_matrix = glm::ortho<float>(0, atlas_texture.width, 0, atlas_texture.height/*, -1.0f, 1.0f*/); screen_shader->update_wvp_uniform(); glUniform4f(screen_shader->uniform("Color"), 1.0f, 1.0f, 1.0f, 1.0f); glBindTexture(GL_TEXTURE_2D, new_texture.texture_id); // app.renderer->quad.render(); app.renderer->quad.render_without_vao(screen_shader); saved_textures.push_back(added_texture); LOG("Added texture '%s' to '%s'", texture_path.c_str(), atlas_texture.name.c_str()); ASSERT(!CheckGLError(), "GL Error in texture_bank_t::add_texture() for \'%s\'", texture_path.c_str()); } void texture_bank_t::add_textures(std::vector<saved_texture_t> const& added_textures) { for(auto const& t : added_textures) add_texture(t); } void texture_bank_t::add_texture(path const& texture_path) { add_texture(saved_texture_t{texture_path.stem().string() , texture_path , std::experimental::filesystem::canonical(texture_path) }); } void texture_bank_t::add_textures(std::vector<path> const& filepaths, path const& relative_dir) { ASSERT(relative_dir.empty() || is_directory(relative_dir), "relative directory is not a directory at all!"); for(path p : filepaths) { if(!relative_dir.empty()) { ASSERT(p.is_relative(), "Texture path is absolute, even though it should be relative to %s", relative_dir.c_str()); p = relative_dir / p; } if(is_regular_file(p)) { add_texture(p); } else { LOG("Texture not found: %s", p.c_str()); } } } void texture_bank_t::add_textures_from_asset_dir(std::vector<path> const& filepaths) { add_textures(filepaths, path(Content.asset_path)); } void texture_bank_t::clear() { saved_textures.clear(); } cJSON* saved_texture_t::to_JSON() const { CJSON_CREATE_ROOT(); CJSON_ADD_STR(name); ASSERT(filepath.string().size() > 0, "Unexpected empty filepath"); cJSON_AddStringToObject(root, "filepath", filepath.string().c_str()); return root; } void saved_texture_t::from_JSON(cJSON* root) { CJSON_GET_STR(name); auto path_str = string(cJSON_GetObjectItem(root, "filepath")->valuestring); asdf::util::replace(path_str, "\\", "/"); filepath = std::experimental::filesystem::path(path_str); } } } <|endoftext|>
<commit_before>/* This file is part of the KDE project Copyright (C) 2010 Thomas Fjellstrom <thomas@fjellstrom.ca> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ //BEGIN Includes #include "katefiletreeplugin.h" #include "katefiletreeplugin.moc" #include "katefiletree.h" #include "katefiletreemodel.h" #include "katefiletreeproxymodel.h" #include "katefiletreeconfigpage.h" #include <kate/application.h> #include <kate/mainwindow.h> #include <kate/documentmanager.h> #include <ktexteditor/view.h> #include <kaboutdata.h> #include <kpluginfactory.h> #include <KAction> #include <KActionCollection> #include <KConfigGroup> #include <QApplication> #include "katefiletreedebug.h" //END Includes K_PLUGIN_FACTORY(KateFileTreeFactory, registerPlugin<KateFileTreePlugin>();) K_EXPORT_PLUGIN(KateFileTreeFactory(KAboutData("katefiletreeplugin","katefiletreeplugin",ki18n("Document Tree"), "0.1", ki18n("Show open documents in a tree"), KAboutData::License_LGPL_V2)) ) //BEGIN KateFileTreePlugin KateFileTreePlugin::KateFileTreePlugin(QObject* parent, const QList<QVariant>&) : Kate::Plugin ((Kate::Application*)parent) { } Kate::PluginView *KateFileTreePlugin::createView (Kate::MainWindow *mainWindow) { if(m_view.contains(mainWindow)) { kDebug(debugArea()) << "ERROR: view hash already contains this mainWindow"; Q_ASSERT(m_view.contains(mainWindow) == true); } m_view[mainWindow] = new KateFileTreePluginView (mainWindow); return m_view[mainWindow]; } uint KateFileTreePlugin::configPages() const { return 1; } QString KateFileTreePlugin::configPageName (uint number) const { if(number != 0) return QString(); return QString("Tree View"); } QString KateFileTreePlugin::configPageFullName (uint number) const { if(number != 0) return QString(); return QString("Configure Tree View"); } KIcon KateFileTreePlugin::configPageIcon (uint number) const { if(number != 0) return KIcon(); return KIcon("view-list-tree"); } Kate::PluginConfigPage *KateFileTreePlugin::configPage (uint number, QWidget *parent, const char *name) { Q_UNUSED(name); if(number != 0) return 0; // HACK HACK HACK HACK HACK // This is some fun stuff. KateApp::activeMainWindow uses // QApplication::activeWindow to get the active window, // but by the time this method is called, the active window // is the KateConfigDialog we're going to be displaying in. // And since KateApp::activeMainWindow can't find the // config dialog in its own window list, it'll just return // the first main window. so we have to use // QApplication::activeWindow ourselves! Kate::MainWindow *mainWindow; Kate::Application *kate_app = Kate::application(); QWidget *hack = qApp->activeWindow(); // hack->parent() isa KateMainWindow // Kate::MainWindow's parent is a KateMainWindow // since we can't just include KateMainWindow's // header to use the mainWindow method, we have to // compare against Kate::MainWindow->window kDebug(debugArea()) << "hack:" << hack->parent(); foreach(Kate::MainWindow *win, kate_app->mainWindows()) { kDebug(debugArea()) << "win:" << win; if(hack->parent() == win->window()) { kDebug(debugArea()) << "found hack!"; mainWindow = win; break; } } Q_ASSERT(mainWindow != 0); if(!m_view.contains(mainWindow)) { kDebug(debugArea()) << "view hash does not contain given main window :("; return 0; } kDebug(debugArea()) << "got mw:" << mainWindow << "parent:" << parent; KateFileTreeConfigPage *page = new KateFileTreeConfigPage(parent, m_view[mainWindow]); return page; } //END KateFileTreePlugin //BEGIN KateFileTreePluginView KateFileTreePluginView::KateFileTreePluginView (Kate::MainWindow *mainWindow) : Kate::PluginView (mainWindow), KXMLGUIClient() { // init console kDebug(debugArea()) << "BEGIN: mw:" << mainWindow; QWidget *toolview = mainWindow->createToolView ("kate_private_plugin_katefiletreeplugin", Kate::MainWindow::Left, SmallIcon("document-open"), i18n("Document Tree")); m_fileTree = new KateFileTree(toolview); m_fileTree->setSortingEnabled(true); connect(m_fileTree, SIGNAL(activateDocument(KTextEditor::Document*)), this, SLOT(activateDocument(KTextEditor::Document*))); connect(m_fileTree, SIGNAL(viewModeChanged(bool)), this, SLOT(viewModeChanged(bool))); connect(m_fileTree, SIGNAL(sortRoleChanged(int)), this, SLOT(sortRoleChanged(int))); m_documentModel = new KateFileTreeModel(this); m_proxyModel = new KateFileTreeProxyModel(this); m_proxyModel->setSourceModel(m_documentModel); m_proxyModel->setDynamicSortFilter(true); Kate::DocumentManager *dm = Kate::application()->documentManager(); connect(dm, SIGNAL(documentCreated(KTextEditor::Document *)), m_documentModel, SLOT(documentOpened(KTextEditor::Document *))); connect(dm, SIGNAL(documentWillBeDeleted(KTextEditor::Document *)), m_documentModel, SLOT(documentClosed(KTextEditor::Document *))); connect(dm, SIGNAL(documentCreated(KTextEditor::Document *)), this, SLOT(documentOpened(KTextEditor::Document *))); connect(dm, SIGNAL(documentWillBeDeleted(KTextEditor::Document *)), this, SLOT(documentClosed(KTextEditor::Document *))); m_fileTree->setModel(m_proxyModel); m_fileTree->setDragEnabled(false); m_fileTree->setDragDropMode(QAbstractItemView::InternalMove); m_fileTree->setDropIndicatorShown(false); m_fileTree->setSelectionMode(QAbstractItemView::SingleSelection); connect( m_fileTree->selectionModel(), SIGNAL(currentChanged(const QModelIndex&, const QModelIndex&)), m_fileTree, SLOT(slotCurrentChanged(const QModelIndex&, const QModelIndex&))); connect(mainWindow, SIGNAL(viewChanged()), this, SLOT(viewChanged())); setComponentData( KComponentData("kate") ); setXMLFile(QString::fromLatin1("plugins/filetree/ui.rc")); KAction *show_active = actionCollection()->addAction("filetree_show_active_document", mainWindow); show_active->setText(i18n("&Show Active")); show_active->setIcon(KIcon("folder-sync")); show_active->setShortcut( QKeySequence(Qt::ALT+Qt::Key_A), KAction::DefaultShortcut ); connect( show_active, SIGNAL( triggered(bool) ), this, SLOT( showActiveDocument() ) ); mainWindow->guiFactory()->addClient(this); m_proxyModel->setSortRole(Qt::DisplayRole); m_proxyModel->sort(0, Qt::AscendingOrder); m_proxyModel->invalidate(); } KateFileTreePluginView::~KateFileTreePluginView () { // clean up tree and toolview delete m_fileTree->parentWidget(); // and TreeModel delete m_documentModel; } KateFileTreeModel *KateFileTreePluginView::model() { return m_documentModel; } KateFileTreeProxyModel *KateFileTreePluginView::proxy() { return m_proxyModel; } void KateFileTreePluginView::documentOpened(KTextEditor::Document *doc) { kDebug(debugArea()) << "open" << doc; connect(doc, SIGNAL(modifiedChanged(KTextEditor::Document*)), m_documentModel, SLOT(documentEdited(KTextEditor::Document*))); m_proxyModel->invalidate(); } void KateFileTreePluginView::documentClosed(KTextEditor::Document *doc) { kDebug(debugArea()) << "close" << doc; m_proxyModel->invalidate(); } void KateFileTreePluginView::viewChanged() { kDebug(debugArea()) << "BEGIN!"; KTextEditor::View *view = mainWindow()->activeView(); if(!view) return; KTextEditor::Document *doc = view->document(); QModelIndex index = m_proxyModel->docIndex(doc); kDebug(debugArea()) << "selected doc=" << doc << index; QString display = m_proxyModel->data(index, Qt::DisplayRole).toString(); kDebug(debugArea()) << "display="<<display; // update the model on which doc is active m_documentModel->documentActivated(doc); m_fileTree->selectionModel()->setCurrentIndex(index, QItemSelectionModel::ClearAndSelect); m_fileTree->scrollTo(index); while(index != QModelIndex()) { m_fileTree->expand(index); index = index.parent(); } kDebug(debugArea()) << "END!"; } void KateFileTreePluginView::setListMode(bool listMode) { kDebug(debugArea()) << "BEGIN"; if(listMode) { kDebug(debugArea()) << "listMode"; m_documentModel->setListMode(true); m_fileTree->setRootIsDecorated(false); } else { kDebug(debugArea()) << "treeMode"; m_documentModel->setListMode(false); m_fileTree->setRootIsDecorated(true); } m_proxyModel->sort(0, Qt::AscendingOrder); m_proxyModel->invalidate(); kDebug(debugArea()) << "END"; } void KateFileTreePluginView::viewModeChanged(bool listMode) { kDebug(debugArea()) << "BEGIN"; setListMode(listMode); kDebug(debugArea()) << "END"; } void KateFileTreePluginView::sortRoleChanged(int role) { kDebug(debugArea()) << "BEGIN"; m_proxyModel->setSortRole(role); m_proxyModel->invalidate(); kDebug(debugArea()) << "END"; } void KateFileTreePluginView::activateDocument(KTextEditor::Document *doc) { mainWindow()->activateView(doc); } void KateFileTreePluginView::showActiveDocument() { // hack? viewChanged(); // FIXME: make the tool view show if it was hidden } void KateFileTreePluginView::readSessionConfig(KConfigBase* config, const QString& group) { KConfigGroup g = config->group(group); bool listMode = g.readEntry("listMode", QVariant(false)).toBool(); setListMode(listMode); int sortRole = g.readEntry("sortRole", int(Qt::DisplayRole)); m_proxyModel->setSortRole(sortRole); // m_fileTree->readSessionConfig(config, group); } void KateFileTreePluginView::writeSessionConfig(KConfigBase* config, const QString& group) { KConfigGroup g = config->group(group); g.writeEntry("listMode", QVariant(m_documentModel->listMode())); g.writeEntry("sortRole", int(m_proxyModel->sortRole())); g.sync(); // m_fileTree->writeSessionConfig(config, group); } //ENDKateFileTreePluginView // kate: space-indent on; indent-width 2; replace-tabs on; <commit_msg>name it documents<commit_after>/* This file is part of the KDE project Copyright (C) 2010 Thomas Fjellstrom <thomas@fjellstrom.ca> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ //BEGIN Includes #include "katefiletreeplugin.h" #include "katefiletreeplugin.moc" #include "katefiletree.h" #include "katefiletreemodel.h" #include "katefiletreeproxymodel.h" #include "katefiletreeconfigpage.h" #include <kate/application.h> #include <kate/mainwindow.h> #include <kate/documentmanager.h> #include <ktexteditor/view.h> #include <kaboutdata.h> #include <kpluginfactory.h> #include <KAction> #include <KActionCollection> #include <KConfigGroup> #include <QApplication> #include "katefiletreedebug.h" //END Includes K_PLUGIN_FACTORY(KateFileTreeFactory, registerPlugin<KateFileTreePlugin>();) K_EXPORT_PLUGIN(KateFileTreeFactory(KAboutData("katefiletreeplugin","katefiletreeplugin",ki18n("Document Tree"), "0.1", ki18n("Show open documents in a tree"), KAboutData::License_LGPL_V2)) ) //BEGIN KateFileTreePlugin KateFileTreePlugin::KateFileTreePlugin(QObject* parent, const QList<QVariant>&) : Kate::Plugin ((Kate::Application*)parent) { } Kate::PluginView *KateFileTreePlugin::createView (Kate::MainWindow *mainWindow) { if(m_view.contains(mainWindow)) { kDebug(debugArea()) << "ERROR: view hash already contains this mainWindow"; Q_ASSERT(m_view.contains(mainWindow) == true); } m_view[mainWindow] = new KateFileTreePluginView (mainWindow); return m_view[mainWindow]; } uint KateFileTreePlugin::configPages() const { return 1; } QString KateFileTreePlugin::configPageName (uint number) const { if(number != 0) return QString(); return QString("Tree View"); } QString KateFileTreePlugin::configPageFullName (uint number) const { if(number != 0) return QString(); return QString("Configure Tree View"); } KIcon KateFileTreePlugin::configPageIcon (uint number) const { if(number != 0) return KIcon(); return KIcon("view-list-tree"); } Kate::PluginConfigPage *KateFileTreePlugin::configPage (uint number, QWidget *parent, const char *name) { Q_UNUSED(name); if(number != 0) return 0; // HACK HACK HACK HACK HACK // This is some fun stuff. KateApp::activeMainWindow uses // QApplication::activeWindow to get the active window, // but by the time this method is called, the active window // is the KateConfigDialog we're going to be displaying in. // And since KateApp::activeMainWindow can't find the // config dialog in its own window list, it'll just return // the first main window. so we have to use // QApplication::activeWindow ourselves! Kate::MainWindow *mainWindow; Kate::Application *kate_app = Kate::application(); QWidget *hack = qApp->activeWindow(); // hack->parent() isa KateMainWindow // Kate::MainWindow's parent is a KateMainWindow // since we can't just include KateMainWindow's // header to use the mainWindow method, we have to // compare against Kate::MainWindow->window kDebug(debugArea()) << "hack:" << hack->parent(); foreach(Kate::MainWindow *win, kate_app->mainWindows()) { kDebug(debugArea()) << "win:" << win; if(hack->parent() == win->window()) { kDebug(debugArea()) << "found hack!"; mainWindow = win; break; } } Q_ASSERT(mainWindow != 0); if(!m_view.contains(mainWindow)) { kDebug(debugArea()) << "view hash does not contain given main window :("; return 0; } kDebug(debugArea()) << "got mw:" << mainWindow << "parent:" << parent; KateFileTreeConfigPage *page = new KateFileTreeConfigPage(parent, m_view[mainWindow]); return page; } //END KateFileTreePlugin //BEGIN KateFileTreePluginView KateFileTreePluginView::KateFileTreePluginView (Kate::MainWindow *mainWindow) : Kate::PluginView (mainWindow), KXMLGUIClient() { // init console kDebug(debugArea()) << "BEGIN: mw:" << mainWindow; QWidget *toolview = mainWindow->createToolView ("kate_private_plugin_katefiletreeplugin", Kate::MainWindow::Left, SmallIcon("document-open"), i18n("Documents")); m_fileTree = new KateFileTree(toolview); m_fileTree->setSortingEnabled(true); connect(m_fileTree, SIGNAL(activateDocument(KTextEditor::Document*)), this, SLOT(activateDocument(KTextEditor::Document*))); connect(m_fileTree, SIGNAL(viewModeChanged(bool)), this, SLOT(viewModeChanged(bool))); connect(m_fileTree, SIGNAL(sortRoleChanged(int)), this, SLOT(sortRoleChanged(int))); m_documentModel = new KateFileTreeModel(this); m_proxyModel = new KateFileTreeProxyModel(this); m_proxyModel->setSourceModel(m_documentModel); m_proxyModel->setDynamicSortFilter(true); Kate::DocumentManager *dm = Kate::application()->documentManager(); connect(dm, SIGNAL(documentCreated(KTextEditor::Document *)), m_documentModel, SLOT(documentOpened(KTextEditor::Document *))); connect(dm, SIGNAL(documentWillBeDeleted(KTextEditor::Document *)), m_documentModel, SLOT(documentClosed(KTextEditor::Document *))); connect(dm, SIGNAL(documentCreated(KTextEditor::Document *)), this, SLOT(documentOpened(KTextEditor::Document *))); connect(dm, SIGNAL(documentWillBeDeleted(KTextEditor::Document *)), this, SLOT(documentClosed(KTextEditor::Document *))); m_fileTree->setModel(m_proxyModel); m_fileTree->setDragEnabled(false); m_fileTree->setDragDropMode(QAbstractItemView::InternalMove); m_fileTree->setDropIndicatorShown(false); m_fileTree->setSelectionMode(QAbstractItemView::SingleSelection); connect( m_fileTree->selectionModel(), SIGNAL(currentChanged(const QModelIndex&, const QModelIndex&)), m_fileTree, SLOT(slotCurrentChanged(const QModelIndex&, const QModelIndex&))); connect(mainWindow, SIGNAL(viewChanged()), this, SLOT(viewChanged())); setComponentData( KComponentData("kate") ); setXMLFile(QString::fromLatin1("plugins/filetree/ui.rc")); KAction *show_active = actionCollection()->addAction("filetree_show_active_document", mainWindow); show_active->setText(i18n("&Show Active")); show_active->setIcon(KIcon("folder-sync")); show_active->setShortcut( QKeySequence(Qt::ALT+Qt::Key_A), KAction::DefaultShortcut ); connect( show_active, SIGNAL( triggered(bool) ), this, SLOT( showActiveDocument() ) ); mainWindow->guiFactory()->addClient(this); m_proxyModel->setSortRole(Qt::DisplayRole); m_proxyModel->sort(0, Qt::AscendingOrder); m_proxyModel->invalidate(); } KateFileTreePluginView::~KateFileTreePluginView () { // clean up tree and toolview delete m_fileTree->parentWidget(); // and TreeModel delete m_documentModel; } KateFileTreeModel *KateFileTreePluginView::model() { return m_documentModel; } KateFileTreeProxyModel *KateFileTreePluginView::proxy() { return m_proxyModel; } void KateFileTreePluginView::documentOpened(KTextEditor::Document *doc) { kDebug(debugArea()) << "open" << doc; connect(doc, SIGNAL(modifiedChanged(KTextEditor::Document*)), m_documentModel, SLOT(documentEdited(KTextEditor::Document*))); m_proxyModel->invalidate(); } void KateFileTreePluginView::documentClosed(KTextEditor::Document *doc) { kDebug(debugArea()) << "close" << doc; m_proxyModel->invalidate(); } void KateFileTreePluginView::viewChanged() { kDebug(debugArea()) << "BEGIN!"; KTextEditor::View *view = mainWindow()->activeView(); if(!view) return; KTextEditor::Document *doc = view->document(); QModelIndex index = m_proxyModel->docIndex(doc); kDebug(debugArea()) << "selected doc=" << doc << index; QString display = m_proxyModel->data(index, Qt::DisplayRole).toString(); kDebug(debugArea()) << "display="<<display; // update the model on which doc is active m_documentModel->documentActivated(doc); m_fileTree->selectionModel()->setCurrentIndex(index, QItemSelectionModel::ClearAndSelect); m_fileTree->scrollTo(index); while(index != QModelIndex()) { m_fileTree->expand(index); index = index.parent(); } kDebug(debugArea()) << "END!"; } void KateFileTreePluginView::setListMode(bool listMode) { kDebug(debugArea()) << "BEGIN"; if(listMode) { kDebug(debugArea()) << "listMode"; m_documentModel->setListMode(true); m_fileTree->setRootIsDecorated(false); } else { kDebug(debugArea()) << "treeMode"; m_documentModel->setListMode(false); m_fileTree->setRootIsDecorated(true); } m_proxyModel->sort(0, Qt::AscendingOrder); m_proxyModel->invalidate(); kDebug(debugArea()) << "END"; } void KateFileTreePluginView::viewModeChanged(bool listMode) { kDebug(debugArea()) << "BEGIN"; setListMode(listMode); kDebug(debugArea()) << "END"; } void KateFileTreePluginView::sortRoleChanged(int role) { kDebug(debugArea()) << "BEGIN"; m_proxyModel->setSortRole(role); m_proxyModel->invalidate(); kDebug(debugArea()) << "END"; } void KateFileTreePluginView::activateDocument(KTextEditor::Document *doc) { mainWindow()->activateView(doc); } void KateFileTreePluginView::showActiveDocument() { // hack? viewChanged(); // FIXME: make the tool view show if it was hidden } void KateFileTreePluginView::readSessionConfig(KConfigBase* config, const QString& group) { KConfigGroup g = config->group(group); bool listMode = g.readEntry("listMode", QVariant(false)).toBool(); setListMode(listMode); int sortRole = g.readEntry("sortRole", int(Qt::DisplayRole)); m_proxyModel->setSortRole(sortRole); // m_fileTree->readSessionConfig(config, group); } void KateFileTreePluginView::writeSessionConfig(KConfigBase* config, const QString& group) { KConfigGroup g = config->group(group); g.writeEntry("listMode", QVariant(m_documentModel->listMode())); g.writeEntry("sortRole", int(m_proxyModel->sortRole())); g.sync(); // m_fileTree->writeSessionConfig(config, group); } //ENDKateFileTreePluginView // kate: space-indent on; indent-width 2; replace-tabs on; <|endoftext|>
<commit_before>/// \file dtsc_analyser.cpp /// Reads an DTSC file and prints all readable data about it #include <string> #include <iostream> #include <sstream> #include <mist/dtsc.h> #include <mist/json.h> #include <mist/config.h> #include <mist/defines.h> ///\brief Holds everything unique to the analysers. namespace Analysers { ///\brief Debugging tool for DTSC data. /// /// Expects DTSC data in a file given on the command line, outputs human-readable information to stderr. ///\param conf The configuration parsed from the commandline. ///\return The return code of the analyser. int analyseDTSC(Util::Config conf){ DTSC::File F(conf.getString("filename")); F.getMeta().toPrettyString(std::cout,0, 0x03); int bPos = 0; F.seek_bpos(0); F.parseNext(); while (F.getPacket()){ switch (F.getPacket().getVersion()){ case DTSC::DTSC_V1: { std::cout << "DTSCv1 packet: " << F.getPacket().getScan().toPrettyString() << std::endl; break; } case DTSC::DTSC_V2: { std::cout << "DTSCv2 packet: " << F.getPacket().getScan().toPrettyString() << std::endl; break; } case DTSC::DTSC_HEAD: { std::cout << "DTSC header: " << F.getPacket().getScan().toPrettyString() << std::endl; break; } default: DEBUG_MSG(DLVL_WARN,"Invalid dtsc packet @ bpos %d", bPos); break; } bPos = F.getBytePos(); F.parseNext(); } return 0; } } /// Reads an DTSC file and prints all readable data about it int main(int argc, char ** argv){ Util::Config conf = Util::Config(argv[0], PACKAGE_VERSION); conf.addOption("filename", JSON::fromString("{\"arg_num\":1, \"arg\":\"string\", \"help\":\"Filename of the DTSC file to analyse.\"}")); conf.parseArgs(argc, argv); return Analysers::analyseDTSC(conf); } //main <commit_msg>Fixed a bug in the DTSC analyser<commit_after>/// \file dtsc_analyser.cpp /// Reads an DTSC file and prints all readable data about it #include <string> #include <iostream> #include <sstream> #include <mist/dtsc.h> #include <mist/json.h> #include <mist/config.h> #include <mist/defines.h> ///\brief Holds everything unique to the analysers. namespace Analysers { ///\brief Debugging tool for DTSC data. /// /// Expects DTSC data in a file given on the command line, outputs human-readable information to stderr. ///\param conf The configuration parsed from the commandline. ///\return The return code of the analyser. int analyseDTSC(Util::Config conf){ DTSC::File F(conf.getString("filename")); if (!F){ std::cerr << "Not a valid DTSC file" << std::endl; return 1; } F.getMeta().toPrettyString(std::cout,0, 0x03); int bPos = 0; F.seek_bpos(0); F.parseNext(); while (F.getPacket()){ switch (F.getPacket().getVersion()){ case DTSC::DTSC_V1: { std::cout << "DTSCv1 packet: " << F.getPacket().getScan().toPrettyString() << std::endl; break; } case DTSC::DTSC_V2: { std::cout << "DTSCv2 packet: " << F.getPacket().getScan().toPrettyString() << std::endl; break; } case DTSC::DTSC_HEAD: { std::cout << "DTSC header: " << F.getPacket().getScan().toPrettyString() << std::endl; break; } default: DEBUG_MSG(DLVL_WARN,"Invalid dtsc packet @ bpos %d", bPos); break; } bPos = F.getBytePos(); F.parseNext(); } return 0; } } /// Reads an DTSC file and prints all readable data about it int main(int argc, char ** argv){ Util::Config conf = Util::Config(argv[0], PACKAGE_VERSION); conf.addOption("filename", JSON::fromString("{\"arg_num\":1, \"arg\":\"string\", \"help\":\"Filename of the DTSC file to analyse.\"}")); conf.parseArgs(argc, argv); return Analysers::analyseDTSC(conf); } //main <|endoftext|>
<commit_before>//===-- CommandObjectDisassemble.cpp ----------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "CommandObjectDisassemble.h" // C Includes // C++ Includes // Other libraries and framework includes // Project includes #include "lldb/Core/AddressRange.h" #include "lldb/Interpreter/Args.h" #include "lldb/Interpreter/CommandCompletions.h" #include "lldb/Interpreter/CommandInterpreter.h" #include "lldb/Interpreter/CommandReturnObject.h" #include "lldb/Core/Disassembler.h" #include "lldb/Interpreter/Options.h" #include "lldb/Core/SourceManager.h" #include "lldb/Core/Stream.h" #include "lldb/Target/StackFrame.h" #include "lldb/Symbol/Symbol.h" #include "lldb/Target/Process.h" #include "lldb/Target/Target.h" #include "lldb/Target/StackFrame.h" #include "lldb/Target/Thread.h" #include "lldb/Symbol/FuncUnwinders.h" #include "lldb/Symbol/UnwindPlan.h" #include "lldb/Symbol/DWARFCallFrameInfo.h" #include "lldb/Utility/ArchVolatileRegs.h" #define DEFAULT_DISASM_BYTE_SIZE 32 using namespace lldb; using namespace lldb_private; CommandObjectDisassemble::CommandOptions::CommandOptions () : Options(), m_func_name(), m_start_addr(), m_end_addr () { ResetOptionValues(); } CommandObjectDisassemble::CommandOptions::~CommandOptions () { } Error CommandObjectDisassemble::CommandOptions::SetOptionValue (int option_idx, const char *option_arg) { Error error; char short_option = (char) m_getopt_table[option_idx].val; switch (short_option) { case 'm': show_mixed = true; break; case 'c': num_lines_context = Args::StringToUInt32(option_arg, 0, 0); break; case 'b': show_bytes = true; break; case 's': m_start_addr = Args::StringToUInt64(optarg, LLDB_INVALID_ADDRESS, 0); if (m_start_addr == LLDB_INVALID_ADDRESS) m_start_addr = Args::StringToUInt64(optarg, LLDB_INVALID_ADDRESS, 16); if (m_start_addr == LLDB_INVALID_ADDRESS) error.SetErrorStringWithFormat ("Invalid start address string '%s'.\n", optarg); break; case 'e': m_end_addr = Args::StringToUInt64(optarg, LLDB_INVALID_ADDRESS, 0); if (m_end_addr == LLDB_INVALID_ADDRESS) m_end_addr = Args::StringToUInt64(optarg, LLDB_INVALID_ADDRESS, 16); if (m_end_addr == LLDB_INVALID_ADDRESS) error.SetErrorStringWithFormat ("Invalid end address string '%s'.\n", optarg); break; case 'n': m_func_name = option_arg; break; case 'r': raw = true; break; case 'f': // The default action is to disassemble the function for the current frame. // There's no need to set any flag. break; default: error.SetErrorStringWithFormat("Unrecognized short option '%c'.\n", short_option); break; } return error; } void CommandObjectDisassemble::CommandOptions::ResetOptionValues () { Options::ResetOptionValues(); show_mixed = false; show_bytes = false; num_lines_context = 0; m_func_name.clear(); m_start_addr = LLDB_INVALID_ADDRESS; m_end_addr = LLDB_INVALID_ADDRESS; raw = false; } const lldb::OptionDefinition* CommandObjectDisassemble::CommandOptions::GetDefinitions () { return g_option_table; } lldb::OptionDefinition CommandObjectDisassemble::CommandOptions::g_option_table[] = { { LLDB_OPT_SET_ALL, false, "bytes", 'b', no_argument, NULL, 0, eArgTypeNone, "Show opcode bytes when disassembling."}, { LLDB_OPT_SET_ALL, false, "context", 'c', required_argument, NULL, 0, eArgTypeNumLines, "Number of context lines of source to show."}, { LLDB_OPT_SET_ALL, false, "mixed", 'm', no_argument, NULL, 0, eArgTypeNone, "Enable mixed source and assembly display."}, { LLDB_OPT_SET_ALL, false, "raw", 'r', no_argument, NULL, 0, eArgTypeNone, "Print raw disassembly with no symbol information."}, { LLDB_OPT_SET_1, true, "start-address", 's', required_argument, NULL, 0, eArgTypeStartAddress, "Address at which to start disassembling."}, { LLDB_OPT_SET_1, false, "end-address", 'e', required_argument, NULL, 0, eArgTypeEndAddress, "Address at which to end disassembling."}, { LLDB_OPT_SET_2, true, "name", 'n', required_argument, NULL, CommandCompletions::eSymbolCompletion, eArgTypeFunctionName, "Disassemble entire contents of the given function name."}, { LLDB_OPT_SET_3, true, "current-frame", 'f', no_argument, NULL, 0, eArgTypeNone, "Disassemble entire contents of the current frame's function."}, { 0, false, NULL, 0, 0, NULL, 0, eArgTypeNone, NULL } }; //------------------------------------------------------------------------- // CommandObjectDisassemble //------------------------------------------------------------------------- CommandObjectDisassemble::CommandObjectDisassemble (CommandInterpreter &interpreter) : CommandObject (interpreter, "disassemble", "Disassemble bytes in the current function, or elsewhere in the executable program as specified by the user.", "disassemble [<cmd-options>]") { } CommandObjectDisassemble::~CommandObjectDisassemble() { } bool CommandObjectDisassemble::Execute ( Args& command, CommandReturnObject &result ) { Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); if (target == NULL) { result.AppendError ("invalid target, set executable file using 'file' command"); result.SetStatus (eReturnStatusFailed); return false; } ArchSpec arch(target->GetArchitecture()); if (!arch.IsValid()) { result.AppendError ("target needs valid architecure in order to be able to disassemble"); result.SetStatus (eReturnStatusFailed); return false; } Disassembler *disassembler = Disassembler::FindPlugin(arch); if (disassembler == NULL) { result.AppendErrorWithFormat ("Unable to find Disassembler plug-in for %s architecture.\n", arch.AsCString()); result.SetStatus (eReturnStatusFailed); return false; } result.SetStatus (eReturnStatusSuccessFinishResult); if (command.GetArgumentCount() != 0) { result.AppendErrorWithFormat ("\"disassemble\" arguments are specified as options.\n"); GetOptions()->GenerateOptionUsage (m_interpreter, result.GetErrorStream(), this); result.SetStatus (eReturnStatusFailed); return false; } ExecutionContext exe_ctx(m_interpreter.GetDebugger().GetExecutionContext()); if (m_options.show_mixed && m_options.num_lines_context == 0) m_options.num_lines_context = 1; if (!m_options.m_func_name.empty()) { ConstString name(m_options.m_func_name.c_str()); if (Disassembler::Disassemble (m_interpreter.GetDebugger(), arch, exe_ctx, name, NULL, // Module * m_options.show_mixed ? m_options.num_lines_context : 0, m_options.show_bytes, result.GetOutputStream())) { result.SetStatus (eReturnStatusSuccessFinishResult); } else { result.AppendErrorWithFormat ("Unable to find symbol with name '%s'.\n", name.GetCString()); result.SetStatus (eReturnStatusFailed); } } else { AddressRange range; if (m_options.m_start_addr != LLDB_INVALID_ADDRESS) { range.GetBaseAddress().SetOffset (m_options.m_start_addr); if (m_options.m_end_addr != LLDB_INVALID_ADDRESS) { if (m_options.m_end_addr < m_options.m_start_addr) { result.AppendErrorWithFormat ("End address before start address.\n"); result.SetStatus (eReturnStatusFailed); return false; } range.SetByteSize (m_options.m_end_addr - m_options.m_start_addr); } else range.SetByteSize (DEFAULT_DISASM_BYTE_SIZE); } else { // The default action is to disassemble the current frame function. if (exe_ctx.frame) { // SymbolContext sc(exe_ctx.frame->GetSymbolContext(eSymbolContextFunction | eSymbolContextSymbol)); SymbolContext sc(exe_ctx.frame->GetSymbolContext (eSymbolContextEverything)); ArchVolatileRegs *vr = ArchVolatileRegs::FindPlugin (exe_ctx.target->GetArchitecture()); Address pc = exe_ctx.frame->GetFrameCodeAddress(); FuncUnwindersSP fu = pc.GetModule()->GetObjectFile()->GetUnwindTable().GetFuncUnwindersContainingAddress (pc, sc); if (fu != NULL) { Address first_non_prologue_insn = fu->GetFirstNonPrologueInsn (*exe_ctx.target); UnwindPlan *up = fu->GetUnwindPlanAtCallSite(); Stream *s = &result.GetOutputStream(); if (up) { s->Printf ("\nJSMDEBUG: unwind plan at call site (from eh_frame)\n"); up->Dump (result.GetOutputStream(), &exe_ctx.frame->GetThread()); } else { result.GetOutputStream().Printf("No UnwindPlanAtCallSite available.\n"); } up = fu->GetUnwindPlanAtNonCallSite(exe_ctx.frame->GetThread()); s->Printf ("\nJSMDEBUG: unwind plan at non-call site (from disassembly)\n"); up->Dump (result.GetOutputStream(), &exe_ctx.frame->GetThread()); up = fu->GetUnwindPlanFastUnwind(exe_ctx.frame->GetThread()); if (up) { s->Printf ("\nJSMDEBUG: fast unwind plan\n"); up->Dump (result.GetOutputStream(), &exe_ctx.frame->GetThread()); } up = fu->GetUnwindPlanArchitectureDefault(exe_ctx.frame->GetThread()); if (up) { s->Printf ("\nJSMDEBUG: architectural default unwind plan\n"); up->Dump (result.GetOutputStream(), &exe_ctx.frame->GetThread()); } } if (sc.function) range = sc.function->GetAddressRange(); else if (sc.symbol && sc.symbol->GetAddressRangePtr()) range = *sc.symbol->GetAddressRangePtr(); else range.GetBaseAddress() = exe_ctx.frame->GetFrameCodeAddress(); } else { result.AppendError ("invalid frame"); result.SetStatus (eReturnStatusFailed); return false; } } if (range.GetByteSize() == 0) range.SetByteSize(DEFAULT_DISASM_BYTE_SIZE); if (Disassembler::Disassemble (m_interpreter.GetDebugger(), arch, exe_ctx, range, m_options.show_mixed ? m_options.num_lines_context : 0, m_options.show_bytes, result.GetOutputStream())) { result.SetStatus (eReturnStatusSuccessFinishResult); } else { result.AppendErrorWithFormat ("Failed to disassemble memory at 0x%8.8llx.\n", m_options.m_start_addr); result.SetStatus (eReturnStatusFailed); } } return result.Succeeded(); } <commit_msg>Revert last checking to CommandObjectDisassemble.cpp; that was some diagnostic test code I was using while debugging the native unwinder and didn't mean to check in.<commit_after>//===-- CommandObjectDisassemble.cpp ----------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "CommandObjectDisassemble.h" // C Includes // C++ Includes // Other libraries and framework includes // Project includes #include "lldb/Core/AddressRange.h" #include "lldb/Interpreter/Args.h" #include "lldb/Interpreter/CommandCompletions.h" #include "lldb/Interpreter/CommandInterpreter.h" #include "lldb/Interpreter/CommandReturnObject.h" #include "lldb/Core/Disassembler.h" #include "lldb/Interpreter/Options.h" #include "lldb/Core/SourceManager.h" #include "lldb/Target/StackFrame.h" #include "lldb/Symbol/Symbol.h" #include "lldb/Target/Process.h" #include "lldb/Target/Target.h" #define DEFAULT_DISASM_BYTE_SIZE 32 using namespace lldb; using namespace lldb_private; CommandObjectDisassemble::CommandOptions::CommandOptions () : Options(), m_func_name(), m_start_addr(), m_end_addr () { ResetOptionValues(); } CommandObjectDisassemble::CommandOptions::~CommandOptions () { } Error CommandObjectDisassemble::CommandOptions::SetOptionValue (int option_idx, const char *option_arg) { Error error; char short_option = (char) m_getopt_table[option_idx].val; switch (short_option) { case 'm': show_mixed = true; break; case 'c': num_lines_context = Args::StringToUInt32(option_arg, 0, 0); break; case 'b': show_bytes = true; break; case 's': m_start_addr = Args::StringToUInt64(optarg, LLDB_INVALID_ADDRESS, 0); if (m_start_addr == LLDB_INVALID_ADDRESS) m_start_addr = Args::StringToUInt64(optarg, LLDB_INVALID_ADDRESS, 16); if (m_start_addr == LLDB_INVALID_ADDRESS) error.SetErrorStringWithFormat ("Invalid start address string '%s'.\n", optarg); break; case 'e': m_end_addr = Args::StringToUInt64(optarg, LLDB_INVALID_ADDRESS, 0); if (m_end_addr == LLDB_INVALID_ADDRESS) m_end_addr = Args::StringToUInt64(optarg, LLDB_INVALID_ADDRESS, 16); if (m_end_addr == LLDB_INVALID_ADDRESS) error.SetErrorStringWithFormat ("Invalid end address string '%s'.\n", optarg); break; case 'n': m_func_name = option_arg; break; case 'r': raw = true; break; case 'f': // The default action is to disassemble the function for the current frame. // There's no need to set any flag. break; default: error.SetErrorStringWithFormat("Unrecognized short option '%c'.\n", short_option); break; } return error; } void CommandObjectDisassemble::CommandOptions::ResetOptionValues () { Options::ResetOptionValues(); show_mixed = false; show_bytes = false; num_lines_context = 0; m_func_name.clear(); m_start_addr = LLDB_INVALID_ADDRESS; m_end_addr = LLDB_INVALID_ADDRESS; raw = false; } const lldb::OptionDefinition* CommandObjectDisassemble::CommandOptions::GetDefinitions () { return g_option_table; } lldb::OptionDefinition CommandObjectDisassemble::CommandOptions::g_option_table[] = { { LLDB_OPT_SET_ALL, false, "bytes", 'b', no_argument, NULL, 0, eArgTypeNone, "Show opcode bytes when disassembling."}, { LLDB_OPT_SET_ALL, false, "context", 'c', required_argument, NULL, 0, eArgTypeNumLines, "Number of context lines of source to show."}, { LLDB_OPT_SET_ALL, false, "mixed", 'm', no_argument, NULL, 0, eArgTypeNone, "Enable mixed source and assembly display."}, { LLDB_OPT_SET_ALL, false, "raw", 'r', no_argument, NULL, 0, eArgTypeNone, "Print raw disassembly with no symbol information."}, { LLDB_OPT_SET_1, true, "start-address", 's', required_argument, NULL, 0, eArgTypeStartAddress, "Address at which to start disassembling."}, { LLDB_OPT_SET_1, false, "end-address", 'e', required_argument, NULL, 0, eArgTypeEndAddress, "Address at which to end disassembling."}, { LLDB_OPT_SET_2, true, "name", 'n', required_argument, NULL, CommandCompletions::eSymbolCompletion, eArgTypeFunctionName, "Disassemble entire contents of the given function name."}, { LLDB_OPT_SET_3, true, "current-frame", 'f', no_argument, NULL, 0, eArgTypeNone, "Disassemble entire contents of the current frame's function."}, { 0, false, NULL, 0, 0, NULL, 0, eArgTypeNone, NULL } }; //------------------------------------------------------------------------- // CommandObjectDisassemble //------------------------------------------------------------------------- CommandObjectDisassemble::CommandObjectDisassemble (CommandInterpreter &interpreter) : CommandObject (interpreter, "disassemble", "Disassemble bytes in the current function, or elsewhere in the executable program as specified by the user.", "disassemble [<cmd-options>]") { } CommandObjectDisassemble::~CommandObjectDisassemble() { } bool CommandObjectDisassemble::Execute ( Args& command, CommandReturnObject &result ) { Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); if (target == NULL) { result.AppendError ("invalid target, set executable file using 'file' command"); result.SetStatus (eReturnStatusFailed); return false; } ArchSpec arch(target->GetArchitecture()); if (!arch.IsValid()) { result.AppendError ("target needs valid architecure in order to be able to disassemble"); result.SetStatus (eReturnStatusFailed); return false; } Disassembler *disassembler = Disassembler::FindPlugin(arch); if (disassembler == NULL) { result.AppendErrorWithFormat ("Unable to find Disassembler plug-in for %s architecture.\n", arch.AsCString()); result.SetStatus (eReturnStatusFailed); return false; } result.SetStatus (eReturnStatusSuccessFinishResult); if (command.GetArgumentCount() != 0) { result.AppendErrorWithFormat ("\"disassemble\" arguments are specified as options.\n"); GetOptions()->GenerateOptionUsage (m_interpreter, result.GetErrorStream(), this); result.SetStatus (eReturnStatusFailed); return false; } ExecutionContext exe_ctx(m_interpreter.GetDebugger().GetExecutionContext()); if (m_options.show_mixed && m_options.num_lines_context == 0) m_options.num_lines_context = 1; if (!m_options.m_func_name.empty()) { ConstString name(m_options.m_func_name.c_str()); if (Disassembler::Disassemble (m_interpreter.GetDebugger(), arch, exe_ctx, name, NULL, // Module * m_options.show_mixed ? m_options.num_lines_context : 0, m_options.show_bytes, result.GetOutputStream())) { result.SetStatus (eReturnStatusSuccessFinishResult); } else { result.AppendErrorWithFormat ("Unable to find symbol with name '%s'.\n", name.GetCString()); result.SetStatus (eReturnStatusFailed); } } else { AddressRange range; if (m_options.m_start_addr != LLDB_INVALID_ADDRESS) { range.GetBaseAddress().SetOffset (m_options.m_start_addr); if (m_options.m_end_addr != LLDB_INVALID_ADDRESS) { if (m_options.m_end_addr < m_options.m_start_addr) { result.AppendErrorWithFormat ("End address before start address.\n"); result.SetStatus (eReturnStatusFailed); return false; } range.SetByteSize (m_options.m_end_addr - m_options.m_start_addr); } else range.SetByteSize (DEFAULT_DISASM_BYTE_SIZE); } else { // The default action is to disassemble the current frame function. if (exe_ctx.frame) { SymbolContext sc(exe_ctx.frame->GetSymbolContext(eSymbolContextFunction | eSymbolContextSymbol)); if (sc.function) range = sc.function->GetAddressRange(); else if (sc.symbol && sc.symbol->GetAddressRangePtr()) range = *sc.symbol->GetAddressRangePtr(); else range.GetBaseAddress() = exe_ctx.frame->GetFrameCodeAddress(); } else { result.AppendError ("invalid frame"); result.SetStatus (eReturnStatusFailed); return false; } } if (range.GetByteSize() == 0) range.SetByteSize(DEFAULT_DISASM_BYTE_SIZE); if (Disassembler::Disassemble (m_interpreter.GetDebugger(), arch, exe_ctx, range, m_options.show_mixed ? m_options.num_lines_context : 0, m_options.show_bytes, result.GetOutputStream())) { result.SetStatus (eReturnStatusSuccessFinishResult); } else { result.AppendErrorWithFormat ("Failed to disassemble memory at 0x%8.8llx.\n", m_options.m_start_addr); result.SetStatus (eReturnStatusFailed); } } return result.Succeeded(); } <|endoftext|>
<commit_before>/* * ssl-server.cpp * * Created on: Dec 10, 2015 * Author: zmij */ #include <iostream> #include <string> #include <functional> #include <boost/asio.hpp> #include <boost/asio/ssl.hpp> #include <boost/asio/ip/address.hpp> #include <boost/program_options.hpp> namespace boost { namespace asio { namespace ip { std::istream& operator >> (std::istream& is, address& val) { std::istream::sentry s(is); if (s) { std::string str; if (is >> str) { try { val = address::from_string(str); } catch (boost::system::error_code const& ec) { is.setstate(std::ios_base::badbit); } } } return is; } } // namespace ip } // namespace asio } // namespace boost typedef boost::asio::ssl::stream< boost::asio::ip::tcp::socket > ssl_socket_type; enum { max_length = 1024 }; class session { public: typedef boost::asio::io_service io_service; public: session(io_service& svc, boost::asio::ssl::context& ctx) : socket_(svc, ctx) { socket_.set_verify_mode(boost::asio::ssl::verify_peer | boost::asio::ssl::verify_fail_if_no_peer_cert); socket_.set_verify_callback( std::bind(&session::verify_certificate, this, std::placeholders::_1, std::placeholders::_2) ); } ssl_socket_type::lowest_layer_type& socket() { return socket_.lowest_layer(); } void start() { socket_.async_handshake(boost::asio::ssl::stream_base::server, std::bind(&session::handle_handshake, this, std::placeholders::_1)); } private: bool verify_certificate(bool preverified, boost::asio::ssl::verify_context& ctx) { char subject_name[256]; X509* cert = X509_STORE_CTX_get_current_cert(ctx.native_handle()); X509_NAME_oneline(X509_get_subject_name(cert), subject_name, 256); std::cout << "Verifying " << subject_name << "\n"; return preverified; } void handle_handshake(boost::system::error_code const& ec) { if (!ec) { socket_.async_read_some(boost::asio::buffer(data_, max_length), std::bind(&session::handle_read, this, std::placeholders::_1, std::placeholders::_2)); } else { std::cerr << "Handshake failed: " << ec.message() << "\n"; delete this; } } void handle_read(boost::system::error_code const& ec, size_t bytes_transferred) { if (!ec) { boost::asio::async_write( socket_, boost::asio::buffer(data_, bytes_transferred), std::bind(&session::handle_write, this, std::placeholders::_1, std::placeholders::_2)); } else { std::cerr << "Read failed: " << ec.message() << "\n"; delete this; } } void handle_write(boost::system::error_code const& ec, size_t bytes_transferred) { if (!ec) { socket_.async_read_some(boost::asio::buffer(data_, max_length), std::bind(&session::handle_read, this, std::placeholders::_1, std::placeholders::_2)); } else { std::cerr << "Write failed: " << ec.message() << "\n"; delete this; } } private: ssl_socket_type socket_; char data_[ max_length ]; }; class server { public: typedef boost::asio::io_service io_service; public: server(io_service& svc, boost::asio::ip::tcp::endpoint const& endpoint, std::string const& verify_file, std::string const& cert_file, std::string const& key_file) : io_service_(svc), acceptor_(svc, endpoint), context_(boost::asio::ssl::context::sslv23) { context_.set_options( boost::asio::ssl::context::default_workarounds | boost::asio::ssl::context::no_sslv2 | boost::asio::ssl::context::single_dh_use ); if (!verify_file.empty()) { context_.load_verify_file(verify_file); } context_.use_certificate_chain_file(cert_file); context_.use_private_key_file(key_file, boost::asio::ssl::context::pem); //context_.use_tmp_dh_file("/tmp/dh512.pem"); start_accept(); } private: void start_accept() { session* new_session = new session(io_service_, context_); acceptor_.async_accept(new_session->socket(), std::bind(&server::handle_accept, this, new_session, std::placeholders::_1)); } void handle_accept(session* new_session, boost::system::error_code const& ec) { if (!ec) { new_session->start(); } else { std::cerr << "Failed to accept: " << ec.message() << "\n"; delete new_session; } start_accept(); } private: io_service& io_service_; boost::asio::ip::tcp::acceptor acceptor_; boost::asio::ssl::context context_; }; int main(int argc, char* argv[]) { try { namespace po = boost::program_options; boost::asio::ip::address bind_addr; unsigned short bind_port = 0; std::string verify_file; std::string cert_file; std::string key_file; po::options_description options("SSL server options"); options.add_options() ("bind-address,a", po::value< boost::asio::ip::address >(&bind_addr), "Bind to interface") ("bind-port,p", po::value< unsigned short >(&bind_port), "Bind to port") ("verify-file,v", po::value< std::string >(&verify_file), "Verify file") ("cert-file,c", po::value< std::string >(&cert_file), "Certificate file") ("key-file,k", po::value< std::string >(&key_file), "Private key file") ; po::variables_map vm; po::store(po::parse_command_line(argc, argv, options), vm); po::notify(vm); if (cert_file.empty() || key_file.empty()) { std::cerr << "No certificate or private key file\n" << options << "\n"; return 2; } std::cerr << "Binding to " << bind_addr.to_string() << ":" << bind_port << "\n"; boost::asio::ip::tcp::endpoint endpoint(bind_addr, bind_port); boost::asio::io_service io_service; server s(io_service, endpoint, verify_file, cert_file, key_file); io_service.run(); } catch (std::exception const& e) { std::cerr << "Exception: " << e.what() << "\n"; return 1; } return 0; } <commit_msg>Try out the SO_REUSEPORT socket option. Works on Mac OS X<commit_after>/* * ssl-server.cpp * * Created on: Dec 10, 2015 * Author: zmij */ #include <iostream> #include <string> #include <functional> #include <boost/asio.hpp> #include <boost/asio/ssl.hpp> #include <boost/asio/ip/address.hpp> #include <boost/program_options.hpp> namespace boost { namespace asio { namespace ip { std::istream& operator >> (std::istream& is, address& val) { std::istream::sentry s(is); if (s) { std::string str; if (is >> str) { try { val = address::from_string(str); } catch (boost::system::error_code const& ec) { is.setstate(std::ios_base::badbit); } } } return is; } } // namespace ip } // namespace asio } // namespace boost #ifdef SO_REUSEPORT namespace test { typedef boost::asio::detail::socket_option::boolean< BOOST_ASIO_OS_DEF(SOL_SOCKET), SO_REUSEPORT > reuse_port; } // namespace test #endif typedef boost::asio::ssl::stream< boost::asio::ip::tcp::socket > ssl_socket_type; enum { max_length = 1024 }; class session { public: typedef boost::asio::io_service io_service; public: session(io_service& svc, boost::asio::ssl::context& ctx) : socket_(svc, ctx) { socket_.set_verify_mode(boost::asio::ssl::verify_peer | boost::asio::ssl::verify_fail_if_no_peer_cert); socket_.set_verify_callback( std::bind(&session::verify_certificate, this, std::placeholders::_1, std::placeholders::_2) ); } ssl_socket_type::lowest_layer_type& socket() { return socket_.lowest_layer(); } void start() { socket_.async_handshake(boost::asio::ssl::stream_base::server, std::bind(&session::handle_handshake, this, std::placeholders::_1)); } private: bool verify_certificate(bool preverified, boost::asio::ssl::verify_context& ctx) { char subject_name[256]; X509* cert = X509_STORE_CTX_get_current_cert(ctx.native_handle()); X509_NAME_oneline(X509_get_subject_name(cert), subject_name, 256); std::cout << "Verifying " << subject_name << "\n"; return preverified; } void handle_handshake(boost::system::error_code const& ec) { if (!ec) { socket_.async_read_some(boost::asio::buffer(data_, max_length), std::bind(&session::handle_read, this, std::placeholders::_1, std::placeholders::_2)); } else { std::cerr << "Handshake failed: " << ec.message() << "\n"; delete this; } } void handle_read(boost::system::error_code const& ec, size_t bytes_transferred) { if (!ec) { boost::asio::async_write( socket_, boost::asio::buffer(data_, bytes_transferred), std::bind(&session::handle_write, this, std::placeholders::_1, std::placeholders::_2)); } else { std::cerr << "Read failed: " << ec.message() << "\n"; delete this; } } void handle_write(boost::system::error_code const& ec, size_t bytes_transferred) { if (!ec) { socket_.async_read_some(boost::asio::buffer(data_, max_length), std::bind(&session::handle_read, this, std::placeholders::_1, std::placeholders::_2)); } else { std::cerr << "Write failed: " << ec.message() << "\n"; delete this; } } private: ssl_socket_type socket_; char data_[ max_length ]; }; class server { public: typedef boost::asio::io_service io_service; typedef boost::asio::ip::tcp::acceptor acceptor; public: server(io_service& svc, boost::asio::ip::tcp::endpoint const& endpoint, std::string const& verify_file, std::string const& cert_file, std::string const& key_file) : io_service_(svc), acceptor_(svc), context_(boost::asio::ssl::context::sslv23) { context_.set_options( boost::asio::ssl::context::default_workarounds | boost::asio::ssl::context::no_sslv2 | boost::asio::ssl::context::single_dh_use ); if (!verify_file.empty()) { context_.load_verify_file(verify_file); } context_.use_certificate_chain_file(cert_file); context_.use_private_key_file(key_file, boost::asio::ssl::context::pem); acceptor_.open(endpoint.protocol()); #ifdef SO_REUSEPORT acceptor_.set_option(test::reuse_port(true)); std::cerr << "Reuse port: 1\n"; #endif acceptor_.bind(endpoint); acceptor_.listen(); start_accept(); } private: void start_accept() { session* new_session = new session(io_service_, context_); acceptor_.async_accept(new_session->socket(), std::bind(&server::handle_accept, this, new_session, std::placeholders::_1)); } void handle_accept(session* new_session, boost::system::error_code const& ec) { if (!ec) { new_session->start(); } else { std::cerr << "Failed to accept: " << ec.message() << "\n"; delete new_session; } start_accept(); } private: io_service& io_service_; acceptor acceptor_; boost::asio::ssl::context context_; }; int main(int argc, char* argv[]) { try { namespace po = boost::program_options; boost::asio::ip::address bind_addr; unsigned short bind_port = 0; std::string verify_file; std::string cert_file; std::string key_file; po::options_description options("SSL server options"); options.add_options() ("help,h", "Produce help message") ("bind-address,a", po::value< boost::asio::ip::address >(&bind_addr) ->default_value(boost::asio::ip::address_v4{}), "Bind to interface") ("bind-port,p", po::value< unsigned short >(&bind_port)->default_value(0), "Bind to port") ("verify-file,v", po::value< std::string >(&verify_file), "Verify file") ("cert-file,c", po::value< std::string >(&cert_file)->required(), "Certificate file") ("key-file,k", po::value< std::string >(&key_file)->required(), "Private key file") ; po::variables_map vm; po::store(po::parse_command_line(argc, argv, options), vm); if (vm.count("help")) { std::cerr << "Usage:\n" << options << "\n"; return 0; } po::notify(vm); if (cert_file.empty() || key_file.empty()) { std::cerr << "No certificate or private key file\n" << options << "\n"; return 2; } std::cerr << "Binding to " << bind_addr.to_string() << ":" << bind_port << "\n"; boost::asio::ip::tcp::endpoint endpoint(bind_addr, bind_port); boost::asio::io_service io_service; server s(io_service, endpoint, verify_file, cert_file, key_file); io_service.run(); } catch (std::exception const& e) { std::cerr << "Exception: " << e.what() << "\n"; return 1; } return 0; } <|endoftext|>
<commit_before>/* This file is part of the KDE project Copyright (C) 2008 Dominik Haumann <dhaumann kde org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "katefindoptions.h" #include <KConfigGroup> KateFindInFilesOptions::KateFindInFilesOptions() { } KateFindInFilesOptions::~KateFindInFilesOptions() { } KateFindInFilesOptions::KateFindInFilesOptions(const KateFindInFilesOptions& copy) { *this = copy; } KateFindInFilesOptions& KateFindInFilesOptions::operator=(const KateFindInFilesOptions& copy) { m_recursive = copy.m_recursive; m_casesensitive = copy.m_casesensitive; m_regexp = copy.m_regexp; m_followDirectorySymlinks = copy.m_followDirectorySymlinks; m_includeHiddenFiles = copy.m_includeHiddenFiles; // only the global models are used } KateFindInFilesOptions& KateFindInFilesOptions::self() { static KateFindInFilesOptions fifo; return fifo; } void KateFindInFilesOptions::load(const KConfigGroup& config) { if (this != &self()) { self().load(config); return; } // now restore new session settings m_searchItems.setStringList(config.readEntry("LastSearchItems", QStringList())); m_searchPaths.setStringList(config.readEntry("LastSearchPaths", QStringList())); m_searchFilters.setStringList(config.readEntry("LastSearchFiles", QStringList())); // sane default values if (m_searchFilters.rowCount() == 0) { // if there are no entries, most probably the first Kate start. // Initialize with default values. QStringList stringList; stringList << "*" << "*.h,*.hxx,*.cpp,*.cc,*.C,*.cxx,*.idl,*.c" << "*.cpp,*.cc,*.C,*.cxx,*.c" << "*.h,*.hxx,*.idl"; m_searchFilters.setStringList(stringList); } m_casesensitive = config.readEntry("CaseSensitive", true); m_recursive = config.readEntry("Recursive", true); m_regexp = config.readEntry("RegExp", false); m_followDirectorySymlinks = config.readEntry("FollowDirectorySymlinks", false); m_includeHiddenFiles = config.readEntry("IncludeHiddenFiles", false); } void KateFindInFilesOptions::save(KConfigGroup& config) { if (this != &self()) { self().save(config); return; } // first remove duplicates, as setDuplicatesEnabled does not work for QComboBox with Model QStringList stringList = m_searchItems.stringList(); if (stringList.removeDuplicates() > 0) m_searchItems.setStringList(stringList); stringList = m_searchPaths.stringList(); if (stringList.removeDuplicates() > 0) m_searchPaths.setStringList(stringList); stringList = m_searchFilters.stringList(); if (stringList.removeDuplicates() > 0) m_searchFilters.setStringList(stringList); // now save config.writeEntry("LastSearchItems", m_searchItems.stringList()); config.writeEntry("LastSearchPaths", m_searchPaths.stringList()); config.writeEntry("LastSearchFiles", m_searchFilters.stringList()); config.writeEntry("Recursive", m_recursive); config.writeEntry("CaseSensitive", m_casesensitive); config.writeEntry("RegExp", m_regexp); config.writeEntry("FollowDirectorySymlinks", m_followDirectorySymlinks); config.writeEntry("IncludeHiddenFiles", m_includeHiddenFiles); } QStringListModel* KateFindInFilesOptions::searchItems() { if (this != &self()) return self().searchItems(); return &m_searchItems; } QStringListModel* KateFindInFilesOptions::searchPaths() { if (this != &self()) return self().searchPaths(); return &m_searchPaths; } QStringListModel* KateFindInFilesOptions::searchFilters() { if (this != &self()) return self().searchFilters(); return &m_searchFilters; } bool KateFindInFilesOptions::recursive() const { return m_recursive; } void KateFindInFilesOptions::setRecursive(bool recursive) { m_recursive = recursive; if (this != &self()) self().setRecursive(recursive); } bool KateFindInFilesOptions::caseSensitive() const { return m_casesensitive; } void KateFindInFilesOptions::setCaseSensitive(bool casesensitive) { m_casesensitive = casesensitive; if (this != &self()) self().setCaseSensitive(casesensitive); } bool KateFindInFilesOptions::regExp() const { return m_regexp; } void KateFindInFilesOptions::setRegExp(bool regexp) { m_regexp = regexp; if (this != &self()) self().setRegExp(regexp); } bool KateFindInFilesOptions::followDirectorySymlinks() const { return m_followDirectorySymlinks; } void KateFindInFilesOptions::setFollowDirectorySymlinks(bool follow) { m_followDirectorySymlinks = follow; if (this != &self()) self().setFollowDirectorySymlinks(follow); } bool KateFindInFilesOptions::includeHiddenFiles() const { return m_includeHiddenFiles; } void KateFindInFilesOptions::setIncludeHiddenFiles(bool include) { m_includeHiddenFiles = include; if (this != &self()) self().setIncludeHiddenFiles(include); } // kate: space-indent on; indent-width 2; replace-tabs on; <commit_msg>dhaumann: limit stringlist entry count to 15<commit_after>/* This file is part of the KDE project Copyright (C) 2008 Dominik Haumann <dhaumann kde org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "katefindoptions.h" #include <KConfigGroup> KateFindInFilesOptions::KateFindInFilesOptions() { } KateFindInFilesOptions::~KateFindInFilesOptions() { } KateFindInFilesOptions::KateFindInFilesOptions(const KateFindInFilesOptions& copy) { *this = copy; } KateFindInFilesOptions& KateFindInFilesOptions::operator=(const KateFindInFilesOptions& copy) { m_recursive = copy.m_recursive; m_casesensitive = copy.m_casesensitive; m_regexp = copy.m_regexp; m_followDirectorySymlinks = copy.m_followDirectorySymlinks; m_includeHiddenFiles = copy.m_includeHiddenFiles; // only the global models are used } KateFindInFilesOptions& KateFindInFilesOptions::self() { static KateFindInFilesOptions fifo; return fifo; } void KateFindInFilesOptions::load(const KConfigGroup& config) { if (this != &self()) { self().load(config); return; } // now restore new session settings m_searchItems.setStringList(config.readEntry("LastSearchItems", QStringList())); m_searchPaths.setStringList(config.readEntry("LastSearchPaths", QStringList())); m_searchFilters.setStringList(config.readEntry("LastSearchFiles", QStringList())); // sane default values if (m_searchFilters.rowCount() == 0) { // if there are no entries, most probably the first Kate start. // Initialize with default values. QStringList stringList; stringList << "*" << "*.h,*.hxx,*.cpp,*.cc,*.C,*.cxx,*.idl,*.c" << "*.cpp,*.cc,*.C,*.cxx,*.c" << "*.h,*.hxx,*.idl"; m_searchFilters.setStringList(stringList); } m_casesensitive = config.readEntry("CaseSensitive", true); m_recursive = config.readEntry("Recursive", true); m_regexp = config.readEntry("RegExp", false); m_followDirectorySymlinks = config.readEntry("FollowDirectorySymlinks", false); m_includeHiddenFiles = config.readEntry("IncludeHiddenFiles", false); } void KateFindInFilesOptions::save(KConfigGroup& config) { if (this != &self()) { self().save(config); return; } // first remove duplicates, as setDuplicatesEnabled does not work for QComboBox with Model // further, limit count of entries to 15 QStringList stringList = m_searchItems.stringList(); stringList.removeDuplicates(); if (stringList.count() > 15) stringList.erase(stringList.begin() + 15, stringList.end()); m_searchItems.setStringList(stringList); stringList = m_searchPaths.stringList(); stringList.removeDuplicates(); if (stringList.count() > 15) stringList.erase(stringList.begin() + 15, stringList.end()); m_searchPaths.setStringList(stringList); stringList = m_searchFilters.stringList(); stringList.removeDuplicates(); if (stringList.count() > 15) stringList.erase(stringList.begin() + 15, stringList.end()); m_searchFilters.setStringList(stringList); // now save config.writeEntry("LastSearchItems", m_searchItems.stringList()); config.writeEntry("LastSearchPaths", m_searchPaths.stringList()); config.writeEntry("LastSearchFiles", m_searchFilters.stringList()); config.writeEntry("Recursive", m_recursive); config.writeEntry("CaseSensitive", m_casesensitive); config.writeEntry("RegExp", m_regexp); config.writeEntry("FollowDirectorySymlinks", m_followDirectorySymlinks); config.writeEntry("IncludeHiddenFiles", m_includeHiddenFiles); } QStringListModel* KateFindInFilesOptions::searchItems() { if (this != &self()) return self().searchItems(); return &m_searchItems; } QStringListModel* KateFindInFilesOptions::searchPaths() { if (this != &self()) return self().searchPaths(); return &m_searchPaths; } QStringListModel* KateFindInFilesOptions::searchFilters() { if (this != &self()) return self().searchFilters(); return &m_searchFilters; } bool KateFindInFilesOptions::recursive() const { return m_recursive; } void KateFindInFilesOptions::setRecursive(bool recursive) { m_recursive = recursive; if (this != &self()) self().setRecursive(recursive); } bool KateFindInFilesOptions::caseSensitive() const { return m_casesensitive; } void KateFindInFilesOptions::setCaseSensitive(bool casesensitive) { m_casesensitive = casesensitive; if (this != &self()) self().setCaseSensitive(casesensitive); } bool KateFindInFilesOptions::regExp() const { return m_regexp; } void KateFindInFilesOptions::setRegExp(bool regexp) { m_regexp = regexp; if (this != &self()) self().setRegExp(regexp); } bool KateFindInFilesOptions::followDirectorySymlinks() const { return m_followDirectorySymlinks; } void KateFindInFilesOptions::setFollowDirectorySymlinks(bool follow) { m_followDirectorySymlinks = follow; if (this != &self()) self().setFollowDirectorySymlinks(follow); } bool KateFindInFilesOptions::includeHiddenFiles() const { return m_includeHiddenFiles; } void KateFindInFilesOptions::setIncludeHiddenFiles(bool include) { m_includeHiddenFiles = include; if (this != &self()) self().setIncludeHiddenFiles(include); } // kate: space-indent on; indent-width 2; replace-tabs on; <|endoftext|>
<commit_before>#include "gl/TextureShader.h" namespace chr { namespace gl { TextureShader textureShader; const char *TextureShader::vertexShaderSource = R"( attribute vec2 a_position; attribute vec2 a_coord; attribute vec4 a_color; uniform mat4 u_mvp_matrix; varying vec2 v_coord; varying vec4 v_color; void main() { v_coord = a_coord; v_color = a_color; gl_Position = u_mvp_matrix * vec4(a_position, 0, 1); } )"; const char *TextureShader::fragmentShaderSource = R"( #ifdef GL_ES precision mediump float; #endif uniform sampler2D u_sampler; varying vec2 v_coord; varying vec4 v_color; void main() { gl_FragColor = v_color * texture2D(u_sampler, v_coord); } )"; bool TextureShader::load() { if (!id) { ShaderProgram::load(vertexShaderSource, fragmentShaderSource); positionLocation = glGetAttribLocation(id, "a_position"); coordLocation = glGetAttribLocation(id, "a_coord"); colorLocation = glGetAttribLocation(id, "a_color"); samplerLocation = glGetUniformLocation(id, "u_sampler"); matrixLocation = glGetUniformLocation(id, "u_mvp_matrix"); } return bool(id); } bool TextureShader::use() { if (load()) { glUseProgram(id); return true; } return false; } } } <commit_msg>FIXING TextureShader: WAS LIMITED TO 2D VERTICES<commit_after>#include "gl/TextureShader.h" namespace chr { namespace gl { TextureShader textureShader; const char *TextureShader::vertexShaderSource = R"( attribute vec3 a_position; attribute vec2 a_coord; attribute vec4 a_color; uniform mat4 u_mvp_matrix; varying vec2 v_coord; varying vec4 v_color; void main() { v_coord = a_coord; v_color = a_color; gl_Position = u_mvp_matrix * vec4(a_position, 1); } )"; const char *TextureShader::fragmentShaderSource = R"( #ifdef GL_ES precision mediump float; #endif uniform sampler2D u_sampler; varying vec2 v_coord; varying vec4 v_color; void main() { gl_FragColor = v_color * texture2D(u_sampler, v_coord); } )"; bool TextureShader::load() { if (!id) { ShaderProgram::load(vertexShaderSource, fragmentShaderSource); positionLocation = glGetAttribLocation(id, "a_position"); coordLocation = glGetAttribLocation(id, "a_coord"); colorLocation = glGetAttribLocation(id, "a_color"); samplerLocation = glGetUniformLocation(id, "u_sampler"); matrixLocation = glGetUniformLocation(id, "u_mvp_matrix"); } return bool(id); } bool TextureShader::use() { if (load()) { glUseProgram(id); return true; } return false; } } } <|endoftext|>
<commit_before>#include "text/fontContext.h" #include "log.h" #include "platform.h" #define SDF_IMPLEMENTATION #include "sdf.h" #include <memory> #include <regex> #define SDF_WIDTH 6 #define MIN_LINE_WIDTH 4 namespace Tangram { const std::vector<float> FontContext::s_fontRasterSizes = { 16, 28, 40 }; FontContext::FontContext(std::shared_ptr<const Platform> _platform) : m_sdfRadius(SDF_WIDTH), m_atlas(*this, GlyphTexture::size, m_sdfRadius), m_batch(m_atlas, m_scratch), m_platform(_platform) {} void FontContext::setPixelScale(float _scale) { m_sdfRadius = SDF_WIDTH * _scale; } void FontContext::loadFonts() { auto fallbacks = m_platform->systemFontFallbacksHandle(); for (size_t i = 0; i < s_fontRasterSizes.size(); i++) { m_font[i] = m_alfons.addFont("default", s_fontRasterSizes[i]); } for (const auto& fallback : fallbacks) { if (!fallback.isValid()) { continue; } alfons::InputSource source; switch (fallback.tag) { case FontSourceHandle::FontPath: source = alfons::InputSource(fallback.fontPath.path()); break; case FontSourceHandle::FontName: source = alfons::InputSource(fallback.fontName, true); break; case FontSourceHandle::FontLoader: source = alfons::InputSource(fallback.fontLoader); break; case FontSourceHandle::None: default: return; } for (size_t i = 0; i < s_fontRasterSizes.size(); i++) { m_font[i]->addFace(m_alfons.addFontFace(source, s_fontRasterSizes[i])); } } } // Synchronized on m_mutex in layoutText(), called on tile-worker threads void FontContext::addTexture(alfons::AtlasID id, uint16_t width, uint16_t height) { std::lock_guard<std::mutex> lock(m_textureMutex); if (m_textures.size() == max_textures) { LOGE("Way too many glyph textures!"); return; } m_textures.push_back(std::make_unique<GlyphTexture>()); } // Synchronized on m_mutex in layoutText(), called on tile-worker threads void FontContext::addGlyph(alfons::AtlasID id, uint16_t gx, uint16_t gy, uint16_t gw, uint16_t gh, const unsigned char* src, uint16_t pad) { std::lock_guard<std::mutex> lock(m_textureMutex); if (id >= max_textures) { return; } auto texData = m_textures[id]->buffer(); auto& texture = m_textures[id]; size_t stride = GlyphTexture::size; size_t width = GlyphTexture::size; unsigned char* dst = &texData[(gx + pad) + (gy + pad) * stride]; for (size_t y = 0, pos = 0; y < gh; y++, pos += gw) { std::memcpy(dst + (y * stride), src + pos, gw); } dst = &texData[size_t(gx) + (size_t(gy) * width)]; gw += pad * 2; gh += pad * 2; size_t bytes = size_t(gw) * size_t(gh) * sizeof(float) * 3; if (m_sdfBuffer.size() < bytes) { m_sdfBuffer.resize(bytes); } sdfBuildDistanceFieldNoAlloc(dst, width, m_sdfRadius, dst, gw, gh, width, &m_sdfBuffer[0]); texture->setRowsDirty(gy, gh); } void FontContext::releaseAtlas(std::bitset<max_textures> _refs) { if (!_refs.any()) { return; } std::lock_guard<std::mutex> lock(m_textureMutex); for (size_t i = 0; i < m_textures.size(); i++) { if (_refs[i]) { m_atlasRefCount[i] -= 1; } } } void FontContext::updateTextures(RenderState& rs) { std::lock_guard<std::mutex> lock(m_textureMutex); for (auto& gt : m_textures) { gt->bind(rs, 0); } } void FontContext::bindTexture(RenderState& rs, alfons::AtlasID _id, GLuint _unit) { std::lock_guard<std::mutex> lock(m_textureMutex); m_textures[_id]->bind(rs, _unit); } bool FontContext::layoutText(TextStyle::Parameters& _params, const icu::UnicodeString& _text, std::vector<GlyphQuad>& _quads, std::bitset<max_textures>& _refs, glm::vec2& _size, TextRange& _textRanges) { std::lock_guard<std::mutex> lock(m_fontMutex); alfons::LineLayout line = m_shaper.shapeICU(_params.font, _text, MIN_LINE_WIDTH, _params.wordWrap ? _params.maxLineWidth : 0); if (line.missingGlyphs() || line.shapes().size() == 0) { // Nothing to do! return false; } line.setScale(_params.fontScale); // m_batch.drawShapeRange() calls FontContext's TextureCallback for new glyphs // and MeshCallback (drawGlyph) for vertex quads of each glyph in LineLayout. m_scratch.quads = &_quads; size_t quadsStart = _quads.size(); alfons::LineMetrics metrics; std::array<bool, 3> alignments = {}; if (_params.align != TextLabelProperty::Align::none) { alignments[int(_params.align)] = true; } // Collect possible alignment from anchor fallbacks for (int i = 0; i < _params.labelOptions.anchors.count; i++) { auto anchor = _params.labelOptions.anchors[i]; TextLabelProperty::Align alignment = TextLabelProperty::alignFromAnchor(anchor); if (alignment != TextLabelProperty::Align::none) { alignments[int(alignment)] = true; } } if (_params.wordWrap) { m_textWrapper.clearWraps(); if (_params.maxLines != 0) { uint32_t numLines = 0; int pos = 0; int max = line.shapes().size(); for (auto& shape : line.shapes()) { pos++; if (shape.mustBreak) { numLines++; if (numLines >= _params.maxLines && pos < max) { shape.mustBreak = false; line.removeShapes(shape.isSpace ? pos-1 : pos, max); auto ellipsis = m_shaper.shape(_params.font, "…"); line.addShapes(ellipsis.shapes()); break; } } } } float width = m_textWrapper.getShapeRangeWidth(line); for (size_t i = 0; i < 3; i++) { int rangeStart = m_scratch.quads->size(); if (!alignments[i]) { _textRanges[i] = Range(rangeStart, 0); continue; } int numLines = m_textWrapper.draw(m_batch, width, line, TextLabelProperty::Align(i), _params.lineSpacing, metrics); int rangeEnd = m_scratch.quads->size(); _textRanges[i] = Range(rangeStart, rangeEnd - rangeStart); // For single line text alignments are the same if (i == 0 && numLines == 1) { _textRanges[1] = Range(rangeEnd, 0); _textRanges[2] = Range(rangeEnd, 0); break; } } } else { glm::vec2 position(0); int rangeStart = m_scratch.quads->size(); m_batch.drawShapeRange(line, 0, line.shapes().size(), position, metrics); int rangeEnd = m_scratch.quads->size(); _textRanges[0] = Range(rangeStart, rangeEnd - rangeStart); _textRanges[1] = Range(rangeEnd, 0); _textRanges[2] = Range(rangeEnd, 0); } auto it = _quads.begin() + quadsStart; if (it == _quads.end()) { // No glyphs added return false; } // TextLabel parameter: Dimension float width = metrics.aabb.z - metrics.aabb.x; float height = metrics.aabb.w - metrics.aabb.y; _size = glm::vec2(width, height); // Offset to center all glyphs around 0/0 glm::vec2 offset((metrics.aabb.x + width * 0.5) * TextVertex::position_scale, (metrics.aabb.y + height * 0.5) * TextVertex::position_scale); { std::lock_guard<std::mutex> lock(m_textureMutex); for (; it != _quads.end(); ++it) { if (!_refs[it->atlas]) { _refs[it->atlas] = true; m_atlasRefCount[it->atlas] += 1; } it->quad[0].pos -= offset; it->quad[1].pos -= offset; it->quad[2].pos -= offset; it->quad[3].pos -= offset; } // Clear unused textures for (size_t i = 0; i < m_textures.size(); i++) { if (m_atlasRefCount[i] == 0) { m_atlas.clear(i); std::memset(m_textures[i]->buffer(), 0, GlyphTexture::size * GlyphTexture::size); } } } return true; } void FontContext::addFont(const FontDescription& _ft, alfons::InputSource _source) { // NB: Synchronize for calls from download thread std::lock_guard<std::mutex> lock(m_fontMutex); for (size_t i = 0; i < s_fontRasterSizes.size(); i++) { if (auto font = m_alfons.getFont(_ft.alias, s_fontRasterSizes[i])) { font->addFace(m_alfons.addFontFace(_source, s_fontRasterSizes[i])); // add fallbacks from default font if (m_font[i]) { font->addFaces(*m_font[i]); } } } } void FontContext::releaseFonts() { std::lock_guard<std::mutex> lock(m_fontMutex); // Unload Freetype and Harfbuzz resources for all font faces m_alfons.unload(); // Release system font fallbacks input source data from default fonts, since // those are 'weak' resources (would be automatically reloaded by alfons from // its URI or source callback. for (auto& font : m_font) { for (auto& face : font->faces()) { alfons::InputSource& fontSource = face->descriptor().source; if (fontSource.isUri() || fontSource.hasSourceCallback()) { fontSource.clearData(); } } } } void FontContext::ScratchBuffer::drawGlyph(const alfons::Rect& q, const alfons::AtlasGlyph& atlasGlyph) { if (atlasGlyph.atlas >= max_textures) { return; } auto& g = *atlasGlyph.glyph; quads->push_back({ atlasGlyph.atlas, {{glm::vec2{q.x1, q.y1} * TextVertex::position_scale, {g.u1, g.v1}}, {glm::vec2{q.x1, q.y2} * TextVertex::position_scale, {g.u1, g.v2}}, {glm::vec2{q.x2, q.y1} * TextVertex::position_scale, {g.u2, g.v1}}, {glm::vec2{q.x2, q.y2} * TextVertex::position_scale, {g.u2, g.v2}}}}); } std::shared_ptr<alfons::Font> FontContext::getFont(const std::string& _family, const std::string& _style, const std::string& _weight, float _size) { // Pick the smallest font that does not scale down too much float fontSize = s_fontRasterSizes.back(); size_t sizeIndex = s_fontRasterSizes.size() - 1; auto fontSizeItr = std::lower_bound(s_fontRasterSizes.begin(), s_fontRasterSizes.end(), _size); if (fontSizeItr != s_fontRasterSizes.end()) { fontSize = *fontSizeItr; sizeIndex = fontSizeItr - s_fontRasterSizes.begin(); } std::lock_guard<std::mutex> lock(m_fontMutex); auto font = m_alfons.getFont(FontDescription::Alias(_family, _style, _weight), fontSize); if (font->hasFaces()) { return font; } // First, try to load from the system fonts. bool useFallbackFont = false; auto systemFontHandle = m_platform->systemFont(_family, _weight, _style); alfons::InputSource source; switch (systemFontHandle.tag) { case FontSourceHandle::FontPath: source = alfons::InputSource(systemFontHandle.fontPath.path()); break; case FontSourceHandle::FontName: source = alfons::InputSource(systemFontHandle.fontName, true); break; case FontSourceHandle::FontLoader: { auto& loader = systemFontHandle.fontLoader; auto fontData = loader(); if (fontData.size() > 0) { source = alfons::InputSource(loader); } else { useFallbackFont = true; } break; } case FontSourceHandle::None: default: useFallbackFont = true; } if (!useFallbackFont) { font->addFace(m_alfons.addFontFace(source, fontSize)); if (m_font[sizeIndex]) { font->addFaces(*m_font[sizeIndex]); } } else { LOGD("Loading fallback font for Family: %s, Style: %s, Weight: %s, Size %f", _family.c_str(), _style.c_str(), _weight.c_str(), _size); // Add fallbacks from default font. if (m_font[sizeIndex]) { font->addFaces(*m_font[sizeIndex]); } } return font; } } <commit_msg>Don't dereference null fonts in FontContext::releaseFonts (#1972)<commit_after>#include "text/fontContext.h" #include "log.h" #include "platform.h" #define SDF_IMPLEMENTATION #include "sdf.h" #include <memory> #include <regex> #define SDF_WIDTH 6 #define MIN_LINE_WIDTH 4 namespace Tangram { const std::vector<float> FontContext::s_fontRasterSizes = { 16, 28, 40 }; FontContext::FontContext(std::shared_ptr<const Platform> _platform) : m_sdfRadius(SDF_WIDTH), m_atlas(*this, GlyphTexture::size, m_sdfRadius), m_batch(m_atlas, m_scratch), m_platform(_platform) {} void FontContext::setPixelScale(float _scale) { m_sdfRadius = SDF_WIDTH * _scale; } void FontContext::loadFonts() { auto fallbacks = m_platform->systemFontFallbacksHandle(); for (size_t i = 0; i < s_fontRasterSizes.size(); i++) { m_font[i] = m_alfons.addFont("default", s_fontRasterSizes[i]); } for (const auto& fallback : fallbacks) { if (!fallback.isValid()) { continue; } alfons::InputSource source; switch (fallback.tag) { case FontSourceHandle::FontPath: source = alfons::InputSource(fallback.fontPath.path()); break; case FontSourceHandle::FontName: source = alfons::InputSource(fallback.fontName, true); break; case FontSourceHandle::FontLoader: source = alfons::InputSource(fallback.fontLoader); break; case FontSourceHandle::None: default: return; } for (size_t i = 0; i < s_fontRasterSizes.size(); i++) { m_font[i]->addFace(m_alfons.addFontFace(source, s_fontRasterSizes[i])); } } } // Synchronized on m_mutex in layoutText(), called on tile-worker threads void FontContext::addTexture(alfons::AtlasID id, uint16_t width, uint16_t height) { std::lock_guard<std::mutex> lock(m_textureMutex); if (m_textures.size() == max_textures) { LOGE("Way too many glyph textures!"); return; } m_textures.push_back(std::make_unique<GlyphTexture>()); } // Synchronized on m_mutex in layoutText(), called on tile-worker threads void FontContext::addGlyph(alfons::AtlasID id, uint16_t gx, uint16_t gy, uint16_t gw, uint16_t gh, const unsigned char* src, uint16_t pad) { std::lock_guard<std::mutex> lock(m_textureMutex); if (id >= max_textures) { return; } auto texData = m_textures[id]->buffer(); auto& texture = m_textures[id]; size_t stride = GlyphTexture::size; size_t width = GlyphTexture::size; unsigned char* dst = &texData[(gx + pad) + (gy + pad) * stride]; for (size_t y = 0, pos = 0; y < gh; y++, pos += gw) { std::memcpy(dst + (y * stride), src + pos, gw); } dst = &texData[size_t(gx) + (size_t(gy) * width)]; gw += pad * 2; gh += pad * 2; size_t bytes = size_t(gw) * size_t(gh) * sizeof(float) * 3; if (m_sdfBuffer.size() < bytes) { m_sdfBuffer.resize(bytes); } sdfBuildDistanceFieldNoAlloc(dst, width, m_sdfRadius, dst, gw, gh, width, &m_sdfBuffer[0]); texture->setRowsDirty(gy, gh); } void FontContext::releaseAtlas(std::bitset<max_textures> _refs) { if (!_refs.any()) { return; } std::lock_guard<std::mutex> lock(m_textureMutex); for (size_t i = 0; i < m_textures.size(); i++) { if (_refs[i]) { m_atlasRefCount[i] -= 1; } } } void FontContext::updateTextures(RenderState& rs) { std::lock_guard<std::mutex> lock(m_textureMutex); for (auto& gt : m_textures) { gt->bind(rs, 0); } } void FontContext::bindTexture(RenderState& rs, alfons::AtlasID _id, GLuint _unit) { std::lock_guard<std::mutex> lock(m_textureMutex); m_textures[_id]->bind(rs, _unit); } bool FontContext::layoutText(TextStyle::Parameters& _params, const icu::UnicodeString& _text, std::vector<GlyphQuad>& _quads, std::bitset<max_textures>& _refs, glm::vec2& _size, TextRange& _textRanges) { std::lock_guard<std::mutex> lock(m_fontMutex); alfons::LineLayout line = m_shaper.shapeICU(_params.font, _text, MIN_LINE_WIDTH, _params.wordWrap ? _params.maxLineWidth : 0); if (line.missingGlyphs() || line.shapes().size() == 0) { // Nothing to do! return false; } line.setScale(_params.fontScale); // m_batch.drawShapeRange() calls FontContext's TextureCallback for new glyphs // and MeshCallback (drawGlyph) for vertex quads of each glyph in LineLayout. m_scratch.quads = &_quads; size_t quadsStart = _quads.size(); alfons::LineMetrics metrics; std::array<bool, 3> alignments = {}; if (_params.align != TextLabelProperty::Align::none) { alignments[int(_params.align)] = true; } // Collect possible alignment from anchor fallbacks for (int i = 0; i < _params.labelOptions.anchors.count; i++) { auto anchor = _params.labelOptions.anchors[i]; TextLabelProperty::Align alignment = TextLabelProperty::alignFromAnchor(anchor); if (alignment != TextLabelProperty::Align::none) { alignments[int(alignment)] = true; } } if (_params.wordWrap) { m_textWrapper.clearWraps(); if (_params.maxLines != 0) { uint32_t numLines = 0; int pos = 0; int max = line.shapes().size(); for (auto& shape : line.shapes()) { pos++; if (shape.mustBreak) { numLines++; if (numLines >= _params.maxLines && pos < max) { shape.mustBreak = false; line.removeShapes(shape.isSpace ? pos-1 : pos, max); auto ellipsis = m_shaper.shape(_params.font, "…"); line.addShapes(ellipsis.shapes()); break; } } } } float width = m_textWrapper.getShapeRangeWidth(line); for (size_t i = 0; i < 3; i++) { int rangeStart = m_scratch.quads->size(); if (!alignments[i]) { _textRanges[i] = Range(rangeStart, 0); continue; } int numLines = m_textWrapper.draw(m_batch, width, line, TextLabelProperty::Align(i), _params.lineSpacing, metrics); int rangeEnd = m_scratch.quads->size(); _textRanges[i] = Range(rangeStart, rangeEnd - rangeStart); // For single line text alignments are the same if (i == 0 && numLines == 1) { _textRanges[1] = Range(rangeEnd, 0); _textRanges[2] = Range(rangeEnd, 0); break; } } } else { glm::vec2 position(0); int rangeStart = m_scratch.quads->size(); m_batch.drawShapeRange(line, 0, line.shapes().size(), position, metrics); int rangeEnd = m_scratch.quads->size(); _textRanges[0] = Range(rangeStart, rangeEnd - rangeStart); _textRanges[1] = Range(rangeEnd, 0); _textRanges[2] = Range(rangeEnd, 0); } auto it = _quads.begin() + quadsStart; if (it == _quads.end()) { // No glyphs added return false; } // TextLabel parameter: Dimension float width = metrics.aabb.z - metrics.aabb.x; float height = metrics.aabb.w - metrics.aabb.y; _size = glm::vec2(width, height); // Offset to center all glyphs around 0/0 glm::vec2 offset((metrics.aabb.x + width * 0.5) * TextVertex::position_scale, (metrics.aabb.y + height * 0.5) * TextVertex::position_scale); { std::lock_guard<std::mutex> lock(m_textureMutex); for (; it != _quads.end(); ++it) { if (!_refs[it->atlas]) { _refs[it->atlas] = true; m_atlasRefCount[it->atlas] += 1; } it->quad[0].pos -= offset; it->quad[1].pos -= offset; it->quad[2].pos -= offset; it->quad[3].pos -= offset; } // Clear unused textures for (size_t i = 0; i < m_textures.size(); i++) { if (m_atlasRefCount[i] == 0) { m_atlas.clear(i); std::memset(m_textures[i]->buffer(), 0, GlyphTexture::size * GlyphTexture::size); } } } return true; } void FontContext::addFont(const FontDescription& _ft, alfons::InputSource _source) { // NB: Synchronize for calls from download thread std::lock_guard<std::mutex> lock(m_fontMutex); for (size_t i = 0; i < s_fontRasterSizes.size(); i++) { if (auto font = m_alfons.getFont(_ft.alias, s_fontRasterSizes[i])) { font->addFace(m_alfons.addFontFace(_source, s_fontRasterSizes[i])); // add fallbacks from default font if (m_font[i]) { font->addFaces(*m_font[i]); } } } } void FontContext::releaseFonts() { std::lock_guard<std::mutex> lock(m_fontMutex); // Unload Freetype and Harfbuzz resources for all font faces m_alfons.unload(); // Release system font fallbacks input source data from default fonts, since // those are 'weak' resources (would be automatically reloaded by alfons from // its URI or source callback. for (auto& font : m_font) { if (!font) { continue; } for (auto& face : font->faces()) { alfons::InputSource& fontSource = face->descriptor().source; if (fontSource.isUri() || fontSource.hasSourceCallback()) { fontSource.clearData(); } } } } void FontContext::ScratchBuffer::drawGlyph(const alfons::Rect& q, const alfons::AtlasGlyph& atlasGlyph) { if (atlasGlyph.atlas >= max_textures) { return; } auto& g = *atlasGlyph.glyph; quads->push_back({ atlasGlyph.atlas, {{glm::vec2{q.x1, q.y1} * TextVertex::position_scale, {g.u1, g.v1}}, {glm::vec2{q.x1, q.y2} * TextVertex::position_scale, {g.u1, g.v2}}, {glm::vec2{q.x2, q.y1} * TextVertex::position_scale, {g.u2, g.v1}}, {glm::vec2{q.x2, q.y2} * TextVertex::position_scale, {g.u2, g.v2}}}}); } std::shared_ptr<alfons::Font> FontContext::getFont(const std::string& _family, const std::string& _style, const std::string& _weight, float _size) { // Pick the smallest font that does not scale down too much float fontSize = s_fontRasterSizes.back(); size_t sizeIndex = s_fontRasterSizes.size() - 1; auto fontSizeItr = std::lower_bound(s_fontRasterSizes.begin(), s_fontRasterSizes.end(), _size); if (fontSizeItr != s_fontRasterSizes.end()) { fontSize = *fontSizeItr; sizeIndex = fontSizeItr - s_fontRasterSizes.begin(); } std::lock_guard<std::mutex> lock(m_fontMutex); auto font = m_alfons.getFont(FontDescription::Alias(_family, _style, _weight), fontSize); if (font->hasFaces()) { return font; } // First, try to load from the system fonts. bool useFallbackFont = false; auto systemFontHandle = m_platform->systemFont(_family, _weight, _style); alfons::InputSource source; switch (systemFontHandle.tag) { case FontSourceHandle::FontPath: source = alfons::InputSource(systemFontHandle.fontPath.path()); break; case FontSourceHandle::FontName: source = alfons::InputSource(systemFontHandle.fontName, true); break; case FontSourceHandle::FontLoader: { auto& loader = systemFontHandle.fontLoader; auto fontData = loader(); if (fontData.size() > 0) { source = alfons::InputSource(loader); } else { useFallbackFont = true; } break; } case FontSourceHandle::None: default: useFallbackFont = true; } if (!useFallbackFont) { font->addFace(m_alfons.addFontFace(source, fontSize)); if (m_font[sizeIndex]) { font->addFaces(*m_font[sizeIndex]); } } else { LOGD("Loading fallback font for Family: %s, Style: %s, Weight: %s, Size %f", _family.c_str(), _style.c_str(), _weight.c_str(), _size); // Add fallbacks from default font. if (m_font[sizeIndex]) { font->addFaces(*m_font[sizeIndex]); } } return font; } } <|endoftext|>
<commit_before>/* kwatchgnupgmainwin.cpp This file is part of Kleopatra, the KDE keymanager Copyright (c) 2001,2002,2004 Klar�vdalens Datakonsult AB Kleopatra is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Kleopatra 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 this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include "kwatchgnupgmainwin.h" #include "kwatchgnupgconfig.h" #include "tray.h" #include <kleo/cryptobackendfactory.h> #include <kleo/cryptoconfig.h> #include <kdebug.h> #include <kmessagebox.h> #include <klocale.h> #include <kapplication.h> #include <kaction.h> #include <kactioncollection.h> #include <kstandardaction.h> #include <k3procio.h> #include <kconfig.h> #include <kfiledialog.h> #include <kedittoolbar.h> #include <kshortcutsdialog.h> #include <QTextEdit> #include <QDir> #include <QEventLoop> #include <QTimer> #include <QTextCodec> //Added by qt3to4: #include <QTextStream> #include <QDateTime> #include <kglobal.h> #include <kicon.h> #define WATCHGNUPGBINARY "watchgnupg" #define WATCHGNUPGSOCKET ( QDir::home().canonicalPath() + "/.gnupg/log-socket") KWatchGnuPGMainWindow::KWatchGnuPGMainWindow( QWidget* parent ) : KXmlGuiWindow( parent, Qt::WType_TopLevel ), mConfig(0) { createActions(); createGUI(); mCentralWidget = new QTextEdit( this ); mCentralWidget->setObjectName( "central log view" ); mCentralWidget->setTextFormat( Qt::LogText ); setCentralWidget( mCentralWidget ); mWatcher = new K3ProcIO( QTextCodec::codecForMib( 106 /*utf-8*/ ) ); connect( mWatcher, SIGNAL( processExited(K3Process*) ), this, SLOT( slotWatcherExited() ) ); connect( mWatcher, SIGNAL( readReady(K3ProcIO*) ), this, SLOT( slotReadStdout() ) ); slotReadConfig(); mSysTray = new KWatchGnuPGTray( this ); mSysTray->show(); connect( mSysTray, SIGNAL( quitSelected() ), this, SLOT( slotQuit() ) ); setAutoSaveSettings(); } KWatchGnuPGMainWindow::~KWatchGnuPGMainWindow() { delete mWatcher; } void KWatchGnuPGMainWindow::slotClear() { mCentralWidget->clear(); mCentralWidget->append( tr("[%1] Log cleared").arg( QDateTime::currentDateTime().toString(Qt::ISODate) ) ); } void KWatchGnuPGMainWindow::createActions() { QAction *action = actionCollection()->addAction( "clear_log" ); action->setIcon( KIcon("history-clear") ); action->setText( i18n("C&lear History") ); connect(action, SIGNAL(triggered(bool) ), SLOT( slotClear() )); action->setShortcut(QKeySequence(Qt::CTRL+Qt::Key_L)); (void)KStandardAction::saveAs( this, SLOT(slotSaveAs()), actionCollection() ); (void)KStandardAction::close( this, SLOT(close()), actionCollection() ); (void)KStandardAction::quit( this, SLOT(slotQuit()), actionCollection() ); (void)KStandardAction::preferences( this, SLOT(slotConfigure()), actionCollection() ); ( void )KStandardAction::keyBindings(this, SLOT(configureShortcuts()), actionCollection()); ( void )KStandardAction::configureToolbars(this, SLOT(slotConfigureToolbars()), actionCollection()); #if 0 (void)new KAction( i18n("Configure KWatchGnuPG..."), QString::fromLatin1("configure"), 0, this, SLOT( slotConfigure() ), actionCollection(), "configure" ); #endif } void KWatchGnuPGMainWindow::configureShortcuts() { KShortcutsDialog::configure( actionCollection(), KShortcutsEditor::LetterShortcutsAllowed, this ); } void KWatchGnuPGMainWindow::slotConfigureToolbars() { KEditToolBar dlg( factory() ); dlg.exec(); } void KWatchGnuPGMainWindow::startWatcher() { disconnect( mWatcher, SIGNAL( processExited(K3Process*) ), this, SLOT( slotWatcherExited() ) ); if( mWatcher->isRunning() ) { mWatcher->kill(); while( mWatcher->isRunning() ) { #ifdef __GNUC__ #warning Port me! #endif // kapp->eventLoop()->processEvents(QEventLoop::ExcludeUserInput); } mCentralWidget->append(tr("[%1] Log stopped") .arg( QDateTime::currentDateTime().toString(Qt::ISODate))); } mWatcher->clearArguments(); KConfigGroup config(KGlobal::config(), "WatchGnuPG"); *mWatcher << config.readEntry("Executable", WATCHGNUPGBINARY); *mWatcher << "--force"; *mWatcher << config.readEntry("Socket", WATCHGNUPGSOCKET); config.changeGroup(QString()); if( !mWatcher->start() ) { KMessageBox::sorry( this, i18n("The watchgnupg logging process could not be started.\nPlease install watchgnupg somewhere in your $PATH.\nThis log window is now completely useless." ) ); } else { mCentralWidget->append( tr("[%1] Log started") .arg( QDateTime::currentDateTime().toString(Qt::ISODate) ) ); } connect( mWatcher, SIGNAL( processExited(K3Process*) ), this, SLOT( slotWatcherExited() ) ); } void KWatchGnuPGMainWindow::setGnuPGConfig() { QStringList logclients; // Get config object Kleo::CryptoConfig* cconfig = Kleo::CryptoBackendFactory::instance()->config(); if ( !cconfig ) return; //Q_ASSERT( cconfig ); KConfigGroup config(KGlobal::config(), "WatchGnuPG"); QStringList comps = cconfig->componentList(); for( QStringList::const_iterator it = comps.begin(); it != comps.end(); ++it ) { Kleo::CryptoConfigComponent* comp = cconfig->component( *it ); Q_ASSERT(comp); // Look for log-file entry in Debug group Kleo::CryptoConfigGroup* group = comp->group("Debug"); if( group ) { Kleo::CryptoConfigEntry* entry = group->entry("log-file"); if( entry ) { entry->setStringValue( QString("socket://")+ config.readEntry("Socket", WATCHGNUPGSOCKET )); logclients << QString("%1 (%2)").arg(*it).arg(comp->description()); } entry = group->entry("debug-level"); if( entry ) { entry->setStringValue( config.readEntry("LogLevel", "basic") ); } } } cconfig->sync(true); if( logclients.isEmpty() ) { KMessageBox::sorry( 0, i18n("There are no components available that support logging." ) ); } } void KWatchGnuPGMainWindow::slotWatcherExited() { if( KMessageBox::questionYesNo( this, i18n("The watchgnupg logging process died.\nDo you want to try to restart it?"), QString(), KGuiItem(i18n("Try Restart")), KGuiItem(i18n("Do Not Try")) ) == KMessageBox::Yes ) { mCentralWidget->append( i18n("====== Restarting logging process =====") ); startWatcher(); } else { KMessageBox::sorry( this, i18n("The watchgnupg logging process is not running.\nThis log window is now completely useless." ) ); } } void KWatchGnuPGMainWindow::slotReadStdout() { if ( !mWatcher ) return; QString str; while( mWatcher->readln(str,false) > 0 ) { mCentralWidget->append( str ); if( !isVisible() ) { // Change tray icon to show something happened // PENDING(steffen) mSysTray->setAttention(true); } } QTimer::singleShot( 0, this, SLOT(slotAckRead()) ); } void KWatchGnuPGMainWindow::slotAckRead() { if ( mWatcher ) mWatcher->ackRead(); } void KWatchGnuPGMainWindow::show() { mSysTray->setAttention(false); KMainWindow::show(); } void KWatchGnuPGMainWindow::slotSaveAs() { QString filename = KFileDialog::getSaveFileName( QString(), QString(), this, i18n("Save Log to File") ); if( filename.isEmpty() ) return; QFile file(filename); if( file.exists() ) { if( KMessageBox::Yes != KMessageBox::warningYesNo( this, i18n("The file named \"%1\" already " "exists. Are you sure you want " "to overwrite it?", filename), i18n("Overwrite File"), KStandardGuiItem::overwrite(), KStandardGuiItem::cancel() ) ) { return; } } if( file.open( QIODevice::WriteOnly ) ) { QTextStream st(&file); st << mCentralWidget->toPlainText(); file.close(); } } void KWatchGnuPGMainWindow::slotQuit() { disconnect( mWatcher, SIGNAL( processExited(K3Process*) ), this, SLOT( slotWatcherExited() ) ); mWatcher->kill(); kapp->quit(); } void KWatchGnuPGMainWindow::slotConfigure() { if( !mConfig ) { mConfig = new KWatchGnuPGConfig( this ); mConfig->setObjectName( "config dialog" ); connect( mConfig, SIGNAL( reconfigure() ), this, SLOT( slotReadConfig() ) ); } mConfig->loadConfig(); mConfig->exec(); } void KWatchGnuPGMainWindow::slotReadConfig() { KConfigGroup config(KGlobal::config(), "LogWindow"); mCentralWidget->setWordWrapMode( config.readEntry("WordWrap", false) ?QTextOption::WordWrap :QTextOption::NoWrap ); #ifdef __GNUC__ #warning "porting kde4: setMaxLogLines "; #endif //mCentralWidget->setMaxLogLines( config->readEntry( "MaxLogLen", 10000 ) ); setGnuPGConfig(); startWatcher(); } bool KWatchGnuPGMainWindow::queryClose() { if ( !kapp->sessionSaving() ) { hide(); return false; } return KMainWindow::queryClose(); } #include "kwatchgnupgmainwin.moc" <commit_msg>Use i18n to translate it. (I hope that it's translated into kde3.5.x)<commit_after>/* kwatchgnupgmainwin.cpp This file is part of Kleopatra, the KDE keymanager Copyright (c) 2001,2002,2004 Klar�vdalens Datakonsult AB Kleopatra is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Kleopatra 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 this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include "kwatchgnupgmainwin.h" #include "kwatchgnupgconfig.h" #include "tray.h" #include <kleo/cryptobackendfactory.h> #include <kleo/cryptoconfig.h> #include <kdebug.h> #include <kmessagebox.h> #include <klocale.h> #include <kapplication.h> #include <kaction.h> #include <kactioncollection.h> #include <kstandardaction.h> #include <k3procio.h> #include <kconfig.h> #include <kfiledialog.h> #include <kedittoolbar.h> #include <kshortcutsdialog.h> #include <QTextEdit> #include <QDir> #include <QEventLoop> #include <QTimer> #include <QTextCodec> //Added by qt3to4: #include <QTextStream> #include <QDateTime> #include <kglobal.h> #include <kicon.h> #define WATCHGNUPGBINARY "watchgnupg" #define WATCHGNUPGSOCKET ( QDir::home().canonicalPath() + "/.gnupg/log-socket") KWatchGnuPGMainWindow::KWatchGnuPGMainWindow( QWidget* parent ) : KXmlGuiWindow( parent, Qt::WType_TopLevel ), mConfig(0) { createActions(); createGUI(); mCentralWidget = new QTextEdit( this ); mCentralWidget->setObjectName( "central log view" ); mCentralWidget->setTextFormat( Qt::LogText ); setCentralWidget( mCentralWidget ); mWatcher = new K3ProcIO( QTextCodec::codecForMib( 106 /*utf-8*/ ) ); connect( mWatcher, SIGNAL( processExited(K3Process*) ), this, SLOT( slotWatcherExited() ) ); connect( mWatcher, SIGNAL( readReady(K3ProcIO*) ), this, SLOT( slotReadStdout() ) ); slotReadConfig(); mSysTray = new KWatchGnuPGTray( this ); mSysTray->show(); connect( mSysTray, SIGNAL( quitSelected() ), this, SLOT( slotQuit() ) ); setAutoSaveSettings(); } KWatchGnuPGMainWindow::~KWatchGnuPGMainWindow() { delete mWatcher; } void KWatchGnuPGMainWindow::slotClear() { mCentralWidget->clear(); mCentralWidget->append( i18n("[%1] Log cleared", QDateTime::currentDateTime().toString(Qt::ISODate) ) ); } void KWatchGnuPGMainWindow::createActions() { QAction *action = actionCollection()->addAction( "clear_log" ); action->setIcon( KIcon("history-clear") ); action->setText( i18n("C&lear History") ); connect(action, SIGNAL(triggered(bool) ), SLOT( slotClear() )); action->setShortcut(QKeySequence(Qt::CTRL+Qt::Key_L)); (void)KStandardAction::saveAs( this, SLOT(slotSaveAs()), actionCollection() ); (void)KStandardAction::close( this, SLOT(close()), actionCollection() ); (void)KStandardAction::quit( this, SLOT(slotQuit()), actionCollection() ); (void)KStandardAction::preferences( this, SLOT(slotConfigure()), actionCollection() ); ( void )KStandardAction::keyBindings(this, SLOT(configureShortcuts()), actionCollection()); ( void )KStandardAction::configureToolbars(this, SLOT(slotConfigureToolbars()), actionCollection()); #if 0 (void)new KAction( i18n("Configure KWatchGnuPG..."), QString::fromLatin1("configure"), 0, this, SLOT( slotConfigure() ), actionCollection(), "configure" ); #endif } void KWatchGnuPGMainWindow::configureShortcuts() { KShortcutsDialog::configure( actionCollection(), KShortcutsEditor::LetterShortcutsAllowed, this ); } void KWatchGnuPGMainWindow::slotConfigureToolbars() { KEditToolBar dlg( factory() ); dlg.exec(); } void KWatchGnuPGMainWindow::startWatcher() { disconnect( mWatcher, SIGNAL( processExited(K3Process*) ), this, SLOT( slotWatcherExited() ) ); if( mWatcher->isRunning() ) { mWatcher->kill(); while( mWatcher->isRunning() ) { #ifdef __GNUC__ #warning Port me! #endif // kapp->eventLoop()->processEvents(QEventLoop::ExcludeUserInput); } mCentralWidget->append(i18n("[%1] Log stopped", QDateTime::currentDateTime().toString(Qt::ISODate))); } mWatcher->clearArguments(); KConfigGroup config(KGlobal::config(), "WatchGnuPG"); *mWatcher << config.readEntry("Executable", WATCHGNUPGBINARY); *mWatcher << "--force"; *mWatcher << config.readEntry("Socket", WATCHGNUPGSOCKET); config.changeGroup(QString()); if( !mWatcher->start() ) { KMessageBox::sorry( this, i18n("The watchgnupg logging process could not be started.\nPlease install watchgnupg somewhere in your $PATH.\nThis log window is now completely useless." ) ); } else { mCentralWidget->append( i18n("[%1] Log started",QDateTime::currentDateTime().toString(Qt::ISODate) ) ); } connect( mWatcher, SIGNAL( processExited(K3Process*) ), this, SLOT( slotWatcherExited() ) ); } void KWatchGnuPGMainWindow::setGnuPGConfig() { QStringList logclients; // Get config object Kleo::CryptoConfig* cconfig = Kleo::CryptoBackendFactory::instance()->config(); if ( !cconfig ) return; //Q_ASSERT( cconfig ); KConfigGroup config(KGlobal::config(), "WatchGnuPG"); QStringList comps = cconfig->componentList(); for( QStringList::const_iterator it = comps.begin(); it != comps.end(); ++it ) { Kleo::CryptoConfigComponent* comp = cconfig->component( *it ); Q_ASSERT(comp); // Look for log-file entry in Debug group Kleo::CryptoConfigGroup* group = comp->group("Debug"); if( group ) { Kleo::CryptoConfigEntry* entry = group->entry("log-file"); if( entry ) { entry->setStringValue( QString("socket://")+ config.readEntry("Socket", WATCHGNUPGSOCKET )); logclients << QString("%1 (%2)").arg(*it).arg(comp->description()); } entry = group->entry("debug-level"); if( entry ) { entry->setStringValue( config.readEntry("LogLevel", "basic") ); } } } cconfig->sync(true); if( logclients.isEmpty() ) { KMessageBox::sorry( 0, i18n("There are no components available that support logging." ) ); } } void KWatchGnuPGMainWindow::slotWatcherExited() { if( KMessageBox::questionYesNo( this, i18n("The watchgnupg logging process died.\nDo you want to try to restart it?"), QString(), KGuiItem(i18n("Try Restart")), KGuiItem(i18n("Do Not Try")) ) == KMessageBox::Yes ) { mCentralWidget->append( i18n("====== Restarting logging process =====") ); startWatcher(); } else { KMessageBox::sorry( this, i18n("The watchgnupg logging process is not running.\nThis log window is now completely useless." ) ); } } void KWatchGnuPGMainWindow::slotReadStdout() { if ( !mWatcher ) return; QString str; while( mWatcher->readln(str,false) > 0 ) { mCentralWidget->append( str ); if( !isVisible() ) { // Change tray icon to show something happened // PENDING(steffen) mSysTray->setAttention(true); } } QTimer::singleShot( 0, this, SLOT(slotAckRead()) ); } void KWatchGnuPGMainWindow::slotAckRead() { if ( mWatcher ) mWatcher->ackRead(); } void KWatchGnuPGMainWindow::show() { mSysTray->setAttention(false); KMainWindow::show(); } void KWatchGnuPGMainWindow::slotSaveAs() { QString filename = KFileDialog::getSaveFileName( QString(), QString(), this, i18n("Save Log to File") ); if( filename.isEmpty() ) return; QFile file(filename); if( file.exists() ) { if( KMessageBox::Yes != KMessageBox::warningYesNo( this, i18n("The file named \"%1\" already " "exists. Are you sure you want " "to overwrite it?", filename), i18n("Overwrite File"), KStandardGuiItem::overwrite(), KStandardGuiItem::cancel() ) ) { return; } } if( file.open( QIODevice::WriteOnly ) ) { QTextStream st(&file); st << mCentralWidget->toPlainText(); file.close(); } } void KWatchGnuPGMainWindow::slotQuit() { disconnect( mWatcher, SIGNAL( processExited(K3Process*) ), this, SLOT( slotWatcherExited() ) ); mWatcher->kill(); kapp->quit(); } void KWatchGnuPGMainWindow::slotConfigure() { if( !mConfig ) { mConfig = new KWatchGnuPGConfig( this ); mConfig->setObjectName( "config dialog" ); connect( mConfig, SIGNAL( reconfigure() ), this, SLOT( slotReadConfig() ) ); } mConfig->loadConfig(); mConfig->exec(); } void KWatchGnuPGMainWindow::slotReadConfig() { KConfigGroup config(KGlobal::config(), "LogWindow"); mCentralWidget->setWordWrapMode( config.readEntry("WordWrap", false) ?QTextOption::WordWrap :QTextOption::NoWrap ); #ifdef __GNUC__ #warning "porting kde4: setMaxLogLines "; #endif //mCentralWidget->setMaxLogLines( config->readEntry( "MaxLogLen", 10000 ) ); setGnuPGConfig(); startWatcher(); } bool KWatchGnuPGMainWindow::queryClose() { if ( !kapp->sessionSaving() ) { hide(); return false; } return KMainWindow::queryClose(); } #include "kwatchgnupgmainwin.moc" <|endoftext|>
<commit_before>/* This file is part of Kontact. Copyright (c) 2003 Tobias Koenig <tokoe@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program 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 this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include <qlabel.h> #include <qlayout.h> #include <kdialog.h> #include <kglobal.h> #include <kiconloader.h> #include <klocale.h> #include <kparts/part.h> #include <kstandarddirs.h> #include <kurllabel.h> #include <qtooltip.h> #include <libkcal/event.h> #include <libkcal/resourcecalendar.h> #include <libkcal/resourcelocal.h> #include <libkdepim/kpimprefs.h> #include "korganizeriface_stub.h" #include "core.h" #include "plugin.h" #include "korganizerplugin.h" #include "korganizer/stdcalendar.h" #include "summarywidget.h" SummaryWidget::SummaryWidget( KOrganizerPlugin *plugin, QWidget *parent, const char *name ) : Kontact::Summary( parent, name ), mPlugin( plugin ), mCalendar( 0 ) { QVBoxLayout *mainLayout = new QVBoxLayout( this, 3, 3 ); QPixmap icon = KGlobal::iconLoader()->loadIcon( "kontact_date", KIcon::Desktop, KIcon::SizeMedium ); QWidget *header = createHeader( this, icon, i18n( "Appointments" ) ); mainLayout->addWidget( header ); mLayout = new QGridLayout( mainLayout, 7, 5, 3 ); mLayout->setRowStretch( 6, 1 ); mCalendar = KOrg::StdCalendar::self(); mCalendar->load(); connect( mCalendar, SIGNAL( calendarChanged() ), SLOT( updateView() ) ); connect( mPlugin->core(), SIGNAL( dayChanged( const QDate& ) ), SLOT( updateView() ) ); updateView(); } SummaryWidget::~SummaryWidget() { } void SummaryWidget::updateView() { mLabels.setAutoDelete( true ); mLabels.clear(); mLabels.setAutoDelete( false ); KIconLoader loader( "kdepim" ); KConfig config( "kcmkorgsummaryrc" ); config.setGroup( "Calendar" ); int days = config.readNumEntry( "DaysToShow", 1 ); QLabel *label = 0; int counter = 0; QPixmap pm = loader.loadIcon( "appointment", KIcon::Small ); QDate dt; QDate currentDate = QDate::currentDate(); for ( dt=currentDate; dt<=currentDate.addDays( days - 1 ); dt=dt.addDays(1) ) { KCal::Event::List events = mCalendar->events( dt ); KCal::Event *ev; KCal::Event::List::ConstIterator it; QDateTime qdt; // Find recurring events, replacing the QDate with the currentDate for ( it=events.begin(); it!=events.end(); ++it ) { ev = *it; if ( ev->recursOn( dt ) ) { qdt = ev->dtStart(); qdt.setDate( dt ); ev->setDtStart( qdt ); } } // sort the events for this date by summary events = KCal::Calendar::sortEvents( &events, KCal::EventSortSummary, KCal::SortDirectionAscending ); // sort the events for this date by start date events = KCal::Calendar::sortEvents( &events, KCal::EventSortStartDate, KCal::SortDirectionAscending ); for ( it=events.begin(); it!=events.end(); ++it ) { ev = *it; // Count number of days remaining in multiday event int span=1; int dayof=1; if ( ev->isMultiDay() ) { QDate d = ev->dtStart().date(); if ( d < currentDate ) { d = currentDate; } while ( d < ev->dtEnd().date() ) { if ( d < dt ) { dayof++; } span++; d=d.addDays( 1 ); } } // If this date is part of a floating, multiday event, then we // only make a print for the first day of the event. if ( ev->isMultiDay() && ev->doesFloat() && dayof != 1 ) continue; // Fill Appointment Pixmap Field label = new QLabel( this ); label->setPixmap( pm ); label->setMaximumWidth( label->minimumSizeHint().width() ); label->setAlignment( AlignVCenter ); mLayout->addWidget( label, counter, 0 ); mLabels.append( label ); // Fill Event Date Field bool makeBold = false; QString datestr; // Modify event date for printing QDate sD = QDate::QDate( dt.year(), dt.month(), dt.day() ); if ( ( sD.month() == currentDate.month() ) && ( sD.day() == currentDate.day() ) ) { datestr = i18n( "Today" ); makeBold = true; } else if ( ( sD.month() == currentDate.addDays( 1 ).month() ) && ( sD.day() == currentDate.addDays( 1 ).day() ) ) { datestr = i18n( "Tomorrow" ); } else { datestr = KGlobal::locale()->formatDate( sD ); } // Print the date span for multiday, floating events, for the // first day of the event only. if ( ev->isMultiDay() && ev->doesFloat() && dayof == 1 && span > 1 ) { QString endstr = KGlobal::locale()->formatDate( sD.addDays( span-1 ) ); datestr += " -\n " + endstr; } label = new QLabel( datestr, this ); label->setAlignment( AlignLeft | AlignVCenter ); if ( makeBold ) { QFont font = label->font(); font.setBold( true ); label->setFont( font ); } mLayout->addWidget( label, counter, 1 ); mLabels.append( label ); // Fill Event Summary Field QString newtext = ev->summary(); if ( ev->isMultiDay() && !ev->doesFloat() ) { newtext.append( QString(" (%1/%2)").arg( dayof ).arg( span ) ); } KURLLabel *urlLabel = new KURLLabel( ev->uid(), newtext, this ); urlLabel->installEventFilter( this ); urlLabel->setAlignment( urlLabel->alignment() | Qt::WordBreak ); mLayout->addWidget( urlLabel, counter, 2 ); mLabels.append( urlLabel ); if ( !ev->description().isEmpty() ) { QToolTip::add( urlLabel, ev->description() ); } // Fill Event Time Range Field (only for non-floating Events) if ( !ev->doesFloat() ) { QTime sST = ev->dtStart().time(); QTime sET = ev->dtEnd().time(); if ( ev->isMultiDay() ) { if ( ev->dtStart().date() < dt ) { sST = QTime::QTime( 0, 0 ); } if ( ev->dtEnd().date() > dt ) { sET = QTime::QTime( 23, 59 ); } } datestr = i18n( "Time from - to", "%1 - %2" ) .arg( KGlobal::locale()->formatTime( sST ) ) .arg( KGlobal::locale()->formatTime( sET ) ); label = new QLabel( datestr, this ); label->setAlignment( AlignLeft | AlignVCenter ); mLayout->addWidget( label, counter, 3 ); mLabels.append( label ); } connect( urlLabel, SIGNAL( leftClickedURL( const QString& ) ), this, SLOT( selectEvent( const QString& ) ) ); counter++; } } if ( !counter ) { QLabel *noEvents = new QLabel( i18n( "No appointments pending within the next day", "No appointments pending within the next %n days", days ), this, "nothing to see" ); noEvents->setAlignment( AlignHCenter | AlignVCenter ); mLayout->addWidget( noEvents, 0, 2 ); mLabels.append( noEvents ); } for ( label = mLabels.first(); label; label = mLabels.next() ) label->show(); } void SummaryWidget::selectEvent( const QString &uid ) { mPlugin->core()->selectPlugin( "kontact_korganizerplugin" ); //ensure loaded KOrganizerIface_stub iface( "korganizer", "KOrganizerIface" ); iface.editIncidence( uid ); } bool SummaryWidget::eventFilter( QObject *obj, QEvent* e ) { if ( obj->inherits( "KURLLabel" ) ) { KURLLabel* label = static_cast<KURLLabel*>( obj ); if ( e->type() == QEvent::Enter ) emit message( i18n( "Edit Appointment: \"%1\"" ).arg( label->text() ) ); if ( e->type() == QEvent::Leave ) emit message( QString::null ); } return Kontact::Summary::eventFilter( obj, e ); } QStringList SummaryWidget::configModules() const { return QStringList( "kcmkorgsummary.desktop" ); } #include "summarywidget.moc" <commit_msg>don't show "Today" as the starting date for multi-day events; use the actual date instead.<commit_after>/* This file is part of Kontact. Copyright (c) 2003 Tobias Koenig <tokoe@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program 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 this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include <qlabel.h> #include <qlayout.h> #include <kdialog.h> #include <kglobal.h> #include <kiconloader.h> #include <klocale.h> #include <kparts/part.h> #include <kstandarddirs.h> #include <kurllabel.h> #include <qtooltip.h> #include <libkcal/event.h> #include <libkcal/resourcecalendar.h> #include <libkcal/resourcelocal.h> #include <libkdepim/kpimprefs.h> #include "korganizeriface_stub.h" #include "core.h" #include "plugin.h" #include "korganizerplugin.h" #include "korganizer/stdcalendar.h" #include "summarywidget.h" SummaryWidget::SummaryWidget( KOrganizerPlugin *plugin, QWidget *parent, const char *name ) : Kontact::Summary( parent, name ), mPlugin( plugin ), mCalendar( 0 ) { QVBoxLayout *mainLayout = new QVBoxLayout( this, 3, 3 ); QPixmap icon = KGlobal::iconLoader()->loadIcon( "kontact_date", KIcon::Desktop, KIcon::SizeMedium ); QWidget *header = createHeader( this, icon, i18n( "Appointments" ) ); mainLayout->addWidget( header ); mLayout = new QGridLayout( mainLayout, 7, 5, 3 ); mLayout->setRowStretch( 6, 1 ); mCalendar = KOrg::StdCalendar::self(); mCalendar->load(); connect( mCalendar, SIGNAL( calendarChanged() ), SLOT( updateView() ) ); connect( mPlugin->core(), SIGNAL( dayChanged( const QDate& ) ), SLOT( updateView() ) ); updateView(); } SummaryWidget::~SummaryWidget() { } void SummaryWidget::updateView() { mLabels.setAutoDelete( true ); mLabels.clear(); mLabels.setAutoDelete( false ); KIconLoader loader( "kdepim" ); KConfig config( "kcmkorgsummaryrc" ); config.setGroup( "Calendar" ); int days = config.readNumEntry( "DaysToShow", 1 ); QLabel *label = 0; int counter = 0; QPixmap pm = loader.loadIcon( "appointment", KIcon::Small ); QDate dt; QDate currentDate = QDate::currentDate(); for ( dt=currentDate; dt<=currentDate.addDays( days - 1 ); dt=dt.addDays(1) ) { KCal::Event::List events = mCalendar->events( dt ); KCal::Event *ev; KCal::Event::List::ConstIterator it; QDateTime qdt; // Find recurring events, replacing the QDate with the currentDate for ( it=events.begin(); it!=events.end(); ++it ) { ev = *it; if ( ev->recursOn( dt ) ) { qdt = ev->dtStart(); qdt.setDate( dt ); ev->setDtStart( qdt ); } } // sort the events for this date by summary events = KCal::Calendar::sortEvents( &events, KCal::EventSortSummary, KCal::SortDirectionAscending ); // sort the events for this date by start date events = KCal::Calendar::sortEvents( &events, KCal::EventSortStartDate, KCal::SortDirectionAscending ); for ( it=events.begin(); it!=events.end(); ++it ) { ev = *it; // Count number of days remaining in multiday event int span=1; int dayof=1; if ( ev->isMultiDay() ) { QDate d = ev->dtStart().date(); if ( d < currentDate ) { d = currentDate; } while ( d < ev->dtEnd().date() ) { if ( d < dt ) { dayof++; } span++; d=d.addDays( 1 ); } } // If this date is part of a floating, multiday event, then we // only make a print for the first day of the event. if ( ev->isMultiDay() && ev->doesFloat() && dayof != 1 ) continue; // Fill Appointment Pixmap Field label = new QLabel( this ); label->setPixmap( pm ); label->setMaximumWidth( label->minimumSizeHint().width() ); label->setAlignment( AlignVCenter ); mLayout->addWidget( label, counter, 0 ); mLabels.append( label ); // Fill Event Date Field bool makeBold = false; QString datestr; // Modify event date for printing QDate sD = QDate::QDate( dt.year(), dt.month(), dt.day() ); if ( ( sD.month() == currentDate.month() ) && ( sD.day() == currentDate.day() ) ) { datestr = i18n( "Today" ); makeBold = true; } else if ( ( sD.month() == currentDate.addDays( 1 ).month() ) && ( sD.day() == currentDate.addDays( 1 ).day() ) ) { datestr = i18n( "Tomorrow" ); } else { datestr = KGlobal::locale()->formatDate( sD ); } // Print the date span for multiday, floating events, for the // first day of the event only. if ( ev->isMultiDay() && ev->doesFloat() && dayof == 1 && span > 1 ) { datestr = KGlobal::locale()->formatDate( ev->dtStart().date() ); datestr += " -\n " + KGlobal::locale()->formatDate( sD.addDays( span-1 ) ); } label = new QLabel( datestr, this ); label->setAlignment( AlignLeft | AlignVCenter ); if ( makeBold ) { QFont font = label->font(); font.setBold( true ); label->setFont( font ); } mLayout->addWidget( label, counter, 1 ); mLabels.append( label ); // Fill Event Summary Field QString newtext = ev->summary(); if ( ev->isMultiDay() && !ev->doesFloat() ) { newtext.append( QString(" (%1/%2)").arg( dayof ).arg( span ) ); } KURLLabel *urlLabel = new KURLLabel( ev->uid(), newtext, this ); urlLabel->installEventFilter( this ); urlLabel->setAlignment( urlLabel->alignment() | Qt::WordBreak ); mLayout->addWidget( urlLabel, counter, 2 ); mLabels.append( urlLabel ); if ( !ev->description().isEmpty() ) { QToolTip::add( urlLabel, ev->description() ); } // Fill Event Time Range Field (only for non-floating Events) if ( !ev->doesFloat() ) { QTime sST = ev->dtStart().time(); QTime sET = ev->dtEnd().time(); if ( ev->isMultiDay() ) { if ( ev->dtStart().date() < dt ) { sST = QTime::QTime( 0, 0 ); } if ( ev->dtEnd().date() > dt ) { sET = QTime::QTime( 23, 59 ); } } datestr = i18n( "Time from - to", "%1 - %2" ) .arg( KGlobal::locale()->formatTime( sST ) ) .arg( KGlobal::locale()->formatTime( sET ) ); label = new QLabel( datestr, this ); label->setAlignment( AlignLeft | AlignVCenter ); mLayout->addWidget( label, counter, 3 ); mLabels.append( label ); } connect( urlLabel, SIGNAL( leftClickedURL( const QString& ) ), this, SLOT( selectEvent( const QString& ) ) ); counter++; } } if ( !counter ) { QLabel *noEvents = new QLabel( i18n( "No appointments pending within the next day", "No appointments pending within the next %n days", days ), this, "nothing to see" ); noEvents->setAlignment( AlignHCenter | AlignVCenter ); mLayout->addWidget( noEvents, 0, 2 ); mLabels.append( noEvents ); } for ( label = mLabels.first(); label; label = mLabels.next() ) label->show(); } void SummaryWidget::selectEvent( const QString &uid ) { mPlugin->core()->selectPlugin( "kontact_korganizerplugin" ); //ensure loaded KOrganizerIface_stub iface( "korganizer", "KOrganizerIface" ); iface.editIncidence( uid ); } bool SummaryWidget::eventFilter( QObject *obj, QEvent* e ) { if ( obj->inherits( "KURLLabel" ) ) { KURLLabel* label = static_cast<KURLLabel*>( obj ); if ( e->type() == QEvent::Enter ) emit message( i18n( "Edit Appointment: \"%1\"" ).arg( label->text() ) ); if ( e->type() == QEvent::Leave ) emit message( QString::null ); } return Kontact::Summary::eventFilter( obj, e ); } QStringList SummaryWidget::configModules() const { return QStringList( "kcmkorgsummary.desktop" ); } #include "summarywidget.moc" <|endoftext|>
<commit_before>// Copyright 2019-2020 Intel Corporation // SPDX-License-Identifier: Apache-2.0 #include <gtest/gtest.h> #include "embree3/rtcore.h" #include "openvkl/openvkl.h" #include "ospray/OSPEnums.h" TEST(Enums, VKLLogLevel) { ASSERT_LE(sizeof(OSPLogLevel), sizeof(VKLLogLevel)); ASSERT_EQ(OSP_LOG_DEBUG, VKL_LOG_DEBUG); ASSERT_EQ(OSP_LOG_INFO, VKL_LOG_INFO); ASSERT_EQ(OSP_LOG_WARNING, VKL_LOG_WARNING); ASSERT_EQ(OSP_LOG_ERROR, VKL_LOG_ERROR); // ASSERT_EQ(OSP_LOG_NONE, VKL_LOG_NONE); } TEST(Enums, VKLDataType) { ASSERT_LE(sizeof(OSPDataType), sizeof(VKLDataType)); ASSERT_EQ(OSP_BOOL, VKL_BOOL); ASSERT_EQ(OSP_CHAR, VKL_CHAR); ASSERT_EQ(OSP_UCHAR, VKL_UCHAR); ASSERT_EQ(OSP_VEC2UC, VKL_VEC2UC); ASSERT_EQ(OSP_VEC3UC, VKL_VEC3UC); ASSERT_EQ(OSP_VEC4UC, VKL_VEC4UC); ASSERT_EQ(OSP_SHORT, VKL_SHORT); ASSERT_EQ(OSP_USHORT, VKL_USHORT); ASSERT_EQ(OSP_INT, VKL_INT); ASSERT_EQ(OSP_VEC2I, VKL_VEC2I); ASSERT_EQ(OSP_VEC3I, VKL_VEC3I); ASSERT_EQ(OSP_VEC4I, VKL_VEC4I); ASSERT_EQ(OSP_UINT, VKL_UINT); ASSERT_EQ(OSP_VEC2UI, VKL_VEC2UI); ASSERT_EQ(OSP_VEC3UI, VKL_VEC3UI); ASSERT_EQ(OSP_VEC4UI, VKL_VEC4UI); ASSERT_EQ(OSP_LONG, VKL_LONG); ASSERT_EQ(OSP_VEC2L, VKL_VEC2L); ASSERT_EQ(OSP_VEC3L, VKL_VEC3L); ASSERT_EQ(OSP_VEC4L, VKL_VEC4L); ASSERT_EQ(OSP_ULONG, VKL_ULONG); ASSERT_EQ(OSP_VEC2UL, VKL_VEC2UL); ASSERT_EQ(OSP_VEC3UL, VKL_VEC3UL); ASSERT_EQ(OSP_VEC4UL, VKL_VEC4UL); ASSERT_EQ(OSP_FLOAT, VKL_FLOAT); ASSERT_EQ(OSP_VEC2F, VKL_VEC2F); ASSERT_EQ(OSP_VEC3F, VKL_VEC3F); ASSERT_EQ(OSP_VEC4F, VKL_VEC4F); ASSERT_EQ(OSP_DOUBLE, VKL_DOUBLE); ASSERT_EQ(OSP_BOX1I, VKL_BOX1I); ASSERT_EQ(OSP_BOX2I, VKL_BOX2I); ASSERT_EQ(OSP_BOX3I, VKL_BOX3I); ASSERT_EQ(OSP_BOX4I, VKL_BOX4I); ASSERT_EQ(OSP_BOX1F, VKL_BOX1F); ASSERT_EQ(OSP_BOX2F, VKL_BOX2F); ASSERT_EQ(OSP_BOX3F, VKL_BOX3F); ASSERT_EQ(OSP_BOX4F, VKL_BOX4F); ASSERT_EQ(OSP_DATA, VKL_DATA); ASSERT_EQ(OSP_LINEAR2F, VKL_LINEAR2F); ASSERT_EQ(OSP_LINEAR3F, VKL_LINEAR3F); ASSERT_EQ(OSP_AFFINE2F, VKL_AFFINE2F); ASSERT_EQ(OSP_AFFINE3F, VKL_AFFINE3F); ASSERT_EQ(OSP_RAW, VKL_RAW); ASSERT_EQ(OSP_BYTE, VKL_BYTE); ASSERT_EQ(OSP_VOID_PTR, VKL_VOID_PTR); ASSERT_EQ(OSP_STRING, VKL_STRING); ASSERT_EQ(OSP_OBJECT, VKL_OBJECT); // those are different object types: // ASSERT_EQ(OSP_VOLUME, VKL_VOLUME); } TEST(Enums, VKLUnstructuredCellType) { ASSERT_LE(sizeof(OSPUnstructuredCellType), sizeof(VKLUnstructuredCellType)); ASSERT_EQ(OSP_TETRAHEDRON, VKL_TETRAHEDRON); ASSERT_EQ(OSP_HEXAHEDRON, VKL_HEXAHEDRON); ASSERT_EQ(OSP_WEDGE, VKL_WEDGE); ASSERT_EQ(OSP_PYRAMID, VKL_PYRAMID); } TEST(Enums, VKLAMRMethod) { ASSERT_LE(sizeof(OSPAMRMethod), sizeof(VKLAMRMethod)); ASSERT_EQ(OSP_AMR_CURRENT, VKL_AMR_CURRENT); ASSERT_EQ(OSP_AMR_FINEST, VKL_AMR_FINEST); ASSERT_EQ(OSP_AMR_OCTANT, VKL_AMR_OCTANT); } TEST(Enums, RTCSubdivisionMode) { ASSERT_LE(sizeof(OSPSubdivisionMode), sizeof(RTCSubdivisionMode)); ASSERT_EQ(OSP_SUBDIVISION_NO_BOUNDARY, RTC_SUBDIVISION_MODE_NO_BOUNDARY); ASSERT_EQ( OSP_SUBDIVISION_SMOOTH_BOUNDARY, RTC_SUBDIVISION_MODE_SMOOTH_BOUNDARY); ASSERT_EQ(OSP_SUBDIVISION_PIN_CORNERS, RTC_SUBDIVISION_MODE_PIN_CORNERS); ASSERT_EQ(OSP_SUBDIVISION_PIN_BOUNDARY, RTC_SUBDIVISION_MODE_PIN_BOUNDARY); ASSERT_EQ(OSP_SUBDIVISION_PIN_ALL, RTC_SUBDIVISION_MODE_PIN_ALL); } <commit_msg>enable equality test for `none` log types<commit_after>// Copyright 2019-2020 Intel Corporation // SPDX-License-Identifier: Apache-2.0 #include <gtest/gtest.h> #include "embree3/rtcore.h" #include "openvkl/openvkl.h" #include "ospray/OSPEnums.h" TEST(Enums, VKLLogLevel) { ASSERT_LE(sizeof(OSPLogLevel), sizeof(VKLLogLevel)); ASSERT_EQ(OSP_LOG_DEBUG, VKL_LOG_DEBUG); ASSERT_EQ(OSP_LOG_INFO, VKL_LOG_INFO); ASSERT_EQ(OSP_LOG_WARNING, VKL_LOG_WARNING); ASSERT_EQ(OSP_LOG_ERROR, VKL_LOG_ERROR); ASSERT_EQ(OSP_LOG_NONE, VKL_LOG_NONE); } TEST(Enums, VKLDataType) { ASSERT_LE(sizeof(OSPDataType), sizeof(VKLDataType)); ASSERT_EQ(OSP_BOOL, VKL_BOOL); ASSERT_EQ(OSP_CHAR, VKL_CHAR); ASSERT_EQ(OSP_UCHAR, VKL_UCHAR); ASSERT_EQ(OSP_VEC2UC, VKL_VEC2UC); ASSERT_EQ(OSP_VEC3UC, VKL_VEC3UC); ASSERT_EQ(OSP_VEC4UC, VKL_VEC4UC); ASSERT_EQ(OSP_SHORT, VKL_SHORT); ASSERT_EQ(OSP_USHORT, VKL_USHORT); ASSERT_EQ(OSP_INT, VKL_INT); ASSERT_EQ(OSP_VEC2I, VKL_VEC2I); ASSERT_EQ(OSP_VEC3I, VKL_VEC3I); ASSERT_EQ(OSP_VEC4I, VKL_VEC4I); ASSERT_EQ(OSP_UINT, VKL_UINT); ASSERT_EQ(OSP_VEC2UI, VKL_VEC2UI); ASSERT_EQ(OSP_VEC3UI, VKL_VEC3UI); ASSERT_EQ(OSP_VEC4UI, VKL_VEC4UI); ASSERT_EQ(OSP_LONG, VKL_LONG); ASSERT_EQ(OSP_VEC2L, VKL_VEC2L); ASSERT_EQ(OSP_VEC3L, VKL_VEC3L); ASSERT_EQ(OSP_VEC4L, VKL_VEC4L); ASSERT_EQ(OSP_ULONG, VKL_ULONG); ASSERT_EQ(OSP_VEC2UL, VKL_VEC2UL); ASSERT_EQ(OSP_VEC3UL, VKL_VEC3UL); ASSERT_EQ(OSP_VEC4UL, VKL_VEC4UL); ASSERT_EQ(OSP_FLOAT, VKL_FLOAT); ASSERT_EQ(OSP_VEC2F, VKL_VEC2F); ASSERT_EQ(OSP_VEC3F, VKL_VEC3F); ASSERT_EQ(OSP_VEC4F, VKL_VEC4F); ASSERT_EQ(OSP_DOUBLE, VKL_DOUBLE); ASSERT_EQ(OSP_BOX1I, VKL_BOX1I); ASSERT_EQ(OSP_BOX2I, VKL_BOX2I); ASSERT_EQ(OSP_BOX3I, VKL_BOX3I); ASSERT_EQ(OSP_BOX4I, VKL_BOX4I); ASSERT_EQ(OSP_BOX1F, VKL_BOX1F); ASSERT_EQ(OSP_BOX2F, VKL_BOX2F); ASSERT_EQ(OSP_BOX3F, VKL_BOX3F); ASSERT_EQ(OSP_BOX4F, VKL_BOX4F); ASSERT_EQ(OSP_DATA, VKL_DATA); ASSERT_EQ(OSP_LINEAR2F, VKL_LINEAR2F); ASSERT_EQ(OSP_LINEAR3F, VKL_LINEAR3F); ASSERT_EQ(OSP_AFFINE2F, VKL_AFFINE2F); ASSERT_EQ(OSP_AFFINE3F, VKL_AFFINE3F); ASSERT_EQ(OSP_RAW, VKL_RAW); ASSERT_EQ(OSP_BYTE, VKL_BYTE); ASSERT_EQ(OSP_VOID_PTR, VKL_VOID_PTR); ASSERT_EQ(OSP_STRING, VKL_STRING); ASSERT_EQ(OSP_OBJECT, VKL_OBJECT); // those are different object types: // ASSERT_EQ(OSP_VOLUME, VKL_VOLUME); } TEST(Enums, VKLUnstructuredCellType) { ASSERT_LE(sizeof(OSPUnstructuredCellType), sizeof(VKLUnstructuredCellType)); ASSERT_EQ(OSP_TETRAHEDRON, VKL_TETRAHEDRON); ASSERT_EQ(OSP_HEXAHEDRON, VKL_HEXAHEDRON); ASSERT_EQ(OSP_WEDGE, VKL_WEDGE); ASSERT_EQ(OSP_PYRAMID, VKL_PYRAMID); } TEST(Enums, VKLAMRMethod) { ASSERT_LE(sizeof(OSPAMRMethod), sizeof(VKLAMRMethod)); ASSERT_EQ(OSP_AMR_CURRENT, VKL_AMR_CURRENT); ASSERT_EQ(OSP_AMR_FINEST, VKL_AMR_FINEST); ASSERT_EQ(OSP_AMR_OCTANT, VKL_AMR_OCTANT); } TEST(Enums, RTCSubdivisionMode) { ASSERT_LE(sizeof(OSPSubdivisionMode), sizeof(RTCSubdivisionMode)); ASSERT_EQ(OSP_SUBDIVISION_NO_BOUNDARY, RTC_SUBDIVISION_MODE_NO_BOUNDARY); ASSERT_EQ( OSP_SUBDIVISION_SMOOTH_BOUNDARY, RTC_SUBDIVISION_MODE_SMOOTH_BOUNDARY); ASSERT_EQ(OSP_SUBDIVISION_PIN_CORNERS, RTC_SUBDIVISION_MODE_PIN_CORNERS); ASSERT_EQ(OSP_SUBDIVISION_PIN_BOUNDARY, RTC_SUBDIVISION_MODE_PIN_BOUNDARY); ASSERT_EQ(OSP_SUBDIVISION_PIN_ALL, RTC_SUBDIVISION_MODE_PIN_ALL); } <|endoftext|>
<commit_before>#include <TestCases/IO/Socket/InetAddrTest.h> namespace vprTest { CPPUNIT_TEST_SUITE_REGISTRATION( InetAddrTest ); void InetAddrTest::testEqual() { vpr::InetAddr addr1; addr1.setPort(80); vpr::InetAddr addr2; addr2.setPort(21); vpr::InetAddr addr3; addr3.setPort(80); CPPUNIT_ASSERT(addr1 != addr2); CPPUNIT_ASSERT(addr1 == addr3); addr1.setAddress(23, addr1.getPort()); addr3.setAddress(23, addr3.getPort()); CPPUNIT_ASSERT(addr1 == addr3); addr3.setAddress(17, addr3.getPort()); CPPUNIT_ASSERT(addr1 != addr3); } void InetAddrTest::testSets() { vpr::InetAddr addr1; addr1.setPort(23); CPPUNIT_ASSERT(23 == addr1.getPort()); addr1.setAddress(1221, addr1.getPort()); CPPUNIT_ASSERT(1221 == addr1.getAddressValue()); } void InetAddrTest::testAddressLookup () { vpr::InetAddr addr1; vpr::InetAddr addr2; vpr::InetAddr addr3; vpr::InetAddr addr4; vpr::InetAddr addr5; vpr::InetAddr local_addr; CPPUNIT_ASSERT_NO_THROW_MESSAGE("", addr1.setAddress("192.49.3.2", 13768)); CPPUNIT_ASSERT_NO_THROW_MESSAGE("", addr2.setAddress((vpr::Uint32)3224437506u, 13768)); CPPUNIT_ASSERT_NO_THROW_MESSAGE("", addr3.setAddress("cruncher.vrac.iastate.edu", 13768)); CPPUNIT_ASSERT_NO_THROW_MESSAGE("", addr4.setAddress("129.186.232.58", 13768)); CPPUNIT_ASSERT_NO_THROW_MESSAGE("", addr5.setAddress("cruncher.vrac.iastate.edu:13768")); CPPUNIT_ASSERT_NO_THROW_MESSAGE("", local_addr.setAddress("localhost", 0)); CPPUNIT_ASSERT(local_addr.getAddressValue() > 0); CPPUNIT_ASSERT(addr1.getAddressValue() == 3224437506u); CPPUNIT_ASSERT(addr1 == addr2); #ifndef VPR_SIMULATOR CPPUNIT_ASSERT(addr3.getAddressValue() == addr4.getAddressValue()); CPPUNIT_ASSERT(addr3.getAddressString() == addr4.getAddressString()); CPPUNIT_ASSERT(addr3 == addr4); std::string addr3_hn, addr4_hn; CPPUNIT_ASSERT_NO_THROW_MESSAGE("", addr3_hn = addr3.getHostname()); CPPUNIT_ASSERT_NO_THROW_MESSAGE("", addr4_hn = addr4.getHostname()); CPPUNIT_ASSERT(addr3_hn == addr4_hn); CPPUNIT_ASSERT(addr3 == addr5); #endif } void InetAddrTest::testLocalAddressLookup () { vpr::InetAddr empty_addr, local_addr; CPPUNIT_ASSERT(empty_addr == local_addr && "Default addresses not equal"); CPPUNIT_ASSERT_NO_THROW_MESSAGE("Local host lookup failed", local_addr = vpr::InetAddr::getLocalHost()); CPPUNIT_ASSERT(empty_addr != local_addr && "Default addresses not equal"); } void InetAddrTest::testGetAllLocalAddrs() { // Set up a localhost address with port 0. This will be used below for // determining whether the loopback address is included with the addresses // returned by vpr::InetAddr::getAllLocalAdddrs(). vpr::InetAddr localhost; localhost.setAddress("127.0.0.1"); localhost.setPort(0); vpr::InetAddr default_addr = vpr::InetAddr::getLocalHost(); // Get all local addresses without loopback. try { std::vector<vpr::InetAddr>::iterator a; std::vector<vpr::InetAddr> addrs = vpr::InetAddr::getAllLocalAddrs(); a = std::find(addrs.begin(), addrs.end(), localhost); CPPUNIT_ASSERT(a == addrs.end() && "Loopback should not be present"); if ( ! addrs.empty() ) { a = std::find(addrs.begin(), addrs.end(), default_addr); CPPUNIT_ASSERT(a != addrs.end() && "Default address not in addrs"); } } catch (vpr::Exception&) { CPPUNIT_ASSERT(false && "Caught vpr::Exception"); } // Get all local addresses with loopback. try { std::vector<vpr::InetAddr>::iterator a; std::vector<vpr::InetAddr> addrs = vpr::InetAddr::getAllLocalAddrs(true); a = std::find(addrs.begin(), addrs.end(), localhost); CPPUNIT_ASSERT(a != addrs.end() && "Loopback should be present"); a = std::find(addrs.begin(), addrs.end(), default_addr); CPPUNIT_ASSERT(a != addrs.end() && "Default address not in addrs"); } catch (vpr::Exception&) { CPPUNIT_ASSERT(false && "Caught vpr::Exception"); } } } // End of vprTest namespace <commit_msg>- Add missing algorithm header.<commit_after>#include <TestCases/IO/Socket/InetAddrTest.h> #include <algorithm> namespace vprTest { CPPUNIT_TEST_SUITE_REGISTRATION( InetAddrTest ); void InetAddrTest::testEqual() { vpr::InetAddr addr1; addr1.setPort(80); vpr::InetAddr addr2; addr2.setPort(21); vpr::InetAddr addr3; addr3.setPort(80); CPPUNIT_ASSERT(addr1 != addr2); CPPUNIT_ASSERT(addr1 == addr3); addr1.setAddress(23, addr1.getPort()); addr3.setAddress(23, addr3.getPort()); CPPUNIT_ASSERT(addr1 == addr3); addr3.setAddress(17, addr3.getPort()); CPPUNIT_ASSERT(addr1 != addr3); } void InetAddrTest::testSets() { vpr::InetAddr addr1; addr1.setPort(23); CPPUNIT_ASSERT(23 == addr1.getPort()); addr1.setAddress(1221, addr1.getPort()); CPPUNIT_ASSERT(1221 == addr1.getAddressValue()); } void InetAddrTest::testAddressLookup () { vpr::InetAddr addr1; vpr::InetAddr addr2; vpr::InetAddr addr3; vpr::InetAddr addr4; vpr::InetAddr addr5; vpr::InetAddr local_addr; CPPUNIT_ASSERT_NO_THROW_MESSAGE("", addr1.setAddress("192.49.3.2", 13768)); CPPUNIT_ASSERT_NO_THROW_MESSAGE("", addr2.setAddress((vpr::Uint32)3224437506u, 13768)); CPPUNIT_ASSERT_NO_THROW_MESSAGE("", addr3.setAddress("cruncher.vrac.iastate.edu", 13768)); CPPUNIT_ASSERT_NO_THROW_MESSAGE("", addr4.setAddress("129.186.232.58", 13768)); CPPUNIT_ASSERT_NO_THROW_MESSAGE("", addr5.setAddress("cruncher.vrac.iastate.edu:13768")); CPPUNIT_ASSERT_NO_THROW_MESSAGE("", local_addr.setAddress("localhost", 0)); CPPUNIT_ASSERT(local_addr.getAddressValue() > 0); CPPUNIT_ASSERT(addr1.getAddressValue() == 3224437506u); CPPUNIT_ASSERT(addr1 == addr2); #ifndef VPR_SIMULATOR CPPUNIT_ASSERT(addr3.getAddressValue() == addr4.getAddressValue()); CPPUNIT_ASSERT(addr3.getAddressString() == addr4.getAddressString()); CPPUNIT_ASSERT(addr3 == addr4); std::string addr3_hn, addr4_hn; CPPUNIT_ASSERT_NO_THROW_MESSAGE("", addr3_hn = addr3.getHostname()); CPPUNIT_ASSERT_NO_THROW_MESSAGE("", addr4_hn = addr4.getHostname()); CPPUNIT_ASSERT(addr3_hn == addr4_hn); CPPUNIT_ASSERT(addr3 == addr5); #endif } void InetAddrTest::testLocalAddressLookup () { vpr::InetAddr empty_addr, local_addr; CPPUNIT_ASSERT(empty_addr == local_addr && "Default addresses not equal"); CPPUNIT_ASSERT_NO_THROW_MESSAGE("Local host lookup failed", local_addr = vpr::InetAddr::getLocalHost()); CPPUNIT_ASSERT(empty_addr != local_addr && "Default addresses not equal"); } void InetAddrTest::testGetAllLocalAddrs() { // Set up a localhost address with port 0. This will be used below for // determining whether the loopback address is included with the addresses // returned by vpr::InetAddr::getAllLocalAdddrs(). vpr::InetAddr localhost; localhost.setAddress("127.0.0.1"); localhost.setPort(0); vpr::InetAddr default_addr = vpr::InetAddr::getLocalHost(); // Get all local addresses without loopback. try { std::vector<vpr::InetAddr>::iterator a; std::vector<vpr::InetAddr> addrs = vpr::InetAddr::getAllLocalAddrs(); a = std::find(addrs.begin(), addrs.end(), localhost); CPPUNIT_ASSERT(a == addrs.end() && "Loopback should not be present"); if ( ! addrs.empty() ) { a = std::find(addrs.begin(), addrs.end(), default_addr); CPPUNIT_ASSERT(a != addrs.end() && "Default address not in addrs"); } } catch (vpr::Exception&) { CPPUNIT_ASSERT(false && "Caught vpr::Exception"); } // Get all local addresses with loopback. try { std::vector<vpr::InetAddr>::iterator a; std::vector<vpr::InetAddr> addrs = vpr::InetAddr::getAllLocalAddrs(true); a = std::find(addrs.begin(), addrs.end(), localhost); CPPUNIT_ASSERT(a != addrs.end() && "Loopback should be present"); a = std::find(addrs.begin(), addrs.end(), default_addr); CPPUNIT_ASSERT(a != addrs.end() && "Default address not in addrs"); } catch (vpr::Exception&) { CPPUNIT_ASSERT(false && "Caught vpr::Exception"); } } } // End of vprTest namespace <|endoftext|>
<commit_before>// Copyright (c) 2015 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "atom/browser/api/atom_api_cookies.h" #include "atom/common/native_mate_converters/callback.h" #include "atom/common/native_mate_converters/gurl_converter.h" #include "atom/common/native_mate_converters/value_converter.h" #include "base/time/time.h" #include "base/values.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_thread.h" #include "native_mate/dictionary.h" #include "native_mate/object_template_builder.h" #include "net/cookies/cookie_monster.h" #include "net/cookies/cookie_store.h" #include "net/cookies/cookie_util.h" #include "net/url_request/url_request_context.h" #include "net/url_request/url_request_context_getter.h" using content::BrowserThread; namespace mate { template<> struct Converter<atom::api::Cookies::Error> { static v8::Local<v8::Value> ToV8(v8::Isolate* isolate, atom::api::Cookies::Error val) { if (val == atom::api::Cookies::SUCCESS) return v8::Null(isolate); else return v8::Exception::Error(StringToV8(isolate, "failed")); } }; template<> struct Converter<net::CanonicalCookie> { static v8::Local<v8::Value> ToV8(v8::Isolate* isolate, const net::CanonicalCookie& val) { mate::Dictionary dict(isolate, v8::Object::New(isolate)); dict.Set("name", val.Name()); dict.Set("value", val.Value()); dict.Set("domain", val.Domain()); dict.Set("hostOnly", net::cookie_util::DomainIsHostOnly(val.Domain())); dict.Set("path", val.Path()); dict.Set("secure", val.IsSecure()); dict.Set("httpOnly", val.IsHttpOnly()); dict.Set("session", !val.IsPersistent()); if (val.IsPersistent()) dict.Set("expirationDate", val.ExpiryDate().ToDoubleT()); return dict.GetHandle(); } }; } // namespace mate namespace atom { namespace api { namespace { // Returns whether |domain| matches |filter|. bool MatchesDomain(std::string filter, const std::string& domain) { // Add a leading '.' character to the filter domain if it doesn't exist. if (net::cookie_util::DomainIsHostOnly(filter)) filter.insert(0, "."); std::string sub_domain(domain); // Strip any leading '.' character from the input cookie domain. if (!net::cookie_util::DomainIsHostOnly(sub_domain)) sub_domain = sub_domain.substr(1); // Now check whether the domain argument is a subdomain of the filter domain. for (sub_domain.insert(0, "."); sub_domain.length() >= filter.length();) { if (sub_domain == filter) return true; const size_t next_dot = sub_domain.find('.', 1); // Skip over leading dot. sub_domain.erase(0, next_dot); } return false; } // Returns whether |cookie| matches |filter|. bool MatchesCookie(const base::DictionaryValue* filter, const net::CanonicalCookie& cookie) { std::string str; bool b; if (filter->GetString("name", &str) && str != cookie.Name()) return false; if (filter->GetString("path", &str) && str != cookie.Path()) return false; if (filter->GetString("domain", &str) && !MatchesDomain(str, cookie.Domain())) return false; if (filter->GetBoolean("secure", &b) && b != cookie.IsSecure()) return false; if (filter->GetBoolean("session", &b) && b != !cookie.IsPersistent()) return false; return true; } // Helper to returns the CookieStore. inline net::CookieStore* GetCookieStore( scoped_refptr<net::URLRequestContextGetter> getter) { return getter->GetURLRequestContext()->cookie_store(); } // Run |callback| on UI thread. void RunCallbackInUI(const base::Closure& callback) { BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, callback); } // Remove cookies from |list| not matching |filter|, and pass it to |callback|. void FilterCookies(scoped_ptr<base::DictionaryValue> filter, const Cookies::GetCallback& callback, const net::CookieList& list) { net::CookieList result; for (const auto& cookie : list) { if (MatchesCookie(filter.get(), cookie)) result.push_back(cookie); } RunCallbackInUI(base::Bind(callback, Cookies::SUCCESS, result)); } // Receives cookies matching |filter| in IO thread. void GetCookiesOnIO(scoped_refptr<net::URLRequestContextGetter> getter, scoped_ptr<base::DictionaryValue> filter, const Cookies::GetCallback& callback) { std::string url; filter->GetString("url", &url); auto filtered_callback = base::Bind(FilterCookies, base::Passed(&filter), callback); // Empty url will match all url cookies. if (url.empty()) GetCookieStore(getter)->GetAllCookiesAsync(filtered_callback); else GetCookieStore(getter)->GetAllCookiesForURLAsync(GURL(url), filtered_callback); } // Removes cookie with |url| and |name| in IO thread. void RemoveCookieOnIOThread(scoped_refptr<net::URLRequestContextGetter> getter, const GURL& url, const std::string& name, const base::Closure& callback) { GetCookieStore(getter)->DeleteCookieAsync( url, name, base::Bind(RunCallbackInUI, callback)); } // Callback of SetCookie. void OnSetCookie(const Cookies::SetCallback& callback, bool success) { RunCallbackInUI( base::Bind(callback, success ? Cookies::SUCCESS : Cookies::FAILED)); } // Sets cookie with |details| in IO thread. void SetCookieOnIO(scoped_refptr<net::URLRequestContextGetter> getter, scoped_ptr<base::DictionaryValue> details, const Cookies::SetCallback& callback) { std::string url, name, value, domain, path; bool secure = false; bool http_only = false; double creation_date; double expiration_date; double last_access_date; details->GetString("url", &url); details->GetString("name", &name); details->GetString("value", &value); details->GetString("domain", &domain); details->GetString("path", &path); details->GetBoolean("secure", &secure); details->GetBoolean("httpOnly", &http_only); base::Time creation_time; if (details->GetDouble("creationDate", &creation_date)) { creation_time = (creation_date == 0) ? base::Time::UnixEpoch() : base::Time::FromDoubleT(creation_date); } base::Time expiration_time; if (details->GetDouble("expirationDate", &expiration_date)) { expiration_time = (expiration_date == 0) ? base::Time::UnixEpoch() : base::Time::FromDoubleT(expiration_date); } base::Time last_access_time; if (details->GetDouble("lastAccessDate", &last_access_date)) { last_access_time = (last_access_date == 0) ? base::Time::UnixEpoch() : base::Time::FromDoubleT(last_access_date); } GetCookieStore(getter)->SetCookieWithDetailsAsync( GURL(url), name, value, domain, path, creation_time, expiration_time, last_access_time, secure, http_only, false, false, net::COOKIE_PRIORITY_DEFAULT, base::Bind(OnSetCookie, callback)); } } // namespace Cookies::Cookies(v8::Isolate* isolate, content::BrowserContext* browser_context) : request_context_getter_(browser_context->GetRequestContext()) { Init(isolate); } Cookies::~Cookies() { } void Cookies::Get(const base::DictionaryValue& filter, const GetCallback& callback) { scoped_ptr<base::DictionaryValue> copied(filter.CreateDeepCopy()); auto getter = make_scoped_refptr(request_context_getter_); content::BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(GetCookiesOnIO, getter, Passed(&copied), callback)); } void Cookies::Remove(const GURL& url, const std::string& name, const base::Closure& callback) { auto getter = make_scoped_refptr(request_context_getter_); content::BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(RemoveCookieOnIOThread, getter, url, name, callback)); } void Cookies::Set(const base::DictionaryValue& details, const SetCallback& callback) { scoped_ptr<base::DictionaryValue> copied(details.CreateDeepCopy()); auto getter = make_scoped_refptr(request_context_getter_); content::BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(SetCookieOnIO, getter, Passed(&copied), callback)); } // static mate::Handle<Cookies> Cookies::Create( v8::Isolate* isolate, content::BrowserContext* browser_context) { return mate::CreateHandle(isolate, new Cookies(isolate, browser_context)); } // static void Cookies::BuildPrototype(v8::Isolate* isolate, v8::Local<v8::ObjectTemplate> prototype) { mate::ObjectTemplateBuilder(isolate, prototype) .SetMethod("get", &Cookies::Get) .SetMethod("remove", &Cookies::Remove) .SetMethod("set", &Cookies::Set); } } // namespace api } // namespace atom <commit_msg>Fix GURL coonstructor from webkit string error<commit_after>// Copyright (c) 2015 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "atom/browser/api/atom_api_cookies.h" #include "atom/common/native_mate_converters/callback.h" #include "atom/common/native_mate_converters/gurl_converter.h" #include "atom/common/native_mate_converters/value_converter.h" #include "base/time/time.h" #include "base/values.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_thread.h" #include "native_mate/dictionary.h" #include "native_mate/object_template_builder.h" #include "net/cookies/cookie_monster.h" #include "net/cookies/cookie_store.h" #include "net/cookies/cookie_util.h" #include "net/url_request/url_request_context.h" #include "net/url_request/url_request_context_getter.h" using content::BrowserThread; namespace mate { template<> struct Converter<atom::api::Cookies::Error> { static v8::Local<v8::Value> ToV8(v8::Isolate* isolate, atom::api::Cookies::Error val) { if (val == atom::api::Cookies::SUCCESS) return v8::Null(isolate); else return v8::Exception::Error(StringToV8(isolate, "failed")); } }; template<> struct Converter<net::CanonicalCookie> { static v8::Local<v8::Value> ToV8(v8::Isolate* isolate, const net::CanonicalCookie& val) { mate::Dictionary dict(isolate, v8::Object::New(isolate)); dict.Set("name", val.Name()); dict.Set("value", val.Value()); dict.Set("domain", val.Domain()); dict.Set("hostOnly", net::cookie_util::DomainIsHostOnly(val.Domain())); dict.Set("path", val.Path()); dict.Set("secure", val.IsSecure()); dict.Set("httpOnly", val.IsHttpOnly()); dict.Set("session", !val.IsPersistent()); if (val.IsPersistent()) dict.Set("expirationDate", val.ExpiryDate().ToDoubleT()); return dict.GetHandle(); } }; } // namespace mate namespace atom { namespace api { namespace { // Returns whether |domain| matches |filter|. bool MatchesDomain(std::string filter, const std::string& domain) { // Add a leading '.' character to the filter domain if it doesn't exist. if (net::cookie_util::DomainIsHostOnly(filter)) filter.insert(0, "."); std::string sub_domain(domain); // Strip any leading '.' character from the input cookie domain. if (!net::cookie_util::DomainIsHostOnly(sub_domain)) sub_domain = sub_domain.substr(1); // Now check whether the domain argument is a subdomain of the filter domain. for (sub_domain.insert(0, "."); sub_domain.length() >= filter.length();) { if (sub_domain == filter) return true; const size_t next_dot = sub_domain.find('.', 1); // Skip over leading dot. sub_domain.erase(0, next_dot); } return false; } // Returns whether |cookie| matches |filter|. bool MatchesCookie(const base::DictionaryValue* filter, const net::CanonicalCookie& cookie) { std::string str; bool b; if (filter->GetString("name", &str) && str != cookie.Name()) return false; if (filter->GetString("path", &str) && str != cookie.Path()) return false; if (filter->GetString("domain", &str) && !MatchesDomain(str, cookie.Domain())) return false; if (filter->GetBoolean("secure", &b) && b != cookie.IsSecure()) return false; if (filter->GetBoolean("session", &b) && b != !cookie.IsPersistent()) return false; return true; } // Helper to returns the CookieStore. inline net::CookieStore* GetCookieStore( scoped_refptr<net::URLRequestContextGetter> getter) { return getter->GetURLRequestContext()->cookie_store(); } // Run |callback| on UI thread. void RunCallbackInUI(const base::Closure& callback) { BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, callback); } // Remove cookies from |list| not matching |filter|, and pass it to |callback|. void FilterCookies(scoped_ptr<base::DictionaryValue> filter, const Cookies::GetCallback& callback, const net::CookieList& list) { net::CookieList result; for (const auto& cookie : list) { if (MatchesCookie(filter.get(), cookie)) result.push_back(cookie); } RunCallbackInUI(base::Bind(callback, Cookies::SUCCESS, result)); } // Receives cookies matching |filter| in IO thread. void GetCookiesOnIO(scoped_refptr<net::URLRequestContextGetter> getter, scoped_ptr<base::DictionaryValue> filter, const Cookies::GetCallback& callback) { std::string url; filter->GetString("url", &url); auto filtered_callback = base::Bind(FilterCookies, base::Passed(&filter), callback); // Empty url will match all url cookies. if (url.empty()) GetCookieStore(getter)->GetAllCookiesAsync(filtered_callback); else GetCookieStore(getter)->GetAllCookiesForURLAsync(GURL(url), filtered_callback); } // Removes cookie with |url| and |name| in IO thread. void RemoveCookieOnIOThread(scoped_refptr<net::URLRequestContextGetter> getter, const GURL& url, const std::string& name, const base::Closure& callback) { GetCookieStore(getter)->DeleteCookieAsync( url, name, base::Bind(RunCallbackInUI, callback)); } // Callback of SetCookie. void OnSetCookie(const Cookies::SetCallback& callback, bool success) { RunCallbackInUI( base::Bind(callback, success ? Cookies::SUCCESS : Cookies::FAILED)); } // Sets cookie with |details| in IO thread. void SetCookieOnIO(scoped_refptr<net::URLRequestContextGetter> getter, scoped_ptr<base::DictionaryValue> details, const Cookies::SetCallback& callback) { std::string url, name, value, domain, path; bool secure = false; bool http_only = false; double creation_date; double expiration_date; double last_access_date; details->GetString("url", &url); details->GetString("name", &name); details->GetString("value", &value); details->GetString("domain", &domain); details->GetString("path", &path); details->GetBoolean("secure", &secure); details->GetBoolean("httpOnly", &http_only); base::Time creation_time; if (details->GetDouble("creationDate", &creation_date)) { creation_time = (creation_date == 0) ? base::Time::UnixEpoch() : base::Time::FromDoubleT(creation_date); } base::Time expiration_time; if (details->GetDouble("expirationDate", &expiration_date)) { expiration_time = (expiration_date == 0) ? base::Time::UnixEpoch() : base::Time::FromDoubleT(expiration_date); } base::Time last_access_time; if (details->GetDouble("lastAccessDate", &last_access_date)) { last_access_time = (last_access_date == 0) ? base::Time::UnixEpoch() : base::Time::FromDoubleT(last_access_date); } GetCookieStore(getter)->SetCookieWithDetailsAsync( GURL(url), name, value, domain, path, creation_time, expiration_time, last_access_time, secure, http_only, false, false, net::COOKIE_PRIORITY_DEFAULT, base::Bind(OnSetCookie, callback)); } } // namespace Cookies::Cookies(v8::Isolate* isolate, content::BrowserContext* browser_context) : request_context_getter_(browser_context->GetRequestContext()) { Init(isolate); } Cookies::~Cookies() { } void Cookies::Get(const base::DictionaryValue& filter, const GetCallback& callback) { scoped_ptr<base::DictionaryValue> copied(filter.CreateDeepCopy()); auto getter = make_scoped_refptr(request_context_getter_); content::BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(GetCookiesOnIO, getter, Passed(&copied), callback)); } void Cookies::Remove(const GURL& url, const std::string& name, const base::Closure& callback) { auto getter = make_scoped_refptr(request_context_getter_); content::BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(RemoveCookieOnIOThread, getter, url, name, callback)); } void Cookies::Set(const base::DictionaryValue& details, const SetCallback& callback) { scoped_ptr<base::DictionaryValue> copied(details.CreateDeepCopy()); auto getter = make_scoped_refptr(request_context_getter_); content::BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(SetCookieOnIO, getter, Passed(&copied), callback)); } // static mate::Handle<Cookies> Cookies::Create( v8::Isolate* isolate, content::BrowserContext* browser_context) { return mate::CreateHandle(isolate, new Cookies(isolate, browser_context)); } // static void Cookies::BuildPrototype(v8::Isolate* isolate, v8::Local<v8::ObjectTemplate> prototype) { mate::ObjectTemplateBuilder(isolate, prototype) .SetMethod("get", &Cookies::Get) .SetMethod("remove", &Cookies::Remove) .SetMethod("set", &Cookies::Set); } } // namespace api } // namespace atom <|endoftext|>
<commit_before>inline cov_mat_kth::cov_mat_kth( const std::string in_path, const std::string in_actionNames, const int in_scale_factor, const int in_shift, const int in_scene, //only for kth const int in_segment_length ) :path(in_path), actionNames(in_actionNames), scale_factor(in_scale_factor), shift(in_shift), scene(in_scene), segment_length(in_segment_length) { actions.load( actionNames ); } inline void cov_mat_kth::calculate( field<string> in_all_people, int in_dim ) { all_people = in_all_people; dim = in_dim; int n_actions = actions.n_rows; int n_peo = all_people.n_rows; //all_people.print("people"); for (int sc = 1; sc<=1; ++sc) //scene { for (int pe = 0; pe< n_peo; ++pe) { for (int act=0; act<n_actions; ++act) { std::stringstream load_folder; std::stringstream load_feat_video_i; std::stringstream load_labels_video_i; //cout << "Loading.." << endl; load_folder << path << "/kth-features/sc" << sc << "/scale" << scale_factor << "-shift"<< shift ; load_feat_video_i << load_folder.str() << "/" << all_people (pe) << "_" << actions(act) << "_dim" << dim << ".h5"; load_labels_video_i << load_folder.str() << "/lab_" << all_people (pe) << "_" << actions(act) << "_dim" << dim << ".h5"; //For one Video cov_mat_kth::one_video(load_feat_video_i.str(), load_labels_video_i.str(), sc, pe, act ); //getchar(); } } } } inline void cov_mat_kth::one_video( std::string load_feat_video_i, std::string load_labels_video_i, int sc, int pe, int act ) { cout << load_feat_video_i << endl; mat mat_features_video_i; vec lab_video_i; mat_features_video_i.load( load_feat_video_i, hdf5_binary ); lab_video_i.load( load_labels_video_i, hdf5_binary ); int n_vec = lab_video_i.n_elem; int last = lab_video_i( n_vec - 1 ); cout << last << endl; int s = 0; std::stringstream save_folder; save_folder << "./kth-cov-mat/sc" << sc << "/scale" << scale_factor << "-shift"<< shift ; for (int l=2; l<last-segment_length; l = l+4 ) { running_stat_vec<rowvec> stat_seg(true); //int k =0; //cout << " " << l; for (int j=l; j<=segment_length+1; ++j) { //k++; uvec indices = find(lab_video_i == j); mat tmp_feat = mat_features_video_i.cols(indices); //cout << "row&col " << tmp_feat.n_rows << " & " << tmp_feat.n_cols << endl; for (int v=0; v < tmp_feat.n_cols; ++v) { vec sample = tmp_feat.col(v); stat_seg (sample); } } cout << " " << stat_seg.count(); std::stringstream save_cov_seg; save_cov_seg << save_folder.str() << "/cov_seg" << s << "_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim << ".h5"; double THRESH = 0.000001; mat cov_seg_i = stat_seg.cov(); //Following Mehrtash suggestions as per email dated June26th 2014 cov_seg_i = 0.5*(cov_seg_i + cov_seg_i.t()); vec D; mat V; eig_sym(D, V, cov_seg_i); uvec q1 = find(D < THRESH); if (q1.n_elem>0) { for (uword pos = 0; pos < q1.n_elem; ++pos) { D( q1(pos) ) = THRESH; } cov_seg_i = V*diagmat(D)*V.t(); } //end suggestion cov_seg_i.save( save_cov_seg.str(), hdf5_binary ); s++; } std::stringstream save_seg; vec total_seg; total_seg.zeros(1); total_seg( 0 ) = s; save_seg << save_folder.str() << "/num_seg_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim << ".dat"; total_seg.save( save_seg.str(), raw_ascii ); cout << "press a key " ; getchar(); } <commit_msg>Another bug buuuuuu :( <commit_after>inline cov_mat_kth::cov_mat_kth( const std::string in_path, const std::string in_actionNames, const int in_scale_factor, const int in_shift, const int in_scene, //only for kth const int in_segment_length ) :path(in_path), actionNames(in_actionNames), scale_factor(in_scale_factor), shift(in_shift), scene(in_scene), segment_length(in_segment_length) { actions.load( actionNames ); } inline void cov_mat_kth::calculate( field<string> in_all_people, int in_dim ) { all_people = in_all_people; dim = in_dim; int n_actions = actions.n_rows; int n_peo = all_people.n_rows; //all_people.print("people"); for (int sc = 1; sc<=1; ++sc) //scene { for (int pe = 0; pe< n_peo; ++pe) { for (int act=0; act<n_actions; ++act) { std::stringstream load_folder; std::stringstream load_feat_video_i; std::stringstream load_labels_video_i; //cout << "Loading.." << endl; load_folder << path << "/kth-features/sc" << sc << "/scale" << scale_factor << "-shift"<< shift ; load_feat_video_i << load_folder.str() << "/" << all_people (pe) << "_" << actions(act) << "_dim" << dim << ".h5"; load_labels_video_i << load_folder.str() << "/lab_" << all_people (pe) << "_" << actions(act) << "_dim" << dim << ".h5"; //For one Video cov_mat_kth::one_video(load_feat_video_i.str(), load_labels_video_i.str(), sc, pe, act ); //getchar(); } } } } inline void cov_mat_kth::one_video( std::string load_feat_video_i, std::string load_labels_video_i, int sc, int pe, int act ) { cout << load_feat_video_i << endl; mat mat_features_video_i; vec lab_video_i; mat_features_video_i.load( load_feat_video_i, hdf5_binary ); lab_video_i.load( load_labels_video_i, hdf5_binary ); int n_vec = lab_video_i.n_elem; int last = lab_video_i( n_vec - 1 ); cout << last << endl; int s = 0; std::stringstream save_folder; save_folder << "./kth-cov-mat/sc" << sc << "/scale" << scale_factor << "-shift"<< shift ; for (int l=2; l<last-segment_length; l = l+4 ) { running_stat_vec<rowvec> stat_seg(true); //int k =0; //cout << " " << l; for (int j=l; j<=segment_length+1; ++j) { //k++; uvec indices = find(lab_video_i == j); mat tmp_feat = mat_features_video_i.cols(indices); cout << "row&col " << tmp_feat.n_rows << " & " << tmp_feat.n_cols << endl; for (int v=0; v < tmp_feat.n_cols; ++v) { vec sample = tmp_feat.col(v); stat_seg (sample); } } cout << " " << stat_seg.count(); std::stringstream save_cov_seg; save_cov_seg << save_folder.str() << "/cov_seg" << s << "_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim << ".h5"; double THRESH = 0.000001; mat cov_seg_i = stat_seg.cov(); //Following Mehrtash suggestions as per email dated June26th 2014 cov_seg_i = 0.5*(cov_seg_i + cov_seg_i.t()); vec D; mat V; eig_sym(D, V, cov_seg_i); uvec q1 = find(D < THRESH); if (q1.n_elem>0) { for (uword pos = 0; pos < q1.n_elem; ++pos) { D( q1(pos) ) = THRESH; } cov_seg_i = V*diagmat(D)*V.t(); } //end suggestion cov_seg_i.save( save_cov_seg.str(), hdf5_binary ); s++; } std::stringstream save_seg; vec total_seg; total_seg.zeros(1); total_seg( 0 ) = s; save_seg << save_folder.str() << "/num_seg_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim << ".dat"; total_seg.save( save_seg.str(), raw_ascii ); cout << "press a key " ; getchar(); } <|endoftext|>
<commit_before>inline cov_mat_kth::cov_mat_kth( const std::string in_path, const std::string in_actionNames, const int in_scale_factor, const int in_shift, const int in_scene, //only for kth const int in_segment_length ) :path(in_path), actionNames(in_actionNames), scale_factor(in_scale_factor), shift(in_shift), scene(in_scene), segment_length(in_segment_length) { actions.load( actionNames ); } inline void cov_mat_kth::calculate( field<string> all_people, int in_dim ) { dim = in_dim; int n_actions = actions.n_rows; int n_peo = all_people.n_rows; //all_people.print("people"); for (int sc = 1; sc<=1; ++sc) //scene { for (int pe = 0; pe< n_peo; ++pe) { for (int act=0; act<n_actions; ++act) { std::stringstream load_folder; std::stringstream load_feat_video_i; std::stringstream load_labels_video_i; cout << "Loading.." << endl; load_folder << path << "/kth-features/sc" << sc << "/scale" << scale_factor << "-shift"<< shift ; load_feat_video_i << load_folder.str() << "/" << all_people (pe) << "_" << actions(act) << "_dim" << dim << ".dat"; load_labels_video_i << load_folder.str() << "/lab_" << all_people (pe) << "_" << actions(act) << "_dim" << dim << ".dat"; //For one Video cov_mat_kth::one_video(load_feat_video_i.str(), load_labels_video_i.str() ); } } } } inline void cov_mat_kth::one_video( std::string load_feat_video_i, std::string load_labels_video_i ) { mat mat_features_video_i; vec lab_video_i; mat_features_video_i.load( load_feat_video_i, raw_ascii ); lab_video_i.load( load_labels_video_i, raw_ascii ); int n_vec = lab_video_i.n_elem; int last = lab_video_i( n_vec - 1 ); cout << last << endl; int s = 0; std::stringstream save_folder; save_folder << "./kth-cov-mat/sc" << sc << "/scale" << scale_factor << "-shift"<< shift ; for (int l=2; l<last-segment_length; l = l+4 ) { running_stat_vec<rowvec> stat_seg(true); //int k =0; cout << " " << l; for (int j=l; j<=segment_length+1; ++j) { //k++; uvec indices = find(lab_video_i == j); mat tmp_feat = mat_features_video_i.cols(indices); //cout << "row&col " << tmp_feat.n_rows << " & " << tmp_feat.n_cols << endl; for (int v=0; v < tmp_feat.n_cols; ++v) { vec sample = tmp_feat.col(v); stat_seg (sample); } } std::stringstream save_feat_video_i; save_feat_video_i << save_folder.str() << "/cov_seg" << s << "_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim << ".dat"; s++; //aca guardar el segmento y crear un txt con los nombres de los segmentos } std::stringstream save_seg; uvec total_seg = s; cout << "Loading.." << endl; save_seg << save_folder.str() << "/num_seg" << s << "_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim << ".dat"; total_seg.save( save_seg.str() ); } /* running_stat_vec<rowvec> more_stats(true); for(uword i=0; i<20; ++i) { sample = randu<rowvec>(3); sample(1) -= sample(0); sample(2) += sample(1); more_stats(sample); }*/<commit_msg>First try<commit_after>inline cov_mat_kth::cov_mat_kth( const std::string in_path, const std::string in_actionNames, const int in_scale_factor, const int in_shift, const int in_scene, //only for kth const int in_segment_length ) :path(in_path), actionNames(in_actionNames), scale_factor(in_scale_factor), shift(in_shift), scene(in_scene), segment_length(in_segment_length) { actions.load( actionNames ); } inline void cov_mat_kth::calculate( field<string> all_people, int in_dim ) { dim = in_dim; int n_actions = actions.n_rows; int n_peo = all_people.n_rows; //all_people.print("people"); for (int sc = 1; sc<=1; ++sc) //scene { for (int pe = 0; pe< n_peo; ++pe) { for (int act=0; act<n_actions; ++act) { std::stringstream load_folder; std::stringstream load_feat_video_i; std::stringstream load_labels_video_i; cout << "Loading.." << endl; load_folder << path << "/kth-features/sc" << sc << "/scale" << scale_factor << "-shift"<< shift ; load_feat_video_i << load_folder.str() << "/" << all_people (pe) << "_" << actions(act) << "_dim" << dim << ".dat"; load_labels_video_i << load_folder.str() << "/lab_" << all_people (pe) << "_" << actions(act) << "_dim" << dim << ".dat"; //For one Video cov_mat_kth::one_video(load_feat_video_i.str(), load_labels_video_i.str() ); getchar(); } } } } inline void cov_mat_kth::one_video( std::string load_feat_video_i, std::string load_labels_video_i ) { mat mat_features_video_i; vec lab_video_i; mat_features_video_i.load( load_feat_video_i, raw_ascii ); lab_video_i.load( load_labels_video_i, raw_ascii ); int n_vec = lab_video_i.n_elem; int last = lab_video_i( n_vec - 1 ); cout << last << endl; int s = 0; std::stringstream save_folder; save_folder << "./kth-cov-mat/sc" << sc << "/scale" << scale_factor << "-shift"<< shift ; for (int l=2; l<last-segment_length; l = l+4 ) { running_stat_vec<rowvec> stat_seg(true); //int k =0; cout << " " << l; for (int j=l; j<=segment_length+1; ++j) { //k++; uvec indices = find(lab_video_i == j); mat tmp_feat = mat_features_video_i.cols(indices); //cout << "row&col " << tmp_feat.n_rows << " & " << tmp_feat.n_cols << endl; for (int v=0; v < tmp_feat.n_cols; ++v) { vec sample = tmp_feat.col(v); stat_seg (sample); } } std::stringstream save_feat_video_i; save_feat_video_i << save_folder.str() << "/cov_seg" << s << "_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim << ".dat"; s++; } std::stringstream save_seg; uvec total_seg = s; cout << "Loading.." << endl; save_seg << save_folder.str() << "/num_seg" << s << "_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim << ".dat"; total_seg.save( save_seg.str() ); } /* running_stat_vec<rowvec> more_stats(true); for(uword i=0; i<20; ++i) { sample = randu<rowvec>(3); sample(1) -= sample(0); sample(2) += sample(1); more_stats(sample); }*/<|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: retstrm.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-09-07 19:25:12 $ * * 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 _STREAM_HXX //autogen #include <tools/stream.hxx> #endif #include "retstrm.hxx" #include "rcontrol.hxx" #include "svcommstream.hxx" RetStream::RetStream() { pSammel = new SvMemoryStream(); pCommStream = new SvCommStream( pSammel ); // SetCommStream( pCommStream ); } RetStream::~RetStream() { delete pCommStream; delete pSammel; } void RetStream::GenError ( SmartId aUId, String aString ) { CmdBaseStream::GenError ( &aUId, &aString ); } void RetStream::GenReturn ( USHORT nRet, SmartId aUId, String aString ) { CmdBaseStream::GenReturn ( nRet, &aUId, &aString ); } void RetStream::GenReturn ( USHORT nRet, SmartId aUId, SbxValue &aValue ) { Write(USHORT(SIReturn)); Write(nRet); Write(&aUId); Write(USHORT(PARAM_SBXVALUE_1)); // Typ der folgenden Parameter Write(aValue); } void RetStream::GenReturn ( USHORT nRet, SmartId aUId, ULONG nNr, String aString, BOOL bBool ) { CmdBaseStream::GenReturn ( nRet, &aUId, nNr, &aString, bBool ); } void RetStream::GenReturn( USHORT nRet, SmartId aUId, USHORT nMethod, String aString ) { CmdBaseStream::GenReturn ( nRet, &aUId, nMethod, &aString ); } void RetStream::GenReturn( USHORT nRet, SmartId aUId, USHORT nMethod, String aString, BOOL bBool ) { CmdBaseStream::GenReturn ( nRet, &aUId, nMethod, &aString, bBool ); } void RetStream::Write( String *pString ) { CmdBaseStream::Write( pString->GetBuffer(), pString->Len() ); } void RetStream::Write( SbxValue &aValue ) { *pSammel << USHORT( BinSbxValue ); aValue.Store( *pSammel ); } void RetStream::Write( SmartId* pId ) { DBG_ASSERT( !pId->HasString() || !pId->HasNumeric(), "SmartId contains Number and String. using String only." ) if ( pId->HasString() ) { String aTmp( pId->GetStr() ); Write( &aTmp ); } else Write( pId->GetNum() ); } SvStream* RetStream::GetStream() { return pSammel; } void RetStream::Reset () { delete pCommStream; delete pSammel; pSammel = new SvMemoryStream(); pCommStream = new SvCommStream( pSammel ); // SetCommStream( pCommStream ); } <commit_msg>INTEGRATION: CWS sixtyfour05 (1.4.30); FILE MERGED 2006/04/13 10:31:52 cmc 1.4.30.1: #i63183# automation 64bit fixes<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: retstrm.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: hr $ $Date: 2006-04-19 13:58: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 _STREAM_HXX //autogen #include <tools/stream.hxx> #endif #include "retstrm.hxx" #include "rcontrol.hxx" #include "svcommstream.hxx" RetStream::RetStream() { pSammel = new SvMemoryStream(); pCommStream = new SvCommStream( pSammel ); // SetCommStream( pCommStream ); } RetStream::~RetStream() { delete pCommStream; delete pSammel; } void RetStream::GenError ( SmartId aUId, String aString ) { CmdBaseStream::GenError ( &aUId, &aString ); } void RetStream::GenReturn ( USHORT nRet, SmartId aUId, String aString ) { CmdBaseStream::GenReturn ( nRet, &aUId, &aString ); } void RetStream::GenReturn ( USHORT nRet, SmartId aUId, SbxValue &aValue ) { Write(USHORT(SIReturn)); Write(nRet); Write(&aUId); Write(USHORT(PARAM_SBXVALUE_1)); // Typ der folgenden Parameter Write(aValue); } void RetStream::GenReturn ( USHORT nRet, SmartId aUId, comm_ULONG nNr, String aString, BOOL bBool ) { CmdBaseStream::GenReturn ( nRet, &aUId, nNr, &aString, bBool ); } void RetStream::GenReturn( USHORT nRet, SmartId aUId, comm_USHORT nMethod, String aString ) { CmdBaseStream::GenReturn ( nRet, &aUId, nMethod, &aString ); } void RetStream::GenReturn( USHORT nRet, SmartId aUId, comm_USHORT nMethod, String aString, BOOL bBool ) { CmdBaseStream::GenReturn ( nRet, &aUId, nMethod, &aString, bBool ); } void RetStream::Write( String *pString ) { CmdBaseStream::Write( pString->GetBuffer(), pString->Len() ); } void RetStream::Write( SbxValue &aValue ) { *pSammel << USHORT( BinSbxValue ); aValue.Store( *pSammel ); } void RetStream::Write( SmartId* pId ) { DBG_ASSERT( !pId->HasString() || !pId->HasNumeric(), "SmartId contains Number and String. using String only." ) if ( pId->HasString() ) { String aTmp( pId->GetStr() ); Write( &aTmp ); } else Write( static_cast<comm_ULONG>(pId->GetNum()) ); ////GetNum() ULONG != comm_ULONG on 64bit } SvStream* RetStream::GetStream() { return pSammel; } void RetStream::Reset () { delete pCommStream; delete pSammel; pSammel = new SvMemoryStream(); pCommStream = new SvCommStream( pSammel ); // SetCommStream( pCommStream ); } <|endoftext|>
<commit_before>// // Audio.cpp // Audio Test // // Created by Matthew Bucci on 2/6/14. // Copyright (c) 2014 Matthew Bucci. All rights reserved. // #include "Audio.h" AudioPlayer::AudioPlayer(Uint8 volume) { } void AudioPlayer::SetVolume(Uint8 effectvolume,Uint8 backgroundvolume) { // MusicPlayer.SetVolume(); // EffectPlayer.SetVolume(); } void AudioPlayer::ReceiveEvent(event action) { //check the event type //if player paused, pause music and effect //if effect //pass the event to the effect handler //if in battle //set the intensity } void AudioPlayer::Subscribe(ActorPlayer* user) { GameEventSubscriber::Subscribe<void(ActorPlayer*)>(&user->PlayerJumped,[this](ActorPlayer* Object) { event test; test.type="player-jump"; test.id=5; EffectPlayer.PlayEffect(test); }); GameEventSubscriber::Subscribe<void(ActorPlayer*)>(&user->PlayerLanded,[this](ActorPlayer* Object) { event test; test.type="player-land"; test.id=5; EffectPlayer.PlayEffect(test); }); GameEventSubscriber::Subscribe<void(ActorPlayer*)>(&user->PlayerWalked,[this](ActorPlayer* Object) { event test; test.type="player-left-foot"; test.id=5; EffectPlayer.PlayEffect(test); }); }<commit_msg>added alternating feet sounds<commit_after>// // Audio.cpp // Audio Test // // Created by Matthew Bucci on 2/6/14. // Copyright (c) 2014 Matthew Bucci. All rights reserved. // #include "Audio.h" AudioPlayer::AudioPlayer(Uint8 volume) { } void AudioPlayer::SetVolume(Uint8 effectvolume,Uint8 backgroundvolume) { // MusicPlayer.SetVolume(); // EffectPlayer.SetVolume(); } void AudioPlayer::ReceiveEvent(event action) { //check the event type //if player paused, pause music and effect //if effect //pass the event to the effect handler //if in battle //set the intensity } void AudioPlayer::Subscribe(ActorPlayer* user) { GameEventSubscriber::Subscribe<void(ActorPlayer*)>(&user->PlayerJumped,[this](ActorPlayer* Object) { event test; test.type="player-jump"; test.id=5; EffectPlayer.PlayEffect(test); }); GameEventSubscriber::Subscribe<void(ActorPlayer*)>(&user->PlayerLanded,[this](ActorPlayer* Object) { event test; test.type="player-land"; test.id=5; EffectPlayer.PlayEffect(test); }); GameEventSubscriber::Subscribe<void(ActorPlayer*)>(&user->PlayerWalked,[this](ActorPlayer* Object) { event test; test.type="player-walk"; test.id=5; EffectPlayer.PlayEffect(test); }); }<|endoftext|>
<commit_before>/** \brief Importer for full text documents. * \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de) * * \copyright 2018 Universitätsbibliothek Tübingen. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <stdexcept> #include <vector> #include <cstdio> #include <cstdlib> #include "FileUtil.h" #include "FullTextImport.h" #include "util.h" namespace { [[noreturn]] void Usage() { ::Usage("[--verbose] fulltext_file1 [fulltext_file2 .. fulltext_fileN]"); } bool ImportDocument(ControlNumberGuesser &control_number_guesser, const std::string &filename) { const auto input(FileUtil::OpenInputFileOrDie(filename)); FullTextImport::FullTextData full_text_data; FullTextImport::ReadExtractedTextFromDisk(input.get(), &full_text_data); std::string ppn; if (not FullTextImport::CorrelateFullTextData(control_number_guesser, full_text_data, &ppn)) return false; return true; } } // unnamed namespace int Main(int argc, char *argv[]) { if (argc < 2) Usage(); const bool verbose(std::strcmp(argv[1], "--verbose") == 0); if (verbose) --argc, ++argv; if (argc < 2) Usage(); ControlNumberGuesser control_number_guesser; unsigned total_count(0), failure_count(0); for (int arg_no(1); arg_no < argc; ++arg_no) { ++total_count; if (not ImportDocument(control_number_guesser, argv[arg_no])) ++failure_count; } LOG_INFO("Failed to import " + std::to_string(failure_count) + " documents of " + std::to_string(total_count) + "."); return EXIT_SUCCESS; } <commit_msg>First feature-complete version.<commit_after>/** \brief Importer for full text documents. * \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de) * * \copyright 2018 Universitätsbibliothek Tübingen. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <stdexcept> #include <vector> #include <cstdio> #include <cstdlib> #include "Elasticsearch.h" #include "FileUtil.h" #include "FullTextImport.h" #include "util.h" namespace { [[noreturn]] void Usage() { ::Usage("[--verbose] fulltext_file1 [fulltext_file2 .. fulltext_fileN]"); } bool ImportDocument(ControlNumberGuesser &control_number_guesser, Elasticsearch * const elasticsearch, const std::string &filename) { const auto input(FileUtil::OpenInputFileOrDie(filename)); FullTextImport::FullTextData full_text_data; FullTextImport::ReadExtractedTextFromDisk(input.get(), &full_text_data); std::string ppn; if (not FullTextImport::CorrelateFullTextData(control_number_guesser, full_text_data, &ppn)) return false; elasticsearch->insertDocument(ppn, full_text_data.full_text_); return true; } } // unnamed namespace int Main(int argc, char *argv[]) { if (argc < 2) Usage(); const bool verbose(std::strcmp(argv[1], "--verbose") == 0); if (verbose) --argc, ++argv; if (argc < 2) Usage(); ControlNumberGuesser control_number_guesser; Elasticsearch elasticsearch; unsigned total_count(0), failure_count(0); for (int arg_no(1); arg_no < argc; ++arg_no) { ++total_count; if (not ImportDocument(control_number_guesser, &elasticsearch, argv[arg_no])) ++failure_count; } LOG_INFO("Failed to import " + std::to_string(failure_count) + " documents of " + std::to_string(total_count) + "."); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* $Id$ */ # ifndef CPPAD_CPPAD_EIGEN_INCLUDED # define CPPAD_CPPAD_EIGEN_INCLUDED /* -------------------------------------------------------------------------- CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-12 Bradley M. Bell CppAD is distributed under multiple licenses. This distribution is under the terms of the Common Public License Version 1.0. A copy of this license is included in the COPYING file of this distribution. Please visit http://www.coin-or.org/CppAD/ for information on other licenses. -------------------------------------------------------------------------- */ /* $begin cppad_eigen.hpp$$ $spell atan Num acos asin CppAD std::numeric enum Mul Eigen cppad.hpp namespace struct typedef const imag sqrt exp cos $$ $section Enable Use of Eigen Linear Algebra Package with CppAD$$ $head Syntax$$ $codei%# include <cppad/example/cppad_eigen.hpp>%$$ $children% example/eigen_det.cpp %$$ $head Purpose$$ Enables the use of the $href%http://eigen.tuxfamily.org%eigen%$$ linear algebra package with the type $icode%AD<%Base%>%$$. $head Example$$ THe file $cref eigen_det.cpp$$ contains an example and test of this include file. It returns true if it succeeds and false otherwise. $head Include Files$$ This file $code cppad_eigen.hpp$$ requires the CppAD types to be defined. In addition, it needs some Eigen definitions to work properly. It assumes that the corresponding $icode Base$$ type is real; e.g., is not $code std::complex<double>$$. $codep */ # include <cppad/cppad.hpp> # include <Eigen/Core> /* $$ $head Traits$$ $codep */ namespace Eigen { template <class Base> struct NumTraits< CppAD::AD<Base> > { typedef CppAD::AD<Base> Real; typedef CppAD::AD<Base> NonInteger; typedef CppAD::AD<Base> Nested; enum { IsComplex = 0 , IsInteger = 0 , IsSigned = 1 , RequireInitialization = 1 , ReadCost = 1 , AddCost = 2 , MulCost = 2 }; }; } /* $$ $head Internal$$ Eigen using the $code internal$$ sub-namespace to access the following: $codep */ namespace CppAD { namespace internal { // standard math functions that get used as is and have prototype // template <class Base> AD<Base> fun(const AD<Base>& x) using CppAD::abs; using CppAD::acos; using CppAD::asin; using CppAD::atan; using CppAD::cos; using CppAD::cosh; using CppAD::exp; using CppAD::log; using CppAD::log10; using CppAD::sin; using CppAD::sinh; using CppAD::sqrt; using CppAD::tan; // standard math functions that get used as is and have prototype // template <class Base> // AD<Base> fun(const AD<Base>& x, const AD<Base>& y) using CppAD::pow; // functions that return references template <class Base> const AD<Base>& conj(const AD<Base>& x) { return x; } template <class Base> const AD<Base>& real(const AD<Base>& x) { return x; } // functions that return values template <class Base> AD<Base> imag(const AD<Base>& x) { return CppAD::AD<Base>(0.); } template <class Base> AD<Base> abs2(const AD<Base>& x) { return x * x; } // machine epsilon with type of real part of x template <class Base> AD<Base> epsilon(const AD<Base>& x) { return CppAD::epsilon<Base>(); } // Relaxed version of machine epsilon for comparison of different // operations that should result in the same value template <class Base> AD<Base> dummy_precision(const AD<Base>& x) { return 100. * CppAD::epsilon<Base>(); } // lowest value not yet part of CppAD API, // so just handle AD<double> case > for now. template <class Base> AD<Base> lowest(void) { return CppAD::nan( AD<Base>(0.0) ); } template <> AD<double> lowest(void) { return std::numeric_limits<double>::min(); } // highest value not yet part of CppAD API, // so just handle AD<double> case > for now. template <class Base> AD<Base> highest(void) { return CppAD::nan( AD<Base>(0.0) ); } template <> AD<double> highest(void) { return std::numeric_limits<double>::max(); } } } /* $$ $end */ # endif <commit_msg>cppad_eigen.hpp: Fix newline missing in comment.<commit_after>/* $Id$ */ # ifndef CPPAD_CPPAD_EIGEN_INCLUDED # define CPPAD_CPPAD_EIGEN_INCLUDED /* -------------------------------------------------------------------------- CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-12 Bradley M. Bell CppAD is distributed under multiple licenses. This distribution is under the terms of the Common Public License Version 1.0. A copy of this license is included in the COPYING file of this distribution. Please visit http://www.coin-or.org/CppAD/ for information on other licenses. -------------------------------------------------------------------------- */ /* $begin cppad_eigen.hpp$$ $spell atan Num acos asin CppAD std::numeric enum Mul Eigen cppad.hpp namespace struct typedef const imag sqrt exp cos $$ $section Enable Use of Eigen Linear Algebra Package with CppAD$$ $head Syntax$$ $codei%# include <cppad/example/cppad_eigen.hpp>%$$ $children% example/eigen_det.cpp %$$ $head Purpose$$ Enables the use of the $href%http://eigen.tuxfamily.org%eigen%$$ linear algebra package with the type $icode%AD<%Base%>%$$. $head Example$$ THe file $cref eigen_det.cpp$$ contains an example and test of this include file. It returns true if it succeeds and false otherwise. $head Include Files$$ This file $code cppad_eigen.hpp$$ requires the CppAD types to be defined. In addition, it needs some Eigen definitions to work properly. It assumes that the corresponding $icode Base$$ type is real; e.g., is not $code std::complex<double>$$. $codep */ # include <cppad/cppad.hpp> # include <Eigen/Core> /* $$ $head Traits$$ $codep */ namespace Eigen { template <class Base> struct NumTraits< CppAD::AD<Base> > { typedef CppAD::AD<Base> Real; typedef CppAD::AD<Base> NonInteger; typedef CppAD::AD<Base> Nested; enum { IsComplex = 0 , IsInteger = 0 , IsSigned = 1 , RequireInitialization = 1 , ReadCost = 1 , AddCost = 2 , MulCost = 2 }; }; } /* $$ $head Internal$$ Eigen using the $code internal$$ sub-namespace to access the following: $codep */ namespace CppAD { namespace internal { // standard math functions that get used as is and have prototype // template <class Base> AD<Base> fun(const AD<Base>& x) using CppAD::abs; using CppAD::acos; using CppAD::asin; using CppAD::atan; using CppAD::cos; using CppAD::cosh; using CppAD::exp; using CppAD::log; using CppAD::log10; using CppAD::sin; using CppAD::sinh; using CppAD::sqrt; using CppAD::tan; // standard math functions that get used as is and have prototype // template <class Base> // AD<Base> fun(const AD<Base>& x, const AD<Base>& y) using CppAD::pow; // functions that return references template <class Base> const AD<Base>& conj(const AD<Base>& x) { return x; } template <class Base> const AD<Base>& real(const AD<Base>& x) { return x; } // functions that return values template <class Base> AD<Base> imag(const AD<Base>& x) { return CppAD::AD<Base>(0.); } template <class Base> AD<Base> abs2(const AD<Base>& x) { return x * x; } // machine epsilon with type of real part of x template <class Base> AD<Base> epsilon(const AD<Base>& x) { return CppAD::epsilon<Base>(); } // Relaxed version of machine epsilon for comparison of different // operations that should result in the same value template <class Base> AD<Base> dummy_precision(const AD<Base>& x) { return 100. * CppAD::epsilon<Base>(); } // lowest value not yet part of CppAD API, // so just handle AD<double> case > for now. template <class Base> AD<Base> lowest(void) { return CppAD::nan( AD<Base>(0.0) ); } template <> AD<double> lowest(void) { return std::numeric_limits<double>::min(); } // highest value not yet part of CppAD API, // so just handle AD<double> case > for now. template <class Base> AD<Base> highest(void) { return CppAD::nan( AD<Base>(0.0) ); } template <> AD<double> highest(void) { return std::numeric_limits<double>::max(); } } } /* $$ $end */ # endif <|endoftext|>
<commit_before>#include "SettingsUI.h" #include <iostream> /* DLGTEMPLATEEX Structure */ #include <pshpack1.h> typedef struct DLGTEMPLATEEX { WORD dlgVer; WORD signature; DWORD helpID; DWORD exStyle; DWORD style; WORD cDlgItems; short x; short y; short cx; short cy; } DLGTEMPLATEEX, *LPDLGTEMPLATEEX; #include <poppack.h> #include "../3RVX/3RVX.h" #include "../3RVX/CommCtl.h" #include "../3RVX/LanguageTranslator.h" #include "../3RVX/Logger.h" #include "../3RVX/Settings.h" #include "Tabs/General.h" #include "Tabs/Display.h" #include "Tabs/OSD.h" #include "Tabs/Hotkeys.h" #include "Tabs/About.h" #include "UITranslator.h" #include "Updater/Updater.h" #include "Updater/UpdaterWindow.h" /* Needed to determine whether the Apply button is enabled/disabled */ static const int IDD_APPLYNOW = 0x3021; const wchar_t *MUTEX_NAME = L"Local\\3RVXSettings"; HANDLE mutex; HWND tabWnd = NULL; bool relaunch = false; int APIENTRY wWinMain( _In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPTSTR lpCmdLine, _In_ int nCmdShow) { UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); Logger::Start(); CLOG(L"Starting SettingsUI..."); bool alreadyRunning = false; mutex = CreateMutex(NULL, FALSE, MUTEX_NAME); if (GetLastError() == ERROR_ALREADY_EXISTS) { if (mutex) { ReleaseMutex(mutex); CloseHandle(mutex); } alreadyRunning = true; } /* Inspect command line parameters to determine whether this settings * instance is being launched as an update checker. */ std::wstring cmdLine(lpCmdLine); if (cmdLine.find(L"-update") != std::wstring::npos) { if (alreadyRunning) { return EXIT_SUCCESS; } else { /* If this is the only settings instance running, we release the * mutex so that the user can launch the settings app. If this * happens, the updater is closed to prevent settings file race * conditions. */ ReleaseMutex(mutex); CloseHandle(mutex); } if (Updater::NewerVersionAvailable()) { Settings::Instance()->Load(); CLOG(L"An update is available. Showing update icon."); UpdaterWindow uw; PostMessage( uw.Handle(), _3RVX::WM_3RVX_SETTINGSCTRL, _3RVX::MSG_UPDATEICON, NULL); uw.DoModal(); } else { #if defined(ENABLE_3RVX_LOG) && (defined(ENABLE_3RVX_LOGTOFILE) == FALSE) CLOG(L"No update available. Press [enter] to terminate"); std::cin.get(); #endif } /* Process was used for updates; time to quit. */ return EXIT_SUCCESS; } if (alreadyRunning) { HWND settingsWnd = _3RVX::MasterSettingsHwnd(); CLOG(L"A settings instance is already running. Moving window [%d] " L"to the foreground.", (int) settingsWnd); SetForegroundWindow(settingsWnd); SendMessage( settingsWnd, _3RVX::WM_3RVX_SETTINGSCTRL, _3RVX::MSG_ACTIVATE, NULL); #if defined(ENABLE_3RVX_LOG) && (defined(ENABLE_3RVX_LOGTOFILE) == FALSE) CLOG(L"Press [enter] to terminate"); std::cin.get(); #endif return EXIT_SUCCESS; } HWND updater = _3RVX::UpdaterHwnd(); if (updater != 0) { CLOG(L"Telling updater to close"); SendMessage(updater, WM_CLOSE, 0, 0); } SettingsUI mainWnd(hInstance); INT_PTR result; do { result = mainWnd.LaunchPropertySheet(); CLOG(L"Relaunch: %s", relaunch ? L"TRUE" : L"FALSE"); } while (relaunch == true); return result; } SettingsUI::SettingsUI(HINSTANCE hInstance) : Window( Window::Builder(_3RVX::CLASS_3RVX_SETTINGS) .Title(_3RVX::CLASS_3RVX_SETTINGS) .InstanceHandle(hInstance) .Icon(LoadIcon(NULL, MAKEINTRESOURCE(IDI_SETTINGS))) .Build()) { Settings::Instance()->Load(); _tabs.push_back((_general = new General)); _tabs.push_back((_display = new Display)); _tabs.push_back((_osd = new OSD)); _tabs.push_back((_hotkeys = new Hotkeys)); _tabs.push_back((_about = new About)); } INT_PTR SettingsUI::LaunchPropertySheet() { HPROPSHEETPAGE *pages = new HPROPSHEETPAGE[_tabs.size()]; for (size_t i = 0; i < _tabs.size(); ++i) { pages[i] = _tabs[i]->PageHandle(); } PROPSHEETHEADER psh = { 0 }; psh.dwSize = sizeof(PROPSHEETHEADER); psh.dwFlags = PSH_USEICONID | PSH_USECALLBACK; psh.hwndParent = Window::Handle(); psh.hInstance = Window::InstanceHandle(); psh.pszIcon = MAKEINTRESOURCE(IDI_SETTINGS); psh.pszCaption = L"3RVX Settings"; psh.nStartPage = 0; psh.nPages = _tabs.size(); psh.phpage = pages; psh.pfnCallback = PropSheetProc; tabWnd = NULL; /* Position the window if this is the first launch */ if (relaunch == false) { POINT pt = { 0 }; GetCursorPos(&pt); MoveWindow(Window::Handle(), pt.x - XOFFSET, pt.y - YOFFSET, 0, 0, TRUE); } relaunch = false; CLOG(L"Launching modal property sheet."); return PropertySheet(&psh); } LRESULT SettingsUI::WndProc( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_DESTROY: PostQuitMessage(0); break; } if (message == _3RVX::WM_3RVX_SETTINGSCTRL) { switch (wParam) { case _3RVX::MSG_ACTIVATE: CLOG(L"Received request to activate window from external program"); SetActiveWindow(tabWnd); break; case _3RVX::MSG_MUSTRESTART: relaunch = true; break; } } return Window::WndProc(hWnd, message, wParam, lParam); } int CALLBACK PropSheetProc(HWND hWnd, UINT msg, LPARAM lParam) { switch (msg) { case PSCB_PRECREATE: /* Disable the help button: */ if (((LPDLGTEMPLATEEX) lParam)->signature == 0xFFFF) { ((LPDLGTEMPLATEEX) lParam)->style &= ~DS_CONTEXTHELP; } else { ((LPDLGTEMPLATE) lParam)->style &= ~DS_CONTEXTHELP; } /* Show window in the taskbar: */ ((LPDLGTEMPLATE) lParam)->dwExtendedStyle |= WS_EX_APPWINDOW; break; case PSCB_INITIALIZED: UITranslator::TranslateWindowText(hWnd); if (tabWnd == NULL) { tabWnd = hWnd; } /* These values are hard-coded in case the user has a non-english GUI but wants to change the program language */ UITranslator::TranslateControlText( hWnd, IDOK, std::wstring(L"OK")); UITranslator::TranslateControlText( hWnd, IDCANCEL, std::wstring(L"Cancel")); UITranslator::TranslateControlText( hWnd, IDD_APPLYNOW, std::wstring(L"Apply")); break; case PSCB_BUTTONPRESSED: if (lParam == PSBTN_OK || lParam == PSBTN_APPLYNOW) { HWND hApply = GetDlgItem(hWnd, IDD_APPLYNOW); if (IsWindowEnabled(hApply)) { /* Save settings*/ CLOG(L"Saving settings..."); // for (SettingsTab *tab : _tabs) { // tab->SaveSettings(); // } Settings::Instance()->Save(); CLOG(L"Notifying 3RVX process of settings change"); _3RVX::Message(_3RVX::MSG_LOAD, NULL, true); if (lParam == PSBTN_APPLYNOW && relaunch == true) { /* Language was changed */ SendMessage(tabWnd, WM_CLOSE, NULL, NULL); } else { relaunch = false; } } } break; } return TRUE; }<commit_msg>Simplify WndProc handling<commit_after>#include "SettingsUI.h" #include <iostream> /* DLGTEMPLATEEX Structure */ #include <pshpack1.h> typedef struct DLGTEMPLATEEX { WORD dlgVer; WORD signature; DWORD helpID; DWORD exStyle; DWORD style; WORD cDlgItems; short x; short y; short cx; short cy; } DLGTEMPLATEEX, *LPDLGTEMPLATEEX; #include <poppack.h> #include "../3RVX/3RVX.h" #include "../3RVX/CommCtl.h" #include "../3RVX/LanguageTranslator.h" #include "../3RVX/Logger.h" #include "../3RVX/Settings.h" #include "Tabs/General.h" #include "Tabs/Display.h" #include "Tabs/OSD.h" #include "Tabs/Hotkeys.h" #include "Tabs/About.h" #include "UITranslator.h" #include "Updater/Updater.h" #include "Updater/UpdaterWindow.h" /* Needed to determine whether the Apply button is enabled/disabled */ static const int IDD_APPLYNOW = 0x3021; const wchar_t *MUTEX_NAME = L"Local\\3RVXSettings"; HANDLE mutex; HWND tabWnd = NULL; bool relaunch = false; int APIENTRY wWinMain( _In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPTSTR lpCmdLine, _In_ int nCmdShow) { UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); Logger::Start(); CLOG(L"Starting SettingsUI..."); bool alreadyRunning = false; mutex = CreateMutex(NULL, FALSE, MUTEX_NAME); if (GetLastError() == ERROR_ALREADY_EXISTS) { if (mutex) { ReleaseMutex(mutex); CloseHandle(mutex); } alreadyRunning = true; } /* Inspect command line parameters to determine whether this settings * instance is being launched as an update checker. */ std::wstring cmdLine(lpCmdLine); if (cmdLine.find(L"-update") != std::wstring::npos) { if (alreadyRunning) { return EXIT_SUCCESS; } else { /* If this is the only settings instance running, we release the * mutex so that the user can launch the settings app. If this * happens, the updater is closed to prevent settings file race * conditions. */ ReleaseMutex(mutex); CloseHandle(mutex); } if (Updater::NewerVersionAvailable()) { Settings::Instance()->Load(); CLOG(L"An update is available. Showing update icon."); UpdaterWindow uw; PostMessage( uw.Handle(), _3RVX::WM_3RVX_SETTINGSCTRL, _3RVX::MSG_UPDATEICON, NULL); uw.DoModal(); } else { #if defined(ENABLE_3RVX_LOG) && (defined(ENABLE_3RVX_LOGTOFILE) == FALSE) CLOG(L"No update available. Press [enter] to terminate"); std::cin.get(); #endif } /* Process was used for updates; time to quit. */ return EXIT_SUCCESS; } if (alreadyRunning) { HWND settingsWnd = _3RVX::MasterSettingsHwnd(); CLOG(L"A settings instance is already running. Moving window [%d] " L"to the foreground.", (int) settingsWnd); SetForegroundWindow(settingsWnd); SendMessage( settingsWnd, _3RVX::WM_3RVX_SETTINGSCTRL, _3RVX::MSG_ACTIVATE, NULL); #if defined(ENABLE_3RVX_LOG) && (defined(ENABLE_3RVX_LOGTOFILE) == FALSE) CLOG(L"Press [enter] to terminate"); std::cin.get(); #endif return EXIT_SUCCESS; } HWND updater = _3RVX::UpdaterHwnd(); if (updater != 0) { CLOG(L"Telling updater to close"); SendMessage(updater, WM_CLOSE, 0, 0); } SettingsUI mainWnd(hInstance); INT_PTR result; do { result = mainWnd.LaunchPropertySheet(); CLOG(L"Relaunch: %s", relaunch ? L"TRUE" : L"FALSE"); } while (relaunch == true); return result; } SettingsUI::SettingsUI(HINSTANCE hInstance) : Window( Window::Builder(_3RVX::CLASS_3RVX_SETTINGS) .Title(_3RVX::CLASS_3RVX_SETTINGS) .InstanceHandle(hInstance) .Icon(LoadIcon(NULL, MAKEINTRESOURCE(IDI_SETTINGS))) .Build()) { Settings::Instance()->Load(); _tabs.push_back((_general = new General)); _tabs.push_back((_display = new Display)); _tabs.push_back((_osd = new OSD)); _tabs.push_back((_hotkeys = new Hotkeys)); _tabs.push_back((_about = new About)); } INT_PTR SettingsUI::LaunchPropertySheet() { HPROPSHEETPAGE *pages = new HPROPSHEETPAGE[_tabs.size()]; for (size_t i = 0; i < _tabs.size(); ++i) { pages[i] = _tabs[i]->PageHandle(); } PROPSHEETHEADER psh = { 0 }; psh.dwSize = sizeof(PROPSHEETHEADER); psh.dwFlags = PSH_USEICONID | PSH_USECALLBACK; psh.hwndParent = Window::Handle(); psh.hInstance = Window::InstanceHandle(); psh.pszIcon = MAKEINTRESOURCE(IDI_SETTINGS); psh.pszCaption = L"3RVX Settings"; psh.nStartPage = 0; psh.nPages = _tabs.size(); psh.phpage = pages; psh.pfnCallback = PropSheetProc; tabWnd = NULL; /* Position the window if this is the first launch */ if (relaunch == false) { POINT pt = { 0 }; GetCursorPos(&pt); MoveWindow(Window::Handle(), pt.x - XOFFSET, pt.y - YOFFSET, 0, 0, TRUE); } relaunch = false; CLOG(L"Launching modal property sheet."); return PropertySheet(&psh); } LRESULT SettingsUI::WndProc( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { if (message == WM_DESTROY) { PostQuitMessage(0); } else if (message == _3RVX::WM_3RVX_SETTINGSCTRL) { switch (wParam) { case _3RVX::MSG_ACTIVATE: CLOG(L"Received request to activate window from external program"); SetActiveWindow(tabWnd); break; case _3RVX::MSG_MUSTRESTART: relaunch = true; break; } } return Window::WndProc(hWnd, message, wParam, lParam); } int CALLBACK PropSheetProc(HWND hWnd, UINT msg, LPARAM lParam) { switch (msg) { case PSCB_PRECREATE: /* Disable the help button: */ if (((LPDLGTEMPLATEEX) lParam)->signature == 0xFFFF) { ((LPDLGTEMPLATEEX) lParam)->style &= ~DS_CONTEXTHELP; } else { ((LPDLGTEMPLATE) lParam)->style &= ~DS_CONTEXTHELP; } /* Show window in the taskbar: */ ((LPDLGTEMPLATE) lParam)->dwExtendedStyle |= WS_EX_APPWINDOW; break; case PSCB_INITIALIZED: UITranslator::TranslateWindowText(hWnd); if (tabWnd == NULL) { tabWnd = hWnd; } /* These values are hard-coded in case the user has a non-english GUI but wants to change the program language */ UITranslator::TranslateControlText( hWnd, IDOK, std::wstring(L"OK")); UITranslator::TranslateControlText( hWnd, IDCANCEL, std::wstring(L"Cancel")); UITranslator::TranslateControlText( hWnd, IDD_APPLYNOW, std::wstring(L"Apply")); break; case PSCB_BUTTONPRESSED: if (lParam == PSBTN_OK || lParam == PSBTN_APPLYNOW) { HWND hApply = GetDlgItem(hWnd, IDD_APPLYNOW); if (IsWindowEnabled(hApply)) { /* Save settings*/ CLOG(L"Saving settings..."); // for (SettingsTab *tab : _tabs) { // tab->SaveSettings(); // } Settings::Instance()->Save(); CLOG(L"Notifying 3RVX process of settings change"); _3RVX::Message(_3RVX::MSG_LOAD, NULL, true); if (lParam == PSBTN_APPLYNOW && relaunch == true) { /* Language was changed */ SendMessage(tabWnd, WM_CLOSE, NULL, NULL); } else { relaunch = false; } } } break; } return TRUE; }<|endoftext|>
<commit_before>// Debugging Settings #define DEBUG #define DEBUG_V1 //#define DEBUG_V2 //#define DEBUG_V3 //#define DEBUG_V4 #include <iostream> #include <iomanip> #include <memory> #include <random> #include <iterator> #include <functional> #include <ctime> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <memory.h> #include <sys/types.h> #include <sys/wait.h> #include <math.h> #include <bsl_memory.h> #include <bslma_testallocator.h> #include <bslma_newdeleteallocator.h> #include <bsls_stopwatch.h> #include <bdlma_sequentialpool.h> #include <bdlma_sequentialallocator.h> #include <bdlma_bufferedsequentialallocator.h> #include <bdlma_multipoolallocator.h> #include <vector> #include <list> #include "benchmark_common.h" // Debugging #include <typeinfo> #include <assert.h> using namespace BloombergLP; // Global Variables #ifdef DEBUG int AF_RF_PRODUCT = 256; #else int AF_RF_PRODUCT = 2560; #endif // DEBUG // Convenience typedefs struct lists { typedef std::list<int> def; typedef std::list<int, typename alloc_adaptors<int>::newdel> newdel; typedef std::list<int, typename alloc_adaptors<int>::monotonic> monotonic; typedef std::list<int, typename alloc_adaptors<int>::multipool> multipool; typedef std::list<int, bsl::allocator<int>> polymorphic; }; struct vectors { typedef std::vector<lists::def> def; typedef std::vector<lists::newdel, typename alloc_adaptors<lists::newdel>::newdel> newdel; typedef std::vector<lists::monotonic, typename alloc_adaptors<lists::monotonic>::monotonic> monotonic; typedef std::vector<lists::multipool, typename alloc_adaptors<lists::multipool>::multipool> multipool; typedef std::vector<lists::polymorphic, bsl::allocator<int>> polymorphic; }; template<typename VECTOR> double access_lists(VECTOR *vec, int af, int rf) { #ifdef DEBUG_V3 std::cout << "Accessing Lists" << std::endl; #endif // DEBUG_V3 std::clock_t c_start = std::clock(); for (size_t r = 0; r < rf; r++) { for (size_t i = 0; i < vec->size(); i++) { for (size_t a = 0; a < af; a++) { for (auto it = (*vec)[i].begin(); it != (*vec)[i].end(); ++it) { (*it)++; // Increment int to cause loop to have some effect } clobber(); // TODO will this hurt caching? } } } std::clock_t c_end = std::clock(); return (c_end - c_start) * 1.0 / CLOCKS_PER_SEC; } template<typename VECTOR> double run_combination(int G, int S, int af, int sf, int rf, VECTOR vec) { // G = Total system size (# subsystems * elements in subsystems). Given as power of 2 (size really = 2^G) // S = Elements per subsystem. Given as power of 2 (size really = 2^S) // af = Access Factor - Number of iterations through a subsystem (linked list) before moving to the next // sf = Shuffle Factor - Number of elements popped from each list and pushed to a randomly chosen list // Note: -ve value means access occurs before shuffle // rf = Repeat Factor - Number of times the subsystems are iterated over int k = std::abs(G) - std::abs(S); size_t expanded_S = 1, expanded_k = 1; expanded_S <<= S; expanded_k <<= k; #ifdef DEBUG_V3 std::cout << "Total number of lists (k) = 2^" << k << " (aka " << expanded_k << ")" << std::endl; std::cout << "Total number of elements per sub system (S) = 2^" << S << " (aka " << expanded_S << ")" << std::endl; #endif // DEBUG_V3 // Create data under test vec.reserve(expanded_k); for (size_t i = 0; i < expanded_k; i++) { vec.emplace_back(vec.get_allocator()); for (size_t j = 0; j < expanded_S; j++) { vec.back().emplace_back((int)j); } } double result = 0.0; if (sf < 0) { // Access the data result = access_lists(&vec, af, rf); } // Shuffle the data #ifdef DEBUG_V3 std::cout << "Shuffling data " << std::abs(sf) << " times" << std::endl; #endif // DEBUG_V3 std::default_random_engine generator(1); // Consistent seed to get the same (pseudo) random distribution each time std::uniform_int_distribution<size_t> position_distribution(0, vec.size() - 1); for (size_t i = 0; i < std::abs(sf); i++) { for (size_t j = 0; j < vec.size(); j++) { vec[position_distribution(generator)].emplace_back(vec[j].front()); vec[j].pop_front(); } } if (sf > 0) { // Access the data result = access_lists(&vec, af, rf); } return result; } void generate_table(int G, int alloc_num) { int sf = 5; for (int S = 21; S >= 0; S--) { for (int af = 256; af >= 1; af >>= 1) { int rf = AF_RF_PRODUCT / af; #ifdef DEBUG_V3 std::cout << "G: " << G << " S: " << S << " af: " << af << " sf: " << sf << " rf: " << rf << std::endl; #endif int pid = fork(); if (pid == 0) { // Child process double result = 0; switch (alloc_num) { case 0: { typename vectors::def vec; result = run_combination(G, S, af, sf, rf, vec); break; } case 7: { BloombergLP::bdlma::MultipoolAllocator alloc; typename vectors::multipool vec(&alloc); result = run_combination(G, S, af, sf, rf, vec); break; } } std::cout << result << " "; exit(0); } else { wait(NULL); } } std::cout << std::endl; } } int main(int argc, char *argv[]) { // TODO: Notes: // 1) Incremented int by 1 on each iteration of af, to prevent compiler optimizing away loop (also used Chandler's // optimizer-defeating functions to access the ints after each iteration -- could this be a problem with caching?) // For baseline, G = 10^7, af = 10 std::cout << "Started" << std::endl; //{ // std::cout << "Creating allocator" << std::endl; // BloombergLP::bdlma::MultipoolAllocator alloc; // std::cout << "Creating Vector" << std::endl; // typename vectors::multipool vector(&alloc); // std::cout << "Creating List" << std::endl; // vector.emplace_back(&alloc); // std::cout << "Adding to list" << std::endl; // vector[0].push_back(3); // std::cout << "Reading from List/Vector" << std::endl; // std::cout << vector[0].back() << std::endl; // std::cout << "Destroying Vector/List" << std::endl; //} std::cout << "Problem Size 2^21 Without Allocators" << std::endl; generate_table(21, 0); std::cout << "Problem Size 2^21 With Allocators" << std::endl; generate_table(21, 7); std::cout << "Problem Size 2^25 Without Allocators" << std::endl; generate_table(25, 0); std::cout << "Problem Size 2^25 With Allocators" << std::endl; generate_table(25, 7); std::cout << "Done" << std::endl; } <commit_msg>Refactored benchmark two to properly use one allocator per subsystem<commit_after>// Debugging Settings #define DEBUG //#define DEBUG_V1 //#define DEBUG_V2 //#define DEBUG_V3 //#define DEBUG_V4 #include <iostream> #include <iomanip> #include <memory> #include <random> #include <iterator> #include <functional> #include <ctime> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <memory.h> #include <sys/types.h> #include <sys/wait.h> #include <math.h> #include <bsl_memory.h> #include <bslma_testallocator.h> #include <bslma_newdeleteallocator.h> #include <bsls_stopwatch.h> #include <bdlma_sequentialpool.h> #include <bdlma_sequentialallocator.h> #include <bdlma_bufferedsequentialallocator.h> #include <bdlma_multipoolallocator.h> #include <vector> #include <list> #include "benchmark_common.h" // Debugging #include <typeinfo> #include <assert.h> using namespace BloombergLP; // Global Variables #ifdef DEBUG int AF_RF_PRODUCT = 256; #else int AF_RF_PRODUCT = 2560; #endif // DEBUG template<typename ALLOC> class AllocSubsystem { public: ALLOC d_alloc; std::list<int, alloc_adaptor<int, ALLOC> > d_list; AllocSubsystem() : d_alloc(), d_list(&d_alloc) {} }; class DefaultSubsystem { public: std::list<int> d_list; DefaultSubsystem() : d_list() {} }; // Convenience typedefs struct subsystems { typedef DefaultSubsystem def; typedef AllocSubsystem<BloombergLP::bdlma::MultipoolAllocator> multipool; }; //struct vectors { // typedef std::vector<subsystems::def> def; // typedef std::vector<subsystems::newdel, typename alloc_adaptors<subsystems::newdel>::newdel> newdel; // typedef std::vector<subsystems::monotonic, typename alloc_adaptors<subsystems::monotonic>::monotonic> monotonic; // typedef std::vector<subsystems::multipool, typename alloc_adaptors<subsystems::multipool>::multipool> multipool; // typedef std::vector<subsystems::polymorphic, bsl::allocator<int>> polymorphic; //}; template<typename VECTOR> double access_lists(VECTOR *vec, int af, int rf) { #ifdef DEBUG_V3 std::cout << "Accessing Lists" << std::endl; #endif // DEBUG_V3 std::clock_t c_start = std::clock(); for (size_t r = 0; r < rf; r++) { for (size_t i = 0; i < vec->size(); i++) { for (size_t a = 0; a < af; a++) { for (auto it = (*vec)[i]->d_list.begin(); it != (*vec)[i]->d_list.end(); ++it) { (*it)++; // Increment int to cause loop to have some effect } clobber(); // TODO will this hurt caching? } } } std::clock_t c_end = std::clock(); return (c_end - c_start) * 1.0 / CLOCKS_PER_SEC; } template<typename SUBSYS> double run_combination(int G, int S, int af, int sf, int rf) { // G = Total system size (# subsystems * elements in subsystems). Given as power of 2 (size really = 2^G) // S = Elements per subsystem. Given as power of 2 (size really = 2^S) // af = Access Factor - Number of iterations through a subsystem (linked list) before moving to the next // sf = Shuffle Factor - Number of elements popped from each list and pushed to a randomly chosen list // Note: -ve value means access occurs before shuffle // rf = Repeat Factor - Number of times the subsystems are iterated over int k = std::abs(G) - std::abs(S); size_t expanded_S = 1, expanded_k = 1; expanded_S <<= S; expanded_k <<= k; #ifdef DEBUG_V3 std::cout << "Total number of lists (k) = 2^" << k << " (aka " << expanded_k << ")" << std::endl; std::cout << "Total number of elements per sub system (S) = 2^" << S << " (aka " << expanded_S << ")" << std::endl; #endif // DEBUG_V3 std::vector<SUBSYS *> vec; // Create data under test vec.reserve(expanded_k); for (size_t i = 0; i < expanded_k; i++) { vec.emplace_back(new SUBSYS()); // Never deallocated because we exit immediately after this function reutrns anyway for (size_t j = 0; j < expanded_S; j++) { vec.back()->d_list.emplace_back((int)j); } } #ifdef DEBUG_V3 std::cout << "Created vector with " << vec.size() << " elements" << std::endl; #endif // DEBUG_V3 double result = 0.0; if (sf < 0) { // Access the data #ifdef DEBUG_V3 std::cout << "Accessing data BEFORE shuffling" << std::endl; #endif // DEBUG_V3 result = access_lists(&vec, af, rf); } // Shuffle the data #ifdef DEBUG_V3 std::cout << "Shuffling data " << std::abs(sf) << " times" << std::endl; #endif // DEBUG_V3 std::default_random_engine generator(1); // Consistent seed to get the same (pseudo) random distribution each time std::uniform_int_distribution<size_t> position_distribution(0, vec.size() - 1); for (size_t i = 0; i < std::abs(sf); i++) { for (size_t j = 0; j < vec.size(); j++) { vec[position_distribution(generator)]->d_list.emplace_back(vec[j]->d_list.front()); vec[j]->d_list.pop_front(); } } if (sf > 0) { // Access the data #ifdef DEBUG_V3 std::cout << "Accessing data AFTER shuffling" << std::endl; #endif // DEBUG_V3 result = access_lists(&vec, af, rf); } return result; } void generate_table(int G, int alloc_num) { int sf = 5; for (int S = 21; S >= 0; S--) { // S = 21 for (int af = 256; af >= 1; af >>= 1) { int rf = AF_RF_PRODUCT / af; #ifdef DEBUG_V3 std::cout << "G: " << G << " S: " << S << " af: " << af << " sf: " << sf << " rf: " << rf << std::endl; #endif int pid = fork(); if (pid == 0) { // Child process double result = 0; switch (alloc_num) { case 0: { result = run_combination<typename subsystems::def>(G, S, af, sf, rf); break; } case 7: { result = run_combination<typename subsystems::multipool>(G, S, af, sf, rf); break; } } std::cout << result << " "; exit(0); } else { wait(NULL); } } std::cout << std::endl; } } int main(int argc, char *argv[]) { // TODO: Notes: // 1) Incremented int by 1 on each iteration of af, to prevent compiler optimizing away loop (also used Chandler's // optimizer-defeating functions to access the ints after each iteration -- could this be a problem with caching?) // For baseline, G = 10^7, af = 10 std::cout << "Started" << std::endl; //std::vector<typename subsystems::def> vec; //std::allocator<int> alloc; //vec.emplace_back(alloc); //std::vector<typename subsystems::multipool> vec_1; //BloombergLP::bdlma::MultipoolAllocator alloc_1; //vec_1.emplace_back(alloc_1); //{ // std::cout << "Creating allocator" << std::endl; // BloombergLP::bdlma::MultipoolAllocator alloc; // std::cout << "Creating Vector" << std::endl; // typename vectors::multipool vector(&alloc); // std::cout << "Creating List" << std::endl; // vector.emplace_back(&alloc); // std::cout << "Adding to list" << std::endl; // vector[0].push_back(3); // std::cout << "Reading from List/Vector" << std::endl; // std::cout << vector[0].back() << std::endl; // std::cout << "Destroying Vector/List" << std::endl; //} std::cout << "Problem Size 2^21 Without Allocators" << std::endl; generate_table(21, 0); //std::cout << "Problem Size 2^25 Without Allocators" << std::endl; //generate_table(25, 0); std::cout << "Problem Size 2^21 With Allocators" << std::endl; generate_table(21, 7); //std::cout << "Problem Size 2^25 With Allocators" << std::endl; //generate_table(25, 7); std::cout << "Done" << std::endl; } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// /// @brief V8 Traverser /// /// @file /// /// DISCLAIMER /// /// Copyright 2014-2015 ArangoDB GmbH, Cologne, Germany /// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Michael Hackstein /// @author Copyright 2014-2015, ArangoDB GmbH, Cologne, Germany /// @author Copyright 2012-2013, triAGENS GmbH, Cologne, Germany //////////////////////////////////////////////////////////////////////////////// #include "v8.h" #include "V8/v8-conv.h" #include "V8/v8-utils.h" #include "V8Server/v8-vocbaseprivate.h" #include "V8Server/v8-wrapshapedjson.h" #include "V8Server/v8-vocindex.h" #include "V8Server/v8-collection.h" #include "Utils/transactions.h" #include "Utils/V8ResolverGuard.h" #include "Utils/CollectionNameResolver.h" #include "VocBase/document-collection.h" #include "Traverser.h" #include "VocBase/key-generator.h" using namespace std; using namespace triagens::basics; using namespace triagens::arango; class SimpleEdgeExpander { //////////////////////////////////////////////////////////////////////////////// /// @brief direction of expansion //////////////////////////////////////////////////////////////////////////////// TRI_edge_direction_e direction; //////////////////////////////////////////////////////////////////////////////// /// @brief edge collection //////////////////////////////////////////////////////////////////////////////// TRI_document_collection_t* edgeCollection; //////////////////////////////////////////////////////////////////////////////// /// @brief collection name and / //////////////////////////////////////////////////////////////////////////////// string edgeIdPrefix; //////////////////////////////////////////////////////////////////////////////// /// @brief the collection name resolver //////////////////////////////////////////////////////////////////////////////// CollectionNameResolver* resolver; //////////////////////////////////////////////////////////////////////////////// /// @brief this indicates whether or not a distance attribute is used or /// whether all edges are considered to have weight 1 //////////////////////////////////////////////////////////////////////////////// bool usesDist; //////////////////////////////////////////////////////////////////////////////// /// @brief an ID for the expander, just for debuggin //////////////////////////////////////////////////////////////////////////////// string id; public: SimpleEdgeExpander(TRI_edge_direction_e direction, TRI_document_collection_t* edgeCollection, string edgeCollectionName, CollectionNameResolver* resolver, string id) : direction(direction), edgeCollection(edgeCollection), resolver(resolver), usesDist(false), id(id) { edgeIdPrefix = edgeCollectionName + "/"; }; Traverser::VertexId extractFromId(TRI_doc_mptr_copy_t& ptr) { char const* key = TRI_EXTRACT_MARKER_FROM_KEY(&ptr); TRI_voc_cid_t cid = TRI_EXTRACT_MARKER_FROM_CID(&ptr); string col = resolver->getCollectionName(cid); col.append("/"); col.append(key); return col; }; Traverser::VertexId extractToId(TRI_doc_mptr_copy_t& ptr) { char const* key = TRI_EXTRACT_MARKER_TO_KEY(&ptr); TRI_voc_cid_t cid = TRI_EXTRACT_MARKER_TO_CID(&ptr); string col = resolver->getCollectionName(cid); col.append("/"); col.append(key); return col; }; Traverser::EdgeId extractEdgeId(TRI_doc_mptr_copy_t& ptr) { char const* key = TRI_EXTRACT_MARKER_KEY(&ptr); return edgeIdPrefix + key; }; void operator() (Traverser::VertexId source, vector<Traverser::Step>& result) { std::vector<TRI_doc_mptr_copy_t> edges; TransactionBase fake(true); // Fake a transaction to please checks. // This is due to multi-threading // Process Vertex Id! size_t split; char const* str = source.c_str(); if (!TRI_ValidateDocumentIdKeyGenerator(str, &split)) { // TODO Error Handling return; } string collectionName = source.substr(0, split); auto col = resolver->getCollectionStruct(collectionName); if (col == nullptr) { // collection not found throw TRI_ERROR_ARANGO_COLLECTION_NOT_FOUND; } auto collectionCId = col->_cid; edges = TRI_LookupEdgesDocumentCollection(edgeCollection, direction, collectionCId, const_cast<char*>(str + split + 1)); unordered_map<Traverser::VertexId, size_t> candidates; Traverser::VertexId from; Traverser::VertexId to; if (usesDist) { for (size_t j = 0; j < edges.size(); ++j) { from = extractFromId(edges[j]); to = extractToId(edges[j]); if (from != source) { auto cand = candidates.find(from); if (cand == candidates.end()) { // Add weight result.emplace_back(to, from, 1, extractEdgeId(edges[j])); candidates.emplace(from, result.size()-1); } else { // Compare weight // use result[cand->seconde].weight() and .setWeight() } } else if (to != source) { auto cand = candidates.find(to); if (cand == candidates.end()) { // Add weight result.emplace_back(to, from, 1, extractEdgeId(edges[j])); candidates.emplace(to, result.size()-1); } else { // Compare weight // use result[cand->seconde].weight() and .setWeight() } } } } else { for (size_t j = 0; j < edges.size(); ++j) { from = extractFromId(edges[j]); to = extractToId(edges[j]); if (from != source) { auto cand = candidates.find(from); if (cand == candidates.end()) { result.emplace_back(from, to, 1, extractEdgeId(edges[j])); candidates.emplace(from, result.size()-1); } } else if (to != source) { auto cand = candidates.find(to); if (cand == candidates.end()) { result.emplace_back(to, from, 1, extractEdgeId(edges[j])); candidates.emplace(to, result.size()-1); } } } } } }; static v8::Handle<v8::Value> pathIdsToV8(v8::Isolate* isolate, Traverser::Path& p) { v8::EscapableHandleScope scope(isolate); TRI_GET_GLOBALS(); v8::Handle<v8::Object> result = v8::Object::New(isolate); uint32_t const vn = static_cast<uint32_t>(p.vertices.size()); v8::Handle<v8::Array> vertices = v8::Array::New(isolate, static_cast<int>(vn)); for (size_t j = 0; j < vn; ++j) { vertices->Set(static_cast<uint32_t>(j), TRI_V8_STRING(p.vertices[j].c_str())); } result->Set(TRI_V8_STRING("vertices"), vertices); uint32_t const en = static_cast<uint32_t>(p.edges.size()); v8::Handle<v8::Array> edges = v8::Array::New(isolate, static_cast<int>(en)); for (size_t j = 0; j < en; ++j) { edges->Set(static_cast<uint32_t>(j), TRI_V8_STRING(p.edges[j].c_str())); } result->Set(TRI_V8_STRING("edges"), edges); result->Set(TRI_V8_STRING("distance"), v8::Number::New(isolate, p.weight)); return scope.Escape<v8::Value>(result); }; struct LocalCollectionGuard { LocalCollectionGuard (TRI_vocbase_col_t* collection) : _collection(collection) { } ~LocalCollectionGuard () { if (_collection != nullptr && ! _collection->_isLocal) { FreeCoordinatorCollection(_collection); } } TRI_vocbase_col_t* _collection; }; void TRI_RunDijkstraSearch (const v8::FunctionCallbackInfo<v8::Value>& args) { v8::Isolate* isolate = args.GetIsolate(); v8::HandleScope scope(isolate); if (args.Length() < 4 || args.Length() > 5) { TRI_V8_THROW_EXCEPTION_USAGE("AQL_SHORTEST_PATH(<vertexcollection>, <edgecollection>, <start>, <end>, <options>)"); } std::unique_ptr<char[]> key; TRI_vocbase_t* vocbase; TRI_vocbase_col_t const* col = nullptr; vocbase = GetContextVocBase(isolate); vector<string> readCollections; vector<string> writeCollections; double lockTimeout = (double) (TRI_TRANSACTION_DEFAULT_LOCK_TIMEOUT / 1000000ULL); bool embed = false; bool waitForSync = false; // get the vertex collection if (! args[0]->IsString()) { TRI_V8_THROW_TYPE_ERROR("expecting string for <vertexcollection>"); } string vertexCollectionName = TRI_ObjectToString(args[0]); // get the edge collection if (! args[1]->IsString()) { TRI_V8_THROW_TYPE_ERROR("expecting string for <edgecollection>"); } string const edgeCollectionName = TRI_ObjectToString(args[1]); vocbase = GetContextVocBase(isolate); if (vocbase == nullptr) { TRI_V8_THROW_EXCEPTION(TRI_ERROR_ARANGO_DATABASE_NOT_FOUND); } V8ResolverGuard resolver(vocbase); readCollections.push_back(vertexCollectionName); readCollections.push_back(edgeCollectionName); if (! args[2]->IsString()) { TRI_V8_THROW_TYPE_ERROR("expecting string for <startVertex>"); } string const startVertex = TRI_ObjectToString(args[2]); if (! args[3]->IsString()) { TRI_V8_THROW_TYPE_ERROR("expecting string for <targetVertex>"); } string const targetVertex = TRI_ObjectToString(args[3]); /* std::string vertexColName; if (! ExtractDocumentHandle(isolate, args[2], vertexColName, key, rid)) { TRI_V8_THROW_EXCEPTION(TRI_ERROR_ARANGO_DOCUMENT_HANDLE_BAD); } if (key.get() == nullptr) { TRI_V8_THROW_EXCEPTION(TRI_ERROR_ARANGO_DOCUMENT_HANDLE_BAD); } TRI_ASSERT(key.get() != nullptr); */ // IHHF isCoordinator // Start Transaction to collect all parts of the path ExplicitTransaction trx( vocbase, readCollections, writeCollections, lockTimeout, waitForSync, embed ); int res = trx.begin(); if (res != TRI_ERROR_NO_ERROR) { TRI_V8_THROW_EXCEPTION(res); } col = resolver.getResolver()->getCollectionStruct(vertexCollectionName); if (col == nullptr) { // collection not found TRI_V8_THROW_EXCEPTION(TRI_ERROR_ARANGO_COLLECTION_NOT_FOUND); } if (trx.orderBarrier(trx.trxCollection(col->_cid)) == nullptr) { TRI_V8_THROW_EXCEPTION_MEMORY(); } col = resolver.getResolver()->getCollectionStruct(edgeCollectionName); if (col == nullptr) { // collection not found TRI_V8_THROW_EXCEPTION(TRI_ERROR_ARANGO_COLLECTION_NOT_FOUND); } if (trx.orderBarrier(trx.trxCollection(col->_cid)) == nullptr) { TRI_V8_THROW_EXCEPTION_MEMORY(); } TRI_document_collection_t* ecol = trx.trxCollection(col->_cid)->_collection->_collection; CollectionNameResolver resolver1(vocbase); CollectionNameResolver resolver2(vocbase); SimpleEdgeExpander forwardExpander(TRI_EDGE_OUT, ecol, edgeCollectionName, &resolver1, "A"); SimpleEdgeExpander backwardExpander(TRI_EDGE_IN, ecol, edgeCollectionName, &resolver2, "B"); Traverser traverser(forwardExpander, backwardExpander); unique_ptr<Traverser::Path> path(traverser.shortestPath(startVertex, targetVertex)); if (path.get() == nullptr) { res = trx.finish(res); v8::EscapableHandleScope scope(isolate); TRI_V8_RETURN(scope.Escape<v8::Value>(v8::Object::New(isolate))); } auto result = pathIdsToV8(isolate, *path); res = trx.finish(res); TRI_V8_RETURN(result); /* // This is how to get the data out of the collections! // Vertices TRI_doc_mptr_copy_t document; res = trx.readSingle(trx.trxCollection(vertexCollectionCId), &document, key.get()); // Edges TRI_EDGE_OUT is hardcoded std::vector<TRI_doc_mptr_copy_t>&& edges = TRI_LookupEdgesDocumentCollection(ecol, TRI_EDGE_OUT, vertexCollectionCId, key.get()); */ // Add Dijkstra here /* // Now build up the result use Subtransactions for each used collection if (res == TRI_ERROR_NO_ERROR) { { // Collect all vertices SingleCollectionReadOnlyTransaction subtrx(new V8TransactionContext(true), vocbase, vertexCollectionCId); res = subtrx.begin(); if (res != TRI_ERROR_NO_ERROR) { TRI_V8_THROW_EXCEPTION(res); } result = TRI_WrapShapedJson(isolate, subtrx, vertexCollectionCId, document.getDataPtr()); if (document.getDataPtr() == nullptr) { res = TRI_ERROR_ARANGO_DOCUMENT_NOT_FOUND; TRI_V8_THROW_EXCEPTION(res); } res = subtrx.finish(res); } { // Collect all edges SingleCollectionReadOnlyTransaction subtrx2(new V8TransactionContext(true), vocbase, edgeCollectionCId); res = subtrx2.begin(); if (res != TRI_ERROR_NO_ERROR) { TRI_V8_THROW_EXCEPTION(res); } bool error = false; uint32_t const n = static_cast<uint32_t>(edges.size()); documents = v8::Array::New(isolate, static_cast<int>(n)); for (size_t j = 0; j < n; ++j) { v8::Handle<v8::Value> doc = TRI_WrapShapedJson(isolate, subtrx2, edgeCollectionCId, edges[j].getDataPtr()); if (doc.IsEmpty()) { error = true; break; } else { documents->Set(static_cast<uint32_t>(j), doc); } } if (error) { TRI_V8_THROW_EXCEPTION_MEMORY(); } res = subtrx2.finish(res); } } */ } <commit_msg>Add some more couts.<commit_after>//////////////////////////////////////////////////////////////////////////////// /// @brief V8 Traverser /// /// @file /// /// DISCLAIMER /// /// Copyright 2014-2015 ArangoDB GmbH, Cologne, Germany /// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Michael Hackstein /// @author Copyright 2014-2015, ArangoDB GmbH, Cologne, Germany /// @author Copyright 2012-2013, triAGENS GmbH, Cologne, Germany //////////////////////////////////////////////////////////////////////////////// #include "v8.h" #include "V8/v8-conv.h" #include "V8/v8-utils.h" #include "V8Server/v8-vocbaseprivate.h" #include "V8Server/v8-wrapshapedjson.h" #include "V8Server/v8-vocindex.h" #include "V8Server/v8-collection.h" #include "Utils/transactions.h" #include "Utils/V8ResolverGuard.h" #include "Utils/CollectionNameResolver.h" #include "VocBase/document-collection.h" #include "Traverser.h" #include "VocBase/key-generator.h" using namespace std; using namespace triagens::basics; using namespace triagens::arango; class SimpleEdgeExpander { //////////////////////////////////////////////////////////////////////////////// /// @brief direction of expansion //////////////////////////////////////////////////////////////////////////////// TRI_edge_direction_e direction; //////////////////////////////////////////////////////////////////////////////// /// @brief edge collection //////////////////////////////////////////////////////////////////////////////// TRI_document_collection_t* edgeCollection; //////////////////////////////////////////////////////////////////////////////// /// @brief collection name and / //////////////////////////////////////////////////////////////////////////////// string edgeIdPrefix; //////////////////////////////////////////////////////////////////////////////// /// @brief the collection name resolver //////////////////////////////////////////////////////////////////////////////// CollectionNameResolver* resolver; //////////////////////////////////////////////////////////////////////////////// /// @brief this indicates whether or not a distance attribute is used or /// whether all edges are considered to have weight 1 //////////////////////////////////////////////////////////////////////////////// bool usesDist; //////////////////////////////////////////////////////////////////////////////// /// @brief an ID for the expander, just for debuggin //////////////////////////////////////////////////////////////////////////////// string id; public: SimpleEdgeExpander(TRI_edge_direction_e direction, TRI_document_collection_t* edgeCollection, string edgeCollectionName, CollectionNameResolver* resolver, string id) : direction(direction), edgeCollection(edgeCollection), resolver(resolver), usesDist(false), id(id) { edgeIdPrefix = edgeCollectionName + "/"; }; Traverser::VertexId extractFromId(TRI_doc_mptr_copy_t& ptr) { char const* key = TRI_EXTRACT_MARKER_FROM_KEY(&ptr); TRI_voc_cid_t cid = TRI_EXTRACT_MARKER_FROM_CID(&ptr); string col = resolver->getCollectionName(cid); col.append("/"); col.append(key); return col; }; Traverser::VertexId extractToId(TRI_doc_mptr_copy_t& ptr) { char const* key = TRI_EXTRACT_MARKER_TO_KEY(&ptr); TRI_voc_cid_t cid = TRI_EXTRACT_MARKER_TO_CID(&ptr); string col = resolver->getCollectionName(cid); col.append("/"); col.append(key); return col; }; Traverser::EdgeId extractEdgeId(TRI_doc_mptr_copy_t& ptr) { char const* key = TRI_EXTRACT_MARKER_KEY(&ptr); return edgeIdPrefix + key; }; void operator() (Traverser::VertexId source, vector<Traverser::Step>& result) { std::cout << "Expander " << id << " called." << std::endl; std::vector<TRI_doc_mptr_copy_t> edges; TransactionBase fake(true); // Fake a transaction to please checks. // This is due to multi-threading // Process Vertex Id! size_t split; char const* str = source.c_str(); if (!TRI_ValidateDocumentIdKeyGenerator(str, &split)) { // TODO Error Handling return; } string collectionName = source.substr(0, split); auto col = resolver->getCollectionStruct(collectionName); if (col == nullptr) { // collection not found throw TRI_ERROR_ARANGO_COLLECTION_NOT_FOUND; } auto collectionCId = col->_cid; edges = TRI_LookupEdgesDocumentCollection(edgeCollection, direction, collectionCId, const_cast<char*>(str + split + 1)); std::cout << "Expander " << id << " got edges." << std::endl; unordered_map<Traverser::VertexId, size_t> candidates; Traverser::VertexId from; Traverser::VertexId to; if (usesDist) { for (size_t j = 0; j < edges.size(); ++j) { from = extractFromId(edges[j]); to = extractToId(edges[j]); if (from != source) { auto cand = candidates.find(from); if (cand == candidates.end()) { // Add weight result.emplace_back(to, from, 1, extractEdgeId(edges[j])); candidates.emplace(from, result.size()-1); } else { // Compare weight // use result[cand->seconde].weight() and .setWeight() } } else if (to != source) { auto cand = candidates.find(to); if (cand == candidates.end()) { // Add weight result.emplace_back(to, from, 1, extractEdgeId(edges[j])); candidates.emplace(to, result.size()-1); } else { // Compare weight // use result[cand->seconde].weight() and .setWeight() } } } } else { for (size_t j = 0; j < edges.size(); ++j) { from = extractFromId(edges[j]); to = extractToId(edges[j]); if (from != source) { auto cand = candidates.find(from); if (cand == candidates.end()) { result.emplace_back(from, to, 1, extractEdgeId(edges[j])); candidates.emplace(from, result.size()-1); } } else if (to != source) { auto cand = candidates.find(to); if (cand == candidates.end()) { result.emplace_back(to, from, 1, extractEdgeId(edges[j])); candidates.emplace(to, result.size()-1); } } } } std::cout << "Expander " << id << " done." << std::endl; } }; static v8::Handle<v8::Value> pathIdsToV8(v8::Isolate* isolate, Traverser::Path& p) { v8::EscapableHandleScope scope(isolate); TRI_GET_GLOBALS(); v8::Handle<v8::Object> result = v8::Object::New(isolate); uint32_t const vn = static_cast<uint32_t>(p.vertices.size()); v8::Handle<v8::Array> vertices = v8::Array::New(isolate, static_cast<int>(vn)); for (size_t j = 0; j < vn; ++j) { vertices->Set(static_cast<uint32_t>(j), TRI_V8_STRING(p.vertices[j].c_str())); } result->Set(TRI_V8_STRING("vertices"), vertices); uint32_t const en = static_cast<uint32_t>(p.edges.size()); v8::Handle<v8::Array> edges = v8::Array::New(isolate, static_cast<int>(en)); for (size_t j = 0; j < en; ++j) { edges->Set(static_cast<uint32_t>(j), TRI_V8_STRING(p.edges[j].c_str())); } result->Set(TRI_V8_STRING("edges"), edges); result->Set(TRI_V8_STRING("distance"), v8::Number::New(isolate, p.weight)); return scope.Escape<v8::Value>(result); }; struct LocalCollectionGuard { LocalCollectionGuard (TRI_vocbase_col_t* collection) : _collection(collection) { } ~LocalCollectionGuard () { if (_collection != nullptr && ! _collection->_isLocal) { FreeCoordinatorCollection(_collection); } } TRI_vocbase_col_t* _collection; }; void TRI_RunDijkstraSearch (const v8::FunctionCallbackInfo<v8::Value>& args) { v8::Isolate* isolate = args.GetIsolate(); v8::HandleScope scope(isolate); if (args.Length() < 4 || args.Length() > 5) { TRI_V8_THROW_EXCEPTION_USAGE("AQL_SHORTEST_PATH(<vertexcollection>, <edgecollection>, <start>, <end>, <options>)"); } std::unique_ptr<char[]> key; TRI_vocbase_t* vocbase; TRI_vocbase_col_t const* col = nullptr; vocbase = GetContextVocBase(isolate); vector<string> readCollections; vector<string> writeCollections; double lockTimeout = (double) (TRI_TRANSACTION_DEFAULT_LOCK_TIMEOUT / 1000000ULL); bool embed = false; bool waitForSync = false; // get the vertex collection if (! args[0]->IsString()) { TRI_V8_THROW_TYPE_ERROR("expecting string for <vertexcollection>"); } string vertexCollectionName = TRI_ObjectToString(args[0]); // get the edge collection if (! args[1]->IsString()) { TRI_V8_THROW_TYPE_ERROR("expecting string for <edgecollection>"); } string const edgeCollectionName = TRI_ObjectToString(args[1]); vocbase = GetContextVocBase(isolate); if (vocbase == nullptr) { TRI_V8_THROW_EXCEPTION(TRI_ERROR_ARANGO_DATABASE_NOT_FOUND); } V8ResolverGuard resolver(vocbase); readCollections.push_back(vertexCollectionName); readCollections.push_back(edgeCollectionName); if (! args[2]->IsString()) { TRI_V8_THROW_TYPE_ERROR("expecting string for <startVertex>"); } string const startVertex = TRI_ObjectToString(args[2]); if (! args[3]->IsString()) { TRI_V8_THROW_TYPE_ERROR("expecting string for <targetVertex>"); } string const targetVertex = TRI_ObjectToString(args[3]); /* std::string vertexColName; if (! ExtractDocumentHandle(isolate, args[2], vertexColName, key, rid)) { TRI_V8_THROW_EXCEPTION(TRI_ERROR_ARANGO_DOCUMENT_HANDLE_BAD); } if (key.get() == nullptr) { TRI_V8_THROW_EXCEPTION(TRI_ERROR_ARANGO_DOCUMENT_HANDLE_BAD); } TRI_ASSERT(key.get() != nullptr); */ // IHHF isCoordinator // Start Transaction to collect all parts of the path ExplicitTransaction trx( vocbase, readCollections, writeCollections, lockTimeout, waitForSync, embed ); int res = trx.begin(); if (res != TRI_ERROR_NO_ERROR) { TRI_V8_THROW_EXCEPTION(res); } col = resolver.getResolver()->getCollectionStruct(vertexCollectionName); if (col == nullptr) { // collection not found TRI_V8_THROW_EXCEPTION(TRI_ERROR_ARANGO_COLLECTION_NOT_FOUND); } if (trx.orderBarrier(trx.trxCollection(col->_cid)) == nullptr) { TRI_V8_THROW_EXCEPTION_MEMORY(); } col = resolver.getResolver()->getCollectionStruct(edgeCollectionName); if (col == nullptr) { // collection not found TRI_V8_THROW_EXCEPTION(TRI_ERROR_ARANGO_COLLECTION_NOT_FOUND); } if (trx.orderBarrier(trx.trxCollection(col->_cid)) == nullptr) { TRI_V8_THROW_EXCEPTION_MEMORY(); } TRI_document_collection_t* ecol = trx.trxCollection(col->_cid)->_collection->_collection; CollectionNameResolver resolver1(vocbase); CollectionNameResolver resolver2(vocbase); SimpleEdgeExpander forwardExpander(TRI_EDGE_OUT, ecol, edgeCollectionName, &resolver1, "A"); SimpleEdgeExpander backwardExpander(TRI_EDGE_IN, ecol, edgeCollectionName, &resolver2, "B"); Traverser traverser(forwardExpander, backwardExpander); unique_ptr<Traverser::Path> path(traverser.shortestPath(startVertex, targetVertex)); if (path.get() == nullptr) { res = trx.finish(res); v8::EscapableHandleScope scope(isolate); TRI_V8_RETURN(scope.Escape<v8::Value>(v8::Object::New(isolate))); } auto result = pathIdsToV8(isolate, *path); res = trx.finish(res); TRI_V8_RETURN(result); /* // This is how to get the data out of the collections! // Vertices TRI_doc_mptr_copy_t document; res = trx.readSingle(trx.trxCollection(vertexCollectionCId), &document, key.get()); // Edges TRI_EDGE_OUT is hardcoded std::vector<TRI_doc_mptr_copy_t>&& edges = TRI_LookupEdgesDocumentCollection(ecol, TRI_EDGE_OUT, vertexCollectionCId, key.get()); */ // Add Dijkstra here /* // Now build up the result use Subtransactions for each used collection if (res == TRI_ERROR_NO_ERROR) { { // Collect all vertices SingleCollectionReadOnlyTransaction subtrx(new V8TransactionContext(true), vocbase, vertexCollectionCId); res = subtrx.begin(); if (res != TRI_ERROR_NO_ERROR) { TRI_V8_THROW_EXCEPTION(res); } result = TRI_WrapShapedJson(isolate, subtrx, vertexCollectionCId, document.getDataPtr()); if (document.getDataPtr() == nullptr) { res = TRI_ERROR_ARANGO_DOCUMENT_NOT_FOUND; TRI_V8_THROW_EXCEPTION(res); } res = subtrx.finish(res); } { // Collect all edges SingleCollectionReadOnlyTransaction subtrx2(new V8TransactionContext(true), vocbase, edgeCollectionCId); res = subtrx2.begin(); if (res != TRI_ERROR_NO_ERROR) { TRI_V8_THROW_EXCEPTION(res); } bool error = false; uint32_t const n = static_cast<uint32_t>(edges.size()); documents = v8::Array::New(isolate, static_cast<int>(n)); for (size_t j = 0; j < n; ++j) { v8::Handle<v8::Value> doc = TRI_WrapShapedJson(isolate, subtrx2, edgeCollectionCId, edges[j].getDataPtr()); if (doc.IsEmpty()) { error = true; break; } else { documents->Set(static_cast<uint32_t>(j), doc); } } if (error) { TRI_V8_THROW_EXCEPTION_MEMORY(); } res = subtrx2.finish(res); } } */ } <|endoftext|>
<commit_before>#include "ContainerController.h" #include "Path.h" #include <cryptopp/secblock.h> #include <cryptopp/osrng.h> #include <string> #include <limits> #include "CloudManager.h" ContainerController::ContainerController(callback_t event_callback, const std::string& vhd_path) : event_callback_(event_callback), vhd_path_(vhd_path) { } ContainerController::~ContainerController() { container_.close(); } container_event ContainerController::create(const std::string& container_name, const std::string& container_location, const std::string& password, const std::string& sync_location, stor_t store_type, size_t store_size) { container_event ev; path filepath = path(container_location).append_filename(container_name + ".cco"); if(store_size == 0) store_size = std::numeric_limits< int >::max(); try { path v(vhd_path_); container_.create(container_name, password, filepath, { std::pair < std::string, size_t >(sync_location, store_size) }, v, store_type, event_callback_); send_callback(INFORMATION, SUCC); } catch (std::invalid_argument e) { send_callback(CONFLICT, WRONG_ARGUMENTS); } return ev; } bool ContainerController::open(const std::string& container_location, const std::string& password, stor_t store_type) { path v(vhd_path_); path cl(container_location); container_event ev; try { container_.open(cl, password, v, store_type, event_callback_); send_callback(INFORMATION, SUCC); return true; } catch (const std::invalid_argument& e) { std::string what = e.what(); send_callback(CONFLICT, WRONG_PASSWORD, what); return false; } } bool ContainerController::sync_now() { send_callback(INFORMATION, SYNCHRONIZING); container_.manual_sync(); send_callback(INFORMATION, FINISHED_SYNCHRONIZING); return true; } std::vector<unsigned char> ContainerController::get_pseudo_seed() { using namespace CryptoPP; SecByteBlock b(32); AutoSeededRandomPool prng; prng.GenerateBlock(b, b.size()); return{ std::begin(b), std::end(b) }; } void ContainerController::set_seed(std::vector<unsigned char>& seed) { //here comes something nice } void ContainerController::delete_booked_node(container_event& e) { //some other nice things here } void ContainerController::send_callback(event_type t, event_message m, std::string data) { container_event ev; ev.type = t; ev.message = m; ev._data_.insert(ev._data_.begin(), data.begin(), data.end()); std::thread th(event_callback_, ev); th.detach(); } void ContainerController::refresh_providerlist() { auto& manager = CloudManager::instance(); manager.create_providerlist(); } void ContainerController::add_provider(std::string name_with_sign, std::string location) { auto& manager = CloudManager::instance(); manager.add_provider(name_with_sign, location); } void ContainerController::delete_provider(std::string name_with_sign) { auto& manager = CloudManager::instance(); manager.delete_provider(name_with_sign); } bool ContainerController::contains_provider(std::string name_with_sign) { auto& manager = CloudManager::instance(); return manager.contains_provider(name_with_sign); } std::vector<std::pair<std::string, std::string> > ContainerController::get_providers() { auto& manager = CloudManager::instance(); return manager.get_providers(); } void ContainerController::close() { container_.close(); } bool ContainerController::is_open() const { return container_.is_open(); } <commit_msg>CHANGE: create generates all necessary folders<commit_after>#include "ContainerController.h" #include "Path.h" #include <cryptopp/secblock.h> #include <cryptopp/osrng.h> #include <string> #include <limits> #include "CloudManager.h" ContainerController::ContainerController(callback_t event_callback, const std::string& vhd_path) : event_callback_(event_callback), vhd_path_(vhd_path) { } ContainerController::~ContainerController() { container_.close(); } container_event ContainerController::create(const std::string& container_name, const std::string& container_location, const std::string& password, const std::string& sync_location, stor_t store_type, size_t store_size) { container_event ev; path filepath = path(container_location).append_filename(container_name + ".cco"); FileSystem::make_folders(path(sync_location).str()); if(store_size == 0) store_size = std::numeric_limits< int >::max(); try { path v(vhd_path_); container_.create(container_name, password, filepath, { std::pair < std::string, size_t >(sync_location, store_size) }, v, store_type, event_callback_); send_callback(INFORMATION, SUCC); } catch (std::invalid_argument e) { send_callback(CONFLICT, WRONG_ARGUMENTS); } return ev; } bool ContainerController::open(const std::string& container_location, const std::string& password, stor_t store_type) { path v(vhd_path_); path cl(container_location); container_event ev; try { container_.open(cl, password, v, store_type, event_callback_); send_callback(INFORMATION, SUCC); return true; } catch (const std::invalid_argument& e) { std::string what = e.what(); send_callback(CONFLICT, WRONG_PASSWORD, what); return false; } } bool ContainerController::sync_now() { send_callback(INFORMATION, SYNCHRONIZING); container_.manual_sync(); send_callback(INFORMATION, FINISHED_SYNCHRONIZING); return true; } std::vector<unsigned char> ContainerController::get_pseudo_seed() { using namespace CryptoPP; SecByteBlock b(32); AutoSeededRandomPool prng; prng.GenerateBlock(b, b.size()); return{ std::begin(b), std::end(b) }; } void ContainerController::set_seed(std::vector<unsigned char>& seed) { //here comes something nice } void ContainerController::delete_booked_node(container_event& e) { //some other nice things here } void ContainerController::send_callback(event_type t, event_message m, std::string data) { container_event ev; ev.type = t; ev.message = m; ev._data_.insert(ev._data_.begin(), data.begin(), data.end()); std::thread th(event_callback_, ev); th.detach(); } void ContainerController::refresh_providerlist() { auto& manager = CloudManager::instance(); manager.create_providerlist(); } void ContainerController::add_provider(std::string name_with_sign, std::string location) { auto& manager = CloudManager::instance(); manager.add_provider(name_with_sign, location); } void ContainerController::delete_provider(std::string name_with_sign) { auto& manager = CloudManager::instance(); manager.delete_provider(name_with_sign); } bool ContainerController::contains_provider(std::string name_with_sign) { auto& manager = CloudManager::instance(); return manager.contains_provider(name_with_sign); } std::vector<std::pair<std::string, std::string> > ContainerController::get_providers() { auto& manager = CloudManager::instance(); return manager.get_providers(); } void ContainerController::close() { container_.close(); } bool ContainerController::is_open() const { return container_.is_open(); } <|endoftext|>
<commit_before>#include "gs_main_menu.h" #include "gs_playing.h" using namespace Urho3D; gs_main_menu::gs_main_menu() : game_state() { Node* node_camera=globals::instance()->camera->GetNode(); node_camera->SetPosition(Vector3(0,0,0)); node_camera->SetDirection(Vector3::FORWARD); boxNode_=globals::instance()->scene->CreateChild("Flag"); nodes.push_back(boxNode_); boxNode_->SetPosition(Vector3(0,-0.5,6)); StaticModel* boxObject=boxNode_->CreateComponent<StaticModel>(); boxObject->SetModel(globals::instance()->cache->GetResource<Model>("Models/flag.mdl")); boxObject->SetMaterial(0,globals::instance()->cache->GetResource<Material>("Materials/flag_pole.xml")); boxObject->SetMaterial(1,globals::instance()->cache->GetResource<Material>("Materials/flag_cloth.xml")); for(int x=-30;x<30;x+=3) for(int y=-30;y<30;y+=3) { Node* boxNode_=globals::instance()->scene->CreateChild("Box"); nodes.push_back(boxNode_); boxNode_->SetPosition(Vector3(x,-1,y)); StaticModel* boxObject=boxNode_->CreateComponent<StaticModel>(); boxObject->SetModel(globals::instance()->cache->GetResource<Model>("Models/Box.mdl")); boxObject->SetMaterial(globals::instance()->cache->GetResource<Material>("Materials/Stone.xml")); boxObject->SetCastShadows(true); } { Node* lightNode=globals::instance()->scene->CreateChild("Light"); nodes.push_back(lightNode); lightNode->SetPosition(Vector3(-5,10,5)); Light* light=lightNode->CreateComponent<Light>(); light->SetLightType(LIGHT_POINT); light->SetRange(50); light->SetBrightness(1.2); light->SetColor(Color(1,.5,.8,1)); light->SetCastShadows(true); } { Node* lightNode=globals::instance()->scene->CreateChild("Light"); nodes.push_back(lightNode); lightNode->SetPosition(Vector3(5,2,5)); Light* light=lightNode->CreateComponent<Light>(); light->SetLightType(LIGHT_POINT); light->SetRange(50); light->SetBrightness(1.2); light->SetColor(Color(.5,.8,1,1)); light->SetCastShadows(true); } { Node* lightNode=globals::instance()->camera->GetNode()->CreateChild("Light"); nodes.push_back(lightNode); lightNode->SetPosition(Vector3(0,2,10)); Light* light=lightNode->CreateComponent<Light>(); light->SetLightType(LIGHT_POINT); light->SetRange(10); light->SetBrightness(2.0); light->SetColor(Color(.8,1,.8,1.0)); light->SetCastShadows(true); } Window* window_=new Window(globals::instance()->context); gui_elements.push_back(window_); globals::instance()->ui_root->AddChild(window_); window_->SetMinSize(384,192); window_->SetLayout(LM_VERTICAL,6,IntRect(6,6,6,6)); window_->SetAlignment(HA_CENTER,VA_CENTER); window_->SetName("Window"); UIElement* titleBar=new UIElement(globals::instance()->context); titleBar->SetMinSize(0,24); titleBar->SetVerticalAlignment(VA_TOP); titleBar->SetLayoutMode(LM_HORIZONTAL); Text* windowTitle=new Text(globals::instance()->context); windowTitle->SetName("WindowTitle"); windowTitle->SetText("Hello GUI!"); windowTitle->SetStyleAuto(); titleBar->AddChild(windowTitle); Button* buttonClose=new Button(globals::instance()->context); buttonClose->SetName("CloseButton"); buttonClose->SetStyle("CloseButton"); titleBar->AddChild(buttonClose); window_->AddChild(titleBar); window_->SetStyleAuto(); { Button* button = new Button(globals::instance()->context); button->SetName("Button"); button->SetMinHeight(100); button->SetStyleAuto(); { Text* t = new Text(globals::instance()->context); t->SetHorizontalAlignment(HA_CENTER); t->SetVerticalAlignment(VA_CENTER); t->SetName("Text"); t->SetText("Quit"); //button->AddChild(t); t->SetStyle("Text"); t->SetMinHeight(100); button->AddChild(t); } window_->AddChild(button); SubscribeToEvent(button,E_RELEASED,HANDLER(gs_main_menu,HandlePlayPressed)); } { Button* button = new Button(globals::instance()->context); button->SetName("Button"); button->SetMinHeight(100); button->SetStyleAuto(); { Text* t = new Text(globals::instance()->context); t->SetHorizontalAlignment(HA_CENTER); t->SetVerticalAlignment(VA_CENTER); t->SetName("Text"); t->SetText("Quit"); //button->AddChild(t); t->SetStyle("Text"); t->SetMinHeight(100); button->AddChild(t); } window_->AddChild(button); SubscribeToEvent(button,E_RELEASED,HANDLER(gs_main_menu,HandleClosePressed)); } GetSubsystem<Input>()->SetMouseVisible(true); GetSubsystem<Input>()->SetMouseGrabbed(false); SubscribeToEvent(E_UPDATE,HANDLER(gs_main_menu,update)); SubscribeToEvent(E_KEYDOWN,HANDLER(gs_main_menu,HandleKeyDown)); SubscribeToEvent(buttonClose,E_RELEASED,HANDLER(gs_main_menu,HandleClosePressed)); } gs_main_menu::~gs_main_menu() { } void gs_main_menu::update(StringHash eventType,VariantMap& eventData) { float timeStep=eventData[Update::P_TIMESTEP].GetFloat(); boxNode_->Rotate(Quaternion(0,32*timeStep,0)); } void gs_main_menu::HandlePlayPressed(Urho3D::StringHash eventType,Urho3D::VariantMap& eventData) { globals::instance()->game_state_.reset(new gs_playing); } void gs_main_menu::HandleKeyDown(StringHash eventType,VariantMap& eventData) { using namespace KeyDown; int key=eventData[P_KEY].GetInt(); if(key==KEY_ESC) globals::instance()->engine->Exit(); } <commit_msg>" fix text on the buttons "<commit_after>#include "gs_main_menu.h" #include "gs_playing.h" using namespace Urho3D; gs_main_menu::gs_main_menu() : game_state() { Node* node_camera=globals::instance()->camera->GetNode(); node_camera->SetPosition(Vector3(0,0,0)); node_camera->SetDirection(Vector3::FORWARD); boxNode_=globals::instance()->scene->CreateChild("Flag"); nodes.push_back(boxNode_); boxNode_->SetPosition(Vector3(0,-0.5,6)); StaticModel* boxObject=boxNode_->CreateComponent<StaticModel>(); boxObject->SetModel(globals::instance()->cache->GetResource<Model>("Models/flag.mdl")); boxObject->SetMaterial(0,globals::instance()->cache->GetResource<Material>("Materials/flag_pole.xml")); boxObject->SetMaterial(1,globals::instance()->cache->GetResource<Material>("Materials/flag_cloth.xml")); for(int x=-30;x<30;x+=3) for(int y=-30;y<30;y+=3) { Node* boxNode_=globals::instance()->scene->CreateChild("Box"); nodes.push_back(boxNode_); boxNode_->SetPosition(Vector3(x,-1,y)); StaticModel* boxObject=boxNode_->CreateComponent<StaticModel>(); boxObject->SetModel(globals::instance()->cache->GetResource<Model>("Models/Box.mdl")); boxObject->SetMaterial(globals::instance()->cache->GetResource<Material>("Materials/Stone.xml")); boxObject->SetCastShadows(true); } { Node* lightNode=globals::instance()->scene->CreateChild("Light"); nodes.push_back(lightNode); lightNode->SetPosition(Vector3(-5,10,5)); Light* light=lightNode->CreateComponent<Light>(); light->SetLightType(LIGHT_POINT); light->SetRange(50); light->SetBrightness(1.2); light->SetColor(Color(1,.5,.8,1)); light->SetCastShadows(true); } { Node* lightNode=globals::instance()->scene->CreateChild("Light"); nodes.push_back(lightNode); lightNode->SetPosition(Vector3(5,2,5)); Light* light=lightNode->CreateComponent<Light>(); light->SetLightType(LIGHT_POINT); light->SetRange(50); light->SetBrightness(1.2); light->SetColor(Color(.5,.8,1,1)); light->SetCastShadows(true); } { Node* lightNode=globals::instance()->camera->GetNode()->CreateChild("Light"); nodes.push_back(lightNode); lightNode->SetPosition(Vector3(0,2,10)); Light* light=lightNode->CreateComponent<Light>(); light->SetLightType(LIGHT_POINT); light->SetRange(10); light->SetBrightness(2.0); light->SetColor(Color(.8,1,.8,1.0)); light->SetCastShadows(true); } Window* window_=new Window(globals::instance()->context); gui_elements.push_back(window_); globals::instance()->ui_root->AddChild(window_); window_->SetMinSize(384,192); window_->SetLayout(LM_VERTICAL,6,IntRect(6,6,6,6)); window_->SetAlignment(HA_CENTER,VA_CENTER); window_->SetName("Window"); UIElement* titleBar=new UIElement(globals::instance()->context); titleBar->SetMinSize(0,24); titleBar->SetVerticalAlignment(VA_TOP); titleBar->SetLayoutMode(LM_HORIZONTAL); Text* windowTitle=new Text(globals::instance()->context); windowTitle->SetName("WindowTitle"); windowTitle->SetText("Hello GUI!"); windowTitle->SetStyleAuto(); titleBar->AddChild(windowTitle); Button* buttonClose=new Button(globals::instance()->context); buttonClose->SetName("CloseButton"); buttonClose->SetStyle("CloseButton"); titleBar->AddChild(buttonClose); window_->AddChild(titleBar); window_->SetStyleAuto(); { Button* button = new Button(globals::instance()->context); button->SetName("Button"); button->SetMinHeight(100); button->SetStyleAuto(); { Text* t = new Text(globals::instance()->context); t->SetFont(globals::instance()->cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"),20); t->SetHorizontalAlignment(HA_CENTER); t->SetVerticalAlignment(VA_CENTER); t->SetName("Text"); t->SetText("Play"); //button->AddChild(t); t->SetStyle("Text"); t->SetMinHeight(VA_CENTER); button->AddChild(t); } window_->AddChild(button); SubscribeToEvent(button,E_RELEASED,HANDLER(gs_main_menu,HandlePlayPressed)); } { Button* button = new Button(globals::instance()->context); button->SetName("Button"); button->SetMinHeight(100); button->SetStyleAuto(); { Text* t = new Text(globals::instance()->context); t->SetFont(globals::instance()->cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"),20); t->SetHorizontalAlignment(HA_CENTER); t->SetVerticalAlignment(VA_CENTER); t->SetName("Text"); t->SetText("Quit"); //button->AddChild(t); t->SetStyle("Text"); t->SetMinHeight(VA_CENTER); button->AddChild(t); } window_->AddChild(button); SubscribeToEvent(button,E_RELEASED,HANDLER(gs_main_menu,HandleClosePressed)); } GetSubsystem<Input>()->SetMouseVisible(true); GetSubsystem<Input>()->SetMouseGrabbed(false); SubscribeToEvent(E_UPDATE,HANDLER(gs_main_menu,update)); SubscribeToEvent(E_KEYDOWN,HANDLER(gs_main_menu,HandleKeyDown)); SubscribeToEvent(buttonClose,E_RELEASED,HANDLER(gs_main_menu,HandleClosePressed)); } gs_main_menu::~gs_main_menu() { } void gs_main_menu::update(StringHash eventType,VariantMap& eventData) { float timeStep=eventData[Update::P_TIMESTEP].GetFloat(); boxNode_->Rotate(Quaternion(0,32*timeStep,0)); } void gs_main_menu::HandlePlayPressed(Urho3D::StringHash eventType,Urho3D::VariantMap& eventData) { globals::instance()->game_state_.reset(new gs_playing); } void gs_main_menu::HandleKeyDown(StringHash eventType,VariantMap& eventData) { using namespace KeyDown; int key=eventData[P_KEY].GetInt(); if(key==KEY_ESC) globals::instance()->engine->Exit(); } <|endoftext|>
<commit_before>/************************************************************************* > File Name: Cards.cpp > Project Name: Hearthstone++ > Author: Chan-Ho Chris Ohk > Purpose: Cards class that stores a list of cards. > Created Time: 2017/10/10 > Copyright (c) 2017, Chan-Ho Chris Ohk *************************************************************************/ #include <Loaders/CardLoader.h> #include <Cards/Cards.h> #include <Cards/Character.h> namespace Hearthstonepp { Cards* Cards::m_instance = nullptr; Cards::Cards() { CardLoader loader; loader.LoadData(m_cards); } Cards::~Cards() { for (auto card : m_cards) { delete card; } m_cards.clear(); } Cards* Cards::GetInstance() { if (m_instance == nullptr) { m_instance = new Cards(); } return m_instance; } std::vector<Card*> Cards::GetAllCards() const { return m_cards; } const Card* Cards::FindCardByID(const std::string& id) { for (auto card : m_cards) { if (card->id == id) { return card; } } return nullptr; } std::vector<Card*> Cards::FindCardByRarity(Rarity rarity) { std::vector<Card*> result; for (auto card : m_cards) { if (card->rarity == rarity) { result.emplace_back(card); } } return result; } std::vector<Card*> Cards::FindCardByClass(CardClass cardClass) { std::vector<Card*> result; for (auto card : m_cards) { if (card->cardClass == cardClass) { result.emplace_back(card); } } return result; } std::vector<Card*> Cards::FindCardByType(CardType cardType) { std::vector<Card*> result; for (auto card : m_cards) { if (card->cardType == cardType) { result.emplace_back(card); } } return result; } std::vector<Card*> Cards::FindCardByRace(Race race) { std::vector<Card*> result; for (auto card : m_cards) { if (card->race == race) { result.emplace_back(card); } } return result; } Card* Cards::FindCardByName(const std::string& name) { for (auto card : m_cards) { if (card->name == name) { return card; } } return nullptr; } std::vector<Card*> Cards::FindCardByCost(size_t minVal, size_t maxVal) { std::vector<Card*> result; for (auto card : m_cards) { if (card->cost >= minVal && card->cost <= maxVal) { result.emplace_back(card); } } return result; } std::vector<Card*> Cards::FindCardByAttack(size_t minVal, size_t maxVal) { std::vector<Card*> result; for (auto card : m_cards) { const Character* character = dynamic_cast<Character*>(card); if (character == nullptr) { continue; } if (character->attack >= minVal && character->attack <= maxVal) { result.emplace_back(card); } } return result; } std::vector<Card*> Cards::FindCardByHealth(size_t minVal, size_t maxVal) { std::vector<Card*> result; for (auto card : m_cards) { const Character* character = dynamic_cast<Character*>(card); if (character == nullptr) { continue; } if (character->health >= minVal && character->health <= maxVal) { result.emplace_back(card); } } return result; } std::vector<Card*> Cards::FindCardByMechanics(std::vector<GameTag> mechanics) { std::vector<Card*> result; for (auto card : m_cards) { auto mechanicsInCard = card->mechanics; for (const auto mechanic : mechanics) { if (std::find(mechanicsInCard.begin(), mechanicsInCard.end(), mechanic) != mechanicsInCard.end()) { result.emplace_back(card); } } } return result; } const Card* Cards::GetHeroCard(CardClass cardClass) { switch (cardClass) { case CardClass::DRUID: return FindCardByID("HERO_06"); case CardClass::HUNTER: return FindCardByID("HERO_05"); case CardClass::MAGE: return FindCardByID("HERO_08"); case CardClass::PALADIN: return FindCardByID("HERO_04"); case CardClass::PRIEST: return FindCardByID("HERO_09"); case CardClass::ROGUE: return FindCardByID("HERO_03"); case CardClass::SHAMAN: return FindCardByID("HERO_02"); case CardClass::WARLOCK: return FindCardByID("HERO_07"); case CardClass::WARRIOR: return FindCardByID("HERO_01"); default: return nullptr; } } const Card* Cards::GetDefaultHeroPower(CardClass cardClass) { switch (cardClass) { case CardClass::DRUID: return FindCardByID("CS2_017"); case CardClass::HUNTER: return FindCardByID("DS1h_292"); case CardClass::MAGE: return FindCardByID("CS2_034"); case CardClass::PALADIN: return FindCardByID("CS2_101"); case CardClass::PRIEST: return FindCardByID("CS1h_001"); case CardClass::ROGUE: return FindCardByID("CS2_083b"); case CardClass::SHAMAN: return FindCardByID("CS2_049"); case CardClass::WARLOCK: return FindCardByID("CS2_056"); case CardClass::WARRIOR: return FindCardByID("CS2_102"); default: return nullptr; } } } <commit_msg>[ci skip] load power data in the constructor<commit_after>/************************************************************************* > File Name: Cards.cpp > Project Name: Hearthstone++ > Author: Chan-Ho Chris Ohk > Purpose: Cards class that stores a list of cards. > Created Time: 2017/10/10 > Copyright (c) 2017, Chan-Ho Chris Ohk *************************************************************************/ #include <Loaders/CardLoader.h> #include <Cards/Cards.h> #include <Cards/Character.h> namespace Hearthstonepp { Cards* Cards::m_instance = nullptr; Cards::Cards() { CardLoader loader; loader.LoadData(m_cards); loader.LoadPower(m_cards); } Cards::~Cards() { for (auto card : m_cards) { delete card; } m_cards.clear(); } Cards* Cards::GetInstance() { if (m_instance == nullptr) { m_instance = new Cards(); } return m_instance; } std::vector<Card*> Cards::GetAllCards() const { return m_cards; } const Card* Cards::FindCardByID(const std::string& id) { for (auto card : m_cards) { if (card->id == id) { return card; } } return nullptr; } std::vector<Card*> Cards::FindCardByRarity(Rarity rarity) { std::vector<Card*> result; for (auto card : m_cards) { if (card->rarity == rarity) { result.emplace_back(card); } } return result; } std::vector<Card*> Cards::FindCardByClass(CardClass cardClass) { std::vector<Card*> result; for (auto card : m_cards) { if (card->cardClass == cardClass) { result.emplace_back(card); } } return result; } std::vector<Card*> Cards::FindCardByType(CardType cardType) { std::vector<Card*> result; for (auto card : m_cards) { if (card->cardType == cardType) { result.emplace_back(card); } } return result; } std::vector<Card*> Cards::FindCardByRace(Race race) { std::vector<Card*> result; for (auto card : m_cards) { if (card->race == race) { result.emplace_back(card); } } return result; } Card* Cards::FindCardByName(const std::string& name) { for (auto card : m_cards) { if (card->name == name) { return card; } } return nullptr; } std::vector<Card*> Cards::FindCardByCost(size_t minVal, size_t maxVal) { std::vector<Card*> result; for (auto card : m_cards) { if (card->cost >= minVal && card->cost <= maxVal) { result.emplace_back(card); } } return result; } std::vector<Card*> Cards::FindCardByAttack(size_t minVal, size_t maxVal) { std::vector<Card*> result; for (auto card : m_cards) { const Character* character = dynamic_cast<Character*>(card); if (character == nullptr) { continue; } if (character->attack >= minVal && character->attack <= maxVal) { result.emplace_back(card); } } return result; } std::vector<Card*> Cards::FindCardByHealth(size_t minVal, size_t maxVal) { std::vector<Card*> result; for (auto card : m_cards) { const Character* character = dynamic_cast<Character*>(card); if (character == nullptr) { continue; } if (character->health >= minVal && character->health <= maxVal) { result.emplace_back(card); } } return result; } std::vector<Card*> Cards::FindCardByMechanics(std::vector<GameTag> mechanics) { std::vector<Card*> result; for (auto card : m_cards) { auto mechanicsInCard = card->mechanics; for (const auto mechanic : mechanics) { if (std::find(mechanicsInCard.begin(), mechanicsInCard.end(), mechanic) != mechanicsInCard.end()) { result.emplace_back(card); } } } return result; } const Card* Cards::GetHeroCard(CardClass cardClass) { switch (cardClass) { case CardClass::DRUID: return FindCardByID("HERO_06"); case CardClass::HUNTER: return FindCardByID("HERO_05"); case CardClass::MAGE: return FindCardByID("HERO_08"); case CardClass::PALADIN: return FindCardByID("HERO_04"); case CardClass::PRIEST: return FindCardByID("HERO_09"); case CardClass::ROGUE: return FindCardByID("HERO_03"); case CardClass::SHAMAN: return FindCardByID("HERO_02"); case CardClass::WARLOCK: return FindCardByID("HERO_07"); case CardClass::WARRIOR: return FindCardByID("HERO_01"); default: return nullptr; } } const Card* Cards::GetDefaultHeroPower(CardClass cardClass) { switch (cardClass) { case CardClass::DRUID: return FindCardByID("CS2_017"); case CardClass::HUNTER: return FindCardByID("DS1h_292"); case CardClass::MAGE: return FindCardByID("CS2_034"); case CardClass::PALADIN: return FindCardByID("CS2_101"); case CardClass::PRIEST: return FindCardByID("CS1h_001"); case CardClass::ROGUE: return FindCardByID("CS2_083b"); case CardClass::SHAMAN: return FindCardByID("CS2_049"); case CardClass::WARLOCK: return FindCardByID("CS2_056"); case CardClass::WARRIOR: return FindCardByID("CS2_102"); default: return nullptr; } } } <|endoftext|>
<commit_before>#include <Arduino.h> #include <util/atomic.h> #include "rf69_ook.h" #define SPI_SS 10 // PB2, pin 16 #define SPI_MOSI 11 // PB3, pin 17 #define SPI_MISO 12 // PB4, pin 18 #define SPI_SCK 13 // PB5, pin 19 static uint8_t rf69ook_byte(uint8_t v) { SPDR = v; while (!(SPSR & _BV(SPIF))) ; return SPDR; } void rf69ook_writeReg(uint8_t reg, uint8_t val) { ATOMIC_BLOCK(ATOMIC_FORCEON) { digitalWrite(SPI_SS, LOW); rf69ook_byte(reg | 0x80); rf69ook_byte(val); digitalWrite(SPI_SS, HIGH); } } uint8_t rf69ook_readReg(uint8_t reg) { ATOMIC_BLOCK(ATOMIC_FORCEON) { uint8_t retVal; digitalWrite(SPI_SS, LOW); rf69ook_byte(reg); retVal = rf69ook_byte(0x00); digitalWrite(SPI_SS, HIGH); return retVal; } } bool rf69ook_init(void) { pinMode(SPI_SS, OUTPUT); digitalWrite(SPI_SS, HIGH); pinMode(SPI_MOSI, OUTPUT); pinMode(SPI_MISO, INPUT); pinMode(SPI_SCK, OUTPUT); SPCR = _BV(SPE) | _BV(MSTR); SPSR |= _BV(SPI2X); delay(50); uint8_t deviceId = rf69ook_readReg(0x10); // Should be 0x24 but as long as it isn't blank if (deviceId == 0x00 || deviceId == 0xff) return false; rf69ook_writeReg(0x01, 0x04); // mode standby rf69ook_writeReg(0x02, 0b01101000); // no shaping, OOK modulation, continuous mode with no sync rf69ook_writeReg(0x03, 0x3E); // bitrate= rf69ook_writeReg(0x04, 0x80); // 2000 bit = 500uS per bit // Frequency 433.845MHz / (32M >> 19) rf69ook_writeReg(0x07, 0x6c); rf69ook_writeReg(0x08, 0x76); rf69ook_writeReg(0x09, 0x15); // bandwidth //rf69ook_writeReg(0x19, 0b01000000); // Stock DdcFreq, 250khz //rf69ook_writeReg(0x19, 0b01010000); // Stock DdcFreq, 166khz //rf69ook_writeReg(0x19, 0b01001001); // Stock DdcFreq, 100Khz rf69ook_writeReg(0x19, 0b01001010); // Stock DdcFreq, 50khz //rf69ook_writeReg(0x19, 0b01001011); // Stock DdcFreq, 25khz //rf69ook_writeReg(0x19, 0b01001100); // Stock DdcFreq, 12.5khz //rf69ook_writeReg(0x19, 0b01001101); // 6.3khz //rf69ook_writeReg(0x19, 0b01001110); // 3.1khz //rf69ook_writeReg(0x19, 0b01001111); // 1.3khz //rf69ook_writeReg(0x18, 0x80); // 200 ohm auto lna gain rf69ook_writeReg(0x18, 0x08); // 50 ohm auto gain (default) //rf69ook_writeReg(0x18, 0x81); // 200 ohm lna max gain //rf69ook_writeReg(0x18, 0x01); // 50ohm lna max gain //rf69ook_writeReg(0x18, 0x08); // -12db gain rf69ook_writeReg(0x1b, 0b01000000); //peak OOK threshold (default) //rf69ook_writeReg(0x1b, 0b00000000); //fixed OOK threshold rf69ook_writeReg(0x1d, 0x30); // OokFixedThresh (noise floor when used in peak mode) //rf69ook_writeReg(0x29, 0xe4); // RssiThreshold (default) //rf69ook_writeReg(0x2e, 0x18); // SYNC off, sync size 3, 0 errors //rf69ook_writeReg(0x2e, 0x98); // SYNC on, sync size 3, 0 errors (default) rf69ook_writeReg(0x01, 0x10); // mode Rx rf69ook_writeReg(0x1e, bit(1)); // AFC clear, must be set when in RX? return true; } void rf69ook_startRssi(void) { rf69ook_writeReg(0x23, 0x01); } uint8_t rf69ook_Rssi(void) { return rf69ook_readReg(0x24); } void rf69ook_dumpRegs(void) { for (uint8_t i=0; i<0x30; ++i) { uint8_t v = rf69ook_readReg(i); if (v < 0x10) Serial.print('0'); Serial.print(v, HEX); if (i % 16 == 15) Serial.println(); else Serial.print(' '); } } <commit_msg>Enable bit syncronizer on RF69, reduce receive BW to 25khz<commit_after>#include <Arduino.h> #include <util/atomic.h> #include "rf69_ook.h" #define SPI_SS 10 // PB2, pin 16 #define SPI_MOSI 11 // PB3, pin 17 #define SPI_MISO 12 // PB4, pin 18 #define SPI_SCK 13 // PB5, pin 19 static uint8_t rf69ook_byte(uint8_t v) { SPDR = v; while (!(SPSR & _BV(SPIF))) ; return SPDR; } void rf69ook_writeReg(uint8_t reg, uint8_t val) { ATOMIC_BLOCK(ATOMIC_FORCEON) { digitalWrite(SPI_SS, LOW); rf69ook_byte(reg | 0x80); rf69ook_byte(val); digitalWrite(SPI_SS, HIGH); } } uint8_t rf69ook_readReg(uint8_t reg) { ATOMIC_BLOCK(ATOMIC_FORCEON) { uint8_t retVal; digitalWrite(SPI_SS, LOW); rf69ook_byte(reg); retVal = rf69ook_byte(0x00); digitalWrite(SPI_SS, HIGH); return retVal; } } bool rf69ook_init(void) { pinMode(SPI_SS, OUTPUT); digitalWrite(SPI_SS, HIGH); pinMode(SPI_MOSI, OUTPUT); pinMode(SPI_MISO, INPUT); pinMode(SPI_SCK, OUTPUT); SPCR = _BV(SPE) | _BV(MSTR); SPSR |= _BV(SPI2X); delay(50); uint8_t deviceId = rf69ook_readReg(0x10); // Should be 0x24 but as long as it isn't blank if (deviceId == 0x00 || deviceId == 0xff) return false; rf69ook_writeReg(0x01, 0x04); // mode standby //rf69ook_writeReg(0x02, 0b01101000); // no shaping, OOK modulation, continuous mode with no sync rf69ook_writeReg(0x02, 0b01001000); // no shaping, OOK modulation, continuous mode with sync rf69ook_writeReg(0x03, 0x3E); // bitrate= rf69ook_writeReg(0x04, 0x80); // 2000 bit = 500uS per bit // Frequency 433.845MHz / (32M >> 19) rf69ook_writeReg(0x07, 0x6c); rf69ook_writeReg(0x08, 0x76); rf69ook_writeReg(0x09, 0x15); // bandwidth //rf69ook_writeReg(0x19, 0b01000000); // Stock DdcFreq, 250khz //rf69ook_writeReg(0x19, 0b01010000); // Stock DdcFreq, 166khz //rf69ook_writeReg(0x19, 0b01001001); // Stock DdcFreq, 100Khz //rf69ook_writeReg(0x19, 0b01001010); // Stock DdcFreq, 50khz rf69ook_writeReg(0x19, 0b01001011); // Stock DdcFreq, 25khz //rf69ook_writeReg(0x19, 0b01001100); // Stock DdcFreq, 12.5khz //rf69ook_writeReg(0x19, 0b01001101); // 6.3khz //rf69ook_writeReg(0x19, 0b01001110); // 3.1khz //rf69ook_writeReg(0x19, 0b01001111); // 1.3khz //rf69ook_writeReg(0x18, 0x80); // 200 ohm auto lna gain rf69ook_writeReg(0x18, 0x08); // 50 ohm auto gain (default) //rf69ook_writeReg(0x18, 0x81); // 200 ohm lna max gain //rf69ook_writeReg(0x18, 0x01); // 50ohm lna max gain //rf69ook_writeReg(0x18, 0x08); // -12db gain rf69ook_writeReg(0x1b, 0b01000000); //peak OOK threshold (default) //rf69ook_writeReg(0x1b, 0b00000000); //fixed OOK threshold rf69ook_writeReg(0x1d, 0x30); // OokFixedThresh (noise floor when used in peak mode) //rf69ook_writeReg(0x29, 0xe4); // RssiThreshold (default) //rf69ook_writeReg(0x2e, 0x18); // SYNC off, sync size 3, 0 errors //rf69ook_writeReg(0x2e, 0x98); // SYNC on, sync size 3, 0 errors (default) rf69ook_writeReg(0x01, 0x10); // mode Rx rf69ook_writeReg(0x1e, bit(1)); // AFC clear, must be set when in RX? return true; } void rf69ook_startRssi(void) { rf69ook_writeReg(0x23, 0x01); } uint8_t rf69ook_Rssi(void) { return rf69ook_readReg(0x24); } void rf69ook_dumpRegs(void) { for (uint8_t i=0; i<0x30; ++i) { uint8_t v = rf69ook_readReg(i); if (v < 0x10) Serial.print('0'); Serial.print(v, HEX); if (i % 16 == 15) Serial.println(); else Serial.print(' '); } } <|endoftext|>
<commit_before>// Copyright (c) 2012 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 "ash/wm/compact_layout_manager.h" #include <vector> #include "ash/shell.h" #include "ash/shell_delegate.h" #include "ash/shell_window_ids.h" #include "ash/wm/window_util.h" #include "ui/aura/client/aura_constants.h" #include "ui/aura/window.h" #include "ui/gfx/compositor/scoped_layer_animation_settings.h" #include "ui/gfx/compositor/layer.h" #include "ui/gfx/compositor/layer_animation_sequence.h" #include "ui/gfx/screen.h" #include "ui/views/widget/widget.h" namespace ash { namespace internal { namespace { typedef std::vector<aura::Window*> WindowList; typedef std::vector<aura::Window*>::const_iterator WindowListConstIter; // Convenience method to get the layer of this container. ui::Layer* GetDefaultContainerLayer() { return Shell::GetInstance()->GetContainer( internal::kShellWindowId_DefaultContainer)->layer(); } // Whether it is a window that should be animated on entrance. bool ShouldAnimateOnEntrance(aura::Window* window) { return window && window->type() == aura::client::WINDOW_TYPE_NORMAL && window_util::IsWindowMaximized(window); } // Adjust layer bounds to grow or shrink in |delta_width|. void AdjustContainerLayerWidth(int delta_width) { gfx::Rect bounds(GetDefaultContainerLayer()->bounds()); bounds.set_width(bounds.width() + delta_width); GetDefaultContainerLayer()->SetBounds(bounds); GetDefaultContainerLayer()->GetCompositor()->WidgetSizeChanged( GetDefaultContainerLayer()->bounds().size()); } } // namespace ///////////////////////////////////////////////////////////////////////////// // CompactLayoutManager, public: CompactLayoutManager::CompactLayoutManager() : status_area_widget_(NULL), current_window_(NULL) { } CompactLayoutManager::~CompactLayoutManager() { } ///////////////////////////////////////////////////////////////////////////// // CompactLayoutManager, LayoutManager overrides: void CompactLayoutManager::OnWindowAddedToLayout(aura::Window* child) { BaseLayoutManager::OnWindowAddedToLayout(child); UpdateStatusAreaVisibility(); if (windows().size() > 1 && child->type() == aura::client::WINDOW_TYPE_NORMAL) { // The first window is already contained in the current layer, // add subsequent windows to layer bounds calculation. AdjustContainerLayerWidth(child->bounds().width()); } } void CompactLayoutManager::OnWillRemoveWindowFromLayout(aura::Window* child) { BaseLayoutManager::OnWillRemoveWindowFromLayout(child); UpdateStatusAreaVisibility(); if (windows().size() > 1 && ShouldAnimateOnEntrance(child)) AdjustContainerLayerWidth(-child->bounds().width()); if (child == current_window_) { LayoutWindows(current_window_); SwitchToReplacementWindow(); } } void CompactLayoutManager::OnChildWindowVisibilityChanged(aura::Window* child, bool visible) { BaseLayoutManager::OnChildWindowVisibilityChanged(child, visible); UpdateStatusAreaVisibility(); if (ShouldAnimateOnEntrance(child)) { LayoutWindows(visible ? NULL : child); if (visible) { current_window_ = child; AnimateSlideTo(child->bounds().x()); } else if (child == current_window_) { SwitchToReplacementWindow(); } } } void CompactLayoutManager::SetChildBounds(aura::Window* child, const gfx::Rect& requested_bounds) { gfx::Rect child_bounds(requested_bounds); // Avoid a janky resize on startup by ensuring the initial bounds fill the // screen. if (window_util::IsWindowMaximized(child)) child_bounds = gfx::Screen::GetMonitorWorkAreaNearestWindow(child); else if (window_util::IsWindowFullscreen(child)) child_bounds = gfx::Screen::GetMonitorAreaNearestWindow(child); else if (current_window_) { // All other windows should be offset by the current viewport. int offset_x = current_window_->bounds().x(); child_bounds.Offset(offset_x, 0); } SetChildBoundsDirect(child, child_bounds); } ///////////////////////////////////////////////////////////////////////////// // CompactLayoutManager, aura::WindowObserver overrides: void CompactLayoutManager::OnWindowPropertyChanged(aura::Window* window, const char* name, void* old) { BaseLayoutManager::OnWindowPropertyChanged(window, name, old); if (name == aura::client::kShowStateKey) UpdateStatusAreaVisibility(); } void CompactLayoutManager::OnWindowStackingChanged(aura::Window* window) { if (!current_window_ || ShouldAnimateOnEntrance(window)) { if (current_window_ != window) { LayoutWindows(current_window_); current_window_ = window; } // Always animate to |window| when there is a stacking change. AnimateSlideTo(window->bounds().x()); } } ///////////////////////////////////////////////////////////////////////////// // CompactLayoutManager, AnimationDelegate overrides: void CompactLayoutManager::OnImplicitAnimationsCompleted() { if (!GetDefaultContainerLayer()->GetAnimator()->is_animating()) HideWindows(); } ////////////////////////////////////////////////////////////////////////////// // CompactLayoutManager, private: void CompactLayoutManager::UpdateStatusAreaVisibility() { if (!status_area_widget_) return; // Full screen windows should hide the status area widget. bool has_fullscreen = window_util::HasFullscreenWindow(windows()); bool widget_visible = status_area_widget_->IsVisible(); if (has_fullscreen && widget_visible) status_area_widget_->Hide(); else if (!has_fullscreen && !widget_visible) status_area_widget_->Show(); } void CompactLayoutManager::AnimateSlideTo(int offset_x) { ui::ScopedLayerAnimationSettings settings( GetDefaultContainerLayer()->GetAnimator()); settings.AddObserver(this); ui::Transform transform; transform.ConcatTranslate(-offset_x, 0); GetDefaultContainerLayer()->SetTransform(transform); // Will be animated! } void CompactLayoutManager::LayoutWindows(aura::Window* skip) { ShellDelegate* shell_delegate = ash::Shell::GetInstance()->delegate(); const WindowList& windows_list = shell_delegate->GetCycleWindowList( ShellDelegate::SOURCE_KEYBOARD, ShellDelegate::ORDER_LINEAR); int new_x = 0; for (WindowListConstIter const_it = windows_list.begin(); const_it != windows_list.end(); ++const_it) { if (*const_it != skip) { gfx::Rect new_bounds((*const_it)->bounds()); new_bounds.set_x(new_x); SetChildBoundsDirect(*const_it, new_bounds); (*const_it)->layer()->SetVisible(true); new_x += (*const_it)->bounds().width(); } } } void CompactLayoutManager::HideWindows() { ShellDelegate* shell_delegate = ash::Shell::GetInstance()->delegate(); const WindowList& windows_list = shell_delegate->GetCycleWindowList( ShellDelegate::SOURCE_KEYBOARD, ShellDelegate::ORDER_LINEAR); // If we do not know which one is the current window, or if the current // window is not visible, do not attempt to hide the windows. if (current_window_ == NULL) return; // Current window should be visible, if not it is an error and we shouldn't // proceed. if (!current_window_->IsVisible()) NOTREACHED() << "Current window is invisible"; for (WindowListConstIter const_it = windows_list.begin(); const_it != windows_list.end(); ++const_it) { if (*const_it != current_window_) (*const_it)->layer()->SetVisible(false); } } aura::Window* CompactLayoutManager::FindReplacementWindow( aura::Window* window) { ShellDelegate* shell_delegate = ash::Shell::GetInstance()->delegate(); const WindowList& windows_list = shell_delegate->GetCycleWindowList( ShellDelegate::SOURCE_KEYBOARD, ShellDelegate::ORDER_LINEAR); WindowListConstIter const_it = std::find(windows_list.begin(), windows_list.end(), window); if (windows_list.size() > 1 && const_it != windows_list.end()) { do { ++const_it; if (const_it == windows_list.end()) const_it = windows_list.begin(); } while (*const_it != window && !(*const_it)->IsVisible()); if (*const_it != window) return *const_it; } return NULL; } void CompactLayoutManager::SwitchToReplacementWindow() { current_window_ = FindReplacementWindow(current_window_); if (current_window_) { ActivateWindow(current_window_); AnimateSlideTo(current_window_->bounds().x()); } } } // namespace internal } // namespace ash <commit_msg>Fix aura compact mode window transition: - disable other window animation when windows are placed into default container, avoid both window_animation and compact layout manager animating the same window. - do not animate the current window if there is already an animation going on on it.<commit_after>// Copyright (c) 2012 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 "ash/wm/compact_layout_manager.h" #include <vector> #include "ash/shell.h" #include "ash/shell_delegate.h" #include "ash/shell_window_ids.h" #include "ash/wm/window_util.h" #include "ui/aura/client/aura_constants.h" #include "ui/aura/window.h" #include "ui/gfx/compositor/scoped_layer_animation_settings.h" #include "ui/gfx/compositor/layer.h" #include "ui/gfx/compositor/layer_animation_sequence.h" #include "ui/gfx/screen.h" #include "ui/views/widget/widget.h" namespace ash { namespace internal { namespace { typedef std::vector<aura::Window*> WindowList; typedef std::vector<aura::Window*>::const_iterator WindowListConstIter; // Convenience method to get the layer of this container. ui::Layer* GetDefaultContainerLayer() { return Shell::GetInstance()->GetContainer( internal::kShellWindowId_DefaultContainer)->layer(); } // Whether it is a window that should be animated on entrance. bool ShouldAnimateOnEntrance(aura::Window* window) { return window && window->type() == aura::client::WINDOW_TYPE_NORMAL && window_util::IsWindowMaximized(window); } // Adjust layer bounds to grow or shrink in |delta_width|. void AdjustContainerLayerWidth(int delta_width) { gfx::Rect bounds(GetDefaultContainerLayer()->bounds()); bounds.set_width(bounds.width() + delta_width); GetDefaultContainerLayer()->SetBounds(bounds); GetDefaultContainerLayer()->GetCompositor()->WidgetSizeChanged( GetDefaultContainerLayer()->bounds().size()); } } // namespace ///////////////////////////////////////////////////////////////////////////// // CompactLayoutManager, public: CompactLayoutManager::CompactLayoutManager() : status_area_widget_(NULL), current_window_(NULL) { } CompactLayoutManager::~CompactLayoutManager() { } ///////////////////////////////////////////////////////////////////////////// // CompactLayoutManager, LayoutManager overrides: void CompactLayoutManager::OnWindowAddedToLayout(aura::Window* child) { // Windows added to this container does not need extra animation. if (child->type() == aura::client::WINDOW_TYPE_NORMAL) child->SetIntProperty(aura::client::kAnimationsDisabledKey, 1); BaseLayoutManager::OnWindowAddedToLayout(child); UpdateStatusAreaVisibility(); if (windows().size() > 1 && child->type() == aura::client::WINDOW_TYPE_NORMAL) { // The first window is already contained in the current layer, // add subsequent windows to layer bounds calculation. AdjustContainerLayerWidth(child->bounds().width()); } } void CompactLayoutManager::OnWillRemoveWindowFromLayout(aura::Window* child) { BaseLayoutManager::OnWillRemoveWindowFromLayout(child); UpdateStatusAreaVisibility(); if (windows().size() > 1 && ShouldAnimateOnEntrance(child)) AdjustContainerLayerWidth(-child->bounds().width()); if (child == current_window_) { LayoutWindows(current_window_); SwitchToReplacementWindow(); } // Allow window to be animated by others. if (child->type() == aura::client::WINDOW_TYPE_NORMAL) child->SetIntProperty(aura::client::kAnimationsDisabledKey, 0); } void CompactLayoutManager::OnChildWindowVisibilityChanged(aura::Window* child, bool visible) { BaseLayoutManager::OnChildWindowVisibilityChanged(child, visible); UpdateStatusAreaVisibility(); if (ShouldAnimateOnEntrance(child)) { LayoutWindows(visible ? NULL : child); if (visible) { current_window_ = child; AnimateSlideTo(child->bounds().x()); } else if (child == current_window_) { SwitchToReplacementWindow(); } } } void CompactLayoutManager::SetChildBounds(aura::Window* child, const gfx::Rect& requested_bounds) { gfx::Rect child_bounds(requested_bounds); // Avoid a janky resize on startup by ensuring the initial bounds fill the // screen. if (window_util::IsWindowMaximized(child)) child_bounds = gfx::Screen::GetMonitorWorkAreaNearestWindow(child); else if (window_util::IsWindowFullscreen(child)) child_bounds = gfx::Screen::GetMonitorAreaNearestWindow(child); else if (current_window_) { // All other windows should be offset by the current viewport. int offset_x = current_window_->bounds().x(); child_bounds.Offset(offset_x, 0); } SetChildBoundsDirect(child, child_bounds); } ///////////////////////////////////////////////////////////////////////////// // CompactLayoutManager, aura::WindowObserver overrides: void CompactLayoutManager::OnWindowPropertyChanged(aura::Window* window, const char* name, void* old) { BaseLayoutManager::OnWindowPropertyChanged(window, name, old); if (name == aura::client::kShowStateKey) UpdateStatusAreaVisibility(); } void CompactLayoutManager::OnWindowStackingChanged(aura::Window* window) { if (!current_window_ || ShouldAnimateOnEntrance(window)) { if (current_window_ != window) { LayoutWindows(current_window_); current_window_ = window; } else { // Same window as |current_window_|, and already animating. if (GetDefaultContainerLayer()->GetAnimator()->is_animating()) return; } // Animate to |window| when there is a stacking change. AnimateSlideTo(window->bounds().x()); } } ///////////////////////////////////////////////////////////////////////////// // CompactLayoutManager, AnimationDelegate overrides: void CompactLayoutManager::OnImplicitAnimationsCompleted() { if (!GetDefaultContainerLayer()->GetAnimator()->is_animating()) HideWindows(); } ////////////////////////////////////////////////////////////////////////////// // CompactLayoutManager, private: void CompactLayoutManager::UpdateStatusAreaVisibility() { if (!status_area_widget_) return; // Full screen windows should hide the status area widget. bool has_fullscreen = window_util::HasFullscreenWindow(windows()); bool widget_visible = status_area_widget_->IsVisible(); if (has_fullscreen && widget_visible) status_area_widget_->Hide(); else if (!has_fullscreen && !widget_visible) status_area_widget_->Show(); } void CompactLayoutManager::AnimateSlideTo(int offset_x) { GetDefaultContainerLayer()->GetAnimator()->RemoveObserver(this); ui::ScopedLayerAnimationSettings settings( GetDefaultContainerLayer()->GetAnimator()); settings.AddObserver(this); ui::Transform transform; transform.ConcatTranslate(-offset_x, 0); GetDefaultContainerLayer()->SetTransform(transform); // Will be animated! } void CompactLayoutManager::LayoutWindows(aura::Window* skip) { ShellDelegate* shell_delegate = ash::Shell::GetInstance()->delegate(); const WindowList& windows_list = shell_delegate->GetCycleWindowList( ShellDelegate::SOURCE_KEYBOARD, ShellDelegate::ORDER_LINEAR); int new_x = 0; for (WindowListConstIter const_it = windows_list.begin(); const_it != windows_list.end(); ++const_it) { if (*const_it != skip) { gfx::Rect new_bounds((*const_it)->bounds()); new_bounds.set_x(new_x); SetChildBoundsDirect(*const_it, new_bounds); (*const_it)->layer()->SetVisible(true); new_x += (*const_it)->bounds().width(); } } } void CompactLayoutManager::HideWindows() { // If we do not know which one is the current window, or if the current // window is not visible, do not attempt to hide the windows. if (current_window_ == NULL) return; // Current window should be visible, if not it is an error and we shouldn't // proceed. if (!current_window_->layer()->visible()) NOTREACHED() << "Current window is invisible"; ShellDelegate* shell_delegate = ash::Shell::GetInstance()->delegate(); const WindowList& windows_list = shell_delegate->GetCycleWindowList( ShellDelegate::SOURCE_KEYBOARD, ShellDelegate::ORDER_LINEAR); for (WindowListConstIter const_it = windows_list.begin(); const_it != windows_list.end(); ++const_it) { if (*const_it != current_window_) (*const_it)->layer()->SetVisible(false); } } aura::Window* CompactLayoutManager::FindReplacementWindow( aura::Window* window) { ShellDelegate* shell_delegate = ash::Shell::GetInstance()->delegate(); const WindowList& windows_list = shell_delegate->GetCycleWindowList( ShellDelegate::SOURCE_KEYBOARD, ShellDelegate::ORDER_LINEAR); WindowListConstIter const_it = std::find(windows_list.begin(), windows_list.end(), window); if (windows_list.size() > 1 && const_it != windows_list.end()) { do { ++const_it; if (const_it == windows_list.end()) const_it = windows_list.begin(); } while (*const_it != window && !(*const_it)->IsVisible()); if (*const_it != window) return *const_it; } return NULL; } void CompactLayoutManager::SwitchToReplacementWindow() { current_window_ = FindReplacementWindow(current_window_); if (current_window_) { ActivateWindow(current_window_); AnimateSlideTo(current_window_->bounds().x()); } } } // namespace internal } // namespace ash <|endoftext|>
<commit_before>// Copyright (C) 2014, Richard Thomson. All rights reserved. #include "date_time.h" #include <boost/fusion/include/adapt_struct.hpp> #include <boost/spirit/include/qi.hpp> #include <stdexcept> using namespace boost::spirit::qi; BOOST_FUSION_ADAPT_STRUCT(date_time::moment, (unsigned, day) (date_time::months, month) (unsigned, year) (unsigned, hour) (unsigned, minute) (unsigned, second) (int, time_zone_offset) ); namespace { typedef ascii::space_type skipper; template <typename Iter> struct date_time_grammar : grammar<Iter, date_time::moment(), skipper> { date_time_grammar() : date_time_grammar::base_type{start} { month_names.add("Jan", date_time::January) ("Feb", date_time::February) ("Mar", date_time::March) ("Apr", date_time::April) ("May", date_time::May) ("Jun", date_time::June) ("Jul", date_time::July) ("Aug", date_time::August) ("Sep", date_time::September) ("Oct", date_time::October) ("Nov", date_time::November) ("Dec", date_time::December); typedef uint_parser<unsigned, 10, 2, 2> digit_2; typedef uint_parser<unsigned, 10, 4, 4> digit_4; start = digit_2() >> month_names >> digit_4() >> digit_2() >> ':' >> digit_2() >> '+' >> digit_4(); }; symbols<char const, date_time::months> month_names; rule<Iter, date_time::moment(), skipper> start; }; } namespace date_time { moment parse(std::string const& text) { moment result{}; std::string::const_iterator start{text.begin()}; if (phrase_parse(start, text.end(), date_time_grammar<std::string::const_iterator>(), ascii::space, result) && start == text.end()) { return result; } throw std::domain_error("invalid date time"); } } <commit_msg>Refactor: Simplify expressions; prefer {} for default initialization.<commit_after>// Copyright (C) 2014, Richard Thomson. All rights reserved. #include "date_time.h" #include <boost/fusion/include/adapt_struct.hpp> #include <boost/spirit/include/qi.hpp> #include <stdexcept> using namespace boost::spirit::qi; BOOST_FUSION_ADAPT_STRUCT(date_time::moment, (unsigned, day) (date_time::months, month) (unsigned, year) (unsigned, hour) (unsigned, minute) (unsigned, second) (int, time_zone_offset) ); namespace { typedef ascii::space_type skipper; template <typename Iter> struct date_time_grammar : grammar<Iter, date_time::moment(), skipper> { date_time_grammar() : date_time_grammar::base_type{start} { month_names.add("Jan", date_time::January) ("Feb", date_time::February) ("Mar", date_time::March) ("Apr", date_time::April) ("May", date_time::May) ("Jun", date_time::June) ("Jul", date_time::July) ("Aug", date_time::August) ("Sep", date_time::September) ("Oct", date_time::October) ("Nov", date_time::November) ("Dec", date_time::December); uint_parser<unsigned, 10, 2, 2> digit_2; uint_parser<unsigned, 10, 4, 4> digit_4; start = digit_2 >> month_names >> digit_4 >> digit_2 >> ':' >> digit_2 >> '+' >> digit_4; }; symbols<char const, date_time::months> month_names; rule<Iter, date_time::moment(), skipper> start; }; } namespace date_time { moment parse(std::string const& text) { moment result{}; std::string::const_iterator start{text.begin()}; if (phrase_parse(start, text.end(), date_time_grammar<std::string::const_iterator>{}, ascii::space, result) && start == text.end()) { return result; } throw std::domain_error("invalid date time"); } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: b3dtex.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2005-09-09 02:13:41 $ * * 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 _B3D_B3DTEX_HXX #define _B3D_B3DTEX_HXX #ifndef _SV_OPENGL_HXX #include <vcl/opengl.hxx> #endif #ifndef _SV_BITMAPEX_HXX #include <vcl/bitmapex.hxx> #endif #ifndef _TOOLS_COLOR_HXX #include <tools/color.hxx> #endif #ifndef _SV_SALBTYPE_HXX #include <vcl/salbtype.hxx> #endif #ifndef _TOOLS_TIME_HXX #include <tools/time.hxx> #endif // Vorausdeklarationen class BitmapReadAccess; class BitmapColor; /************************************************************************* |* |* define for lifetime of a texture in texture cache. |* Parameter of Time(...) call, so hrs, min, sec, 100thsec. |* Timer for cache uses ten secs delays |* \************************************************************************/ #define B3D_TEXTURE_LIFETIME 0, 1, 0 /************************************************************************* |* |* Long-Zeiger fuer OpenGL Texturdatenuebergabe |* \************************************************************************/ #ifdef WIN typedef UINT8 huge* GL_UINT8; #else typedef UINT8* GL_UINT8; #endif /************************************************************************* |* |* Art der Pixeldaten der Textur |* \************************************************************************/ enum Base3DTextureKind { Base3DTextureLuminance = 1, Base3DTextureIntensity, Base3DTextureColor }; /************************************************************************* |* |* Modus der Textur |* \************************************************************************/ enum Base3DTextureMode { Base3DTextureReplace = 1, Base3DTextureModulate, Base3DTextureBlend }; /************************************************************************* |* |* Filtermodus der Textur |* \************************************************************************/ enum Base3DTextureFilter { Base3DTextureNearest = 1, Base3DTextureLinear }; /************************************************************************* |* |* Wrapping-Modus |* \************************************************************************/ enum Base3DTextureWrap { Base3DTextureClamp = 1, Base3DTextureRepeat, Base3DTextureSingle }; /************************************************************************* |* |* Defines fuer Maskenbildung um Entscheidung innerhalb von ModifyColor |* zu beschleunigen |* \************************************************************************/ #define B3D_TXT_KIND_LUM 0x00 #define B3D_TXT_KIND_INT 0x01 #define B3D_TXT_KIND_COL 0x02 #define B3D_TXT_MODE_REP 0x04 #define B3D_TXT_MODE_MOD 0x08 #define B3D_TXT_MODE_BND 0x0C #define B3D_TXT_FLTR_NEA 0x10 /************************************************************************* |* |* Klassen fuer TexturAttribute beim Anfordern von Texturen |* \************************************************************************/ #define TEXTURE_ATTRIBUTE_TYPE_COLOR 0x0000 #define TEXTURE_ATTRIBUTE_TYPE_BITMAP 0x0001 #define TEXTURE_ATTRIBUTE_TYPE_GRADIENT 0x0002 #define TEXTURE_ATTRIBUTE_TYPE_HATCH 0x0003 class TextureAttributes { private: void* mpFloatTrans; BOOL mbGhosted; public: TextureAttributes(BOOL bGhosted, void* pFT); virtual BOOL operator==(const TextureAttributes&) const; virtual UINT16 GetTextureAttributeType() const =0; BOOL GetGhostedAttribute() { return mbGhosted; } void* GetFloatTransAttribute() { return mpFloatTrans; } }; class TextureAttributesColor : public TextureAttributes { private: Color maColorAttribute; public: TextureAttributesColor(BOOL bGhosted, void* pFT, Color aColor); virtual BOOL operator==(const TextureAttributes&) const; virtual UINT16 GetTextureAttributeType() const; Color GetColorAttribute() { return maColorAttribute; } }; class TextureAttributesBitmap : public TextureAttributes { private: Bitmap maBitmapAttribute; public: TextureAttributesBitmap(BOOL bGhosted, void* pFT, Bitmap aBmp); virtual BOOL operator==(const TextureAttributes&) const; virtual UINT16 GetTextureAttributeType() const; Bitmap GetBitmapAttribute() { return maBitmapAttribute; } }; class TextureAttributesGradient : public TextureAttributes { private: void* mpFill; void* mpStepCount; public: TextureAttributesGradient(BOOL bGhosted, void* pFT, void* pF, void *pSC); virtual BOOL operator==(const TextureAttributes&) const; virtual UINT16 GetTextureAttributeType() const; void* GetFillAttribute() { return mpFill; } void* GetStepCountAttribute() { return mpStepCount; } }; class TextureAttributesHatch : public TextureAttributes { private: void* mpFill; public: TextureAttributesHatch(BOOL bGhosted, void* pFT, void* pF); virtual BOOL operator==(const TextureAttributes&) const; virtual UINT16 GetTextureAttributeType() const; void* GetHatchFillAttribute() { return mpFill; } }; /************************************************************************* |* |* Klasse fuer Texturen in Base3D |* \************************************************************************/ class B3dTexture { protected: // Die Bitmap(s) der Textur Bitmap aBitmap; AlphaMask aAlphaMask; BitmapReadAccess* pReadAccess; BitmapReadAccess* pAlphaReadAccess; // Attribute bei der Generierung TextureAttributes* pAttributes; // Gibt die Haeufigkeit der Benutzung wieder Time maTimeStamp; // Farbe fuer Base3DTextureBlend - Modus BitmapColor aColBlend; // Farbe, wenn keine Textur an einer Stelle liegt BitmapColor aColTexture; // Art der Textur Base3DTextureKind eKind; // Modus der Textur Base3DTextureMode eMode; // Filter Base3DTextureFilter eFilter; // Wrapping-Modes fuer beide Freiheitsgrade Base3DTextureWrap eWrapS; Base3DTextureWrap eWrapT; // Entscheidungsvariable UINT8 nSwitchVal; // Vorbestimmbare interne booleans unsigned bTextureKindChanged : 1; // Konstruktor / Destruktor B3dTexture(TextureAttributes& rAtt, BitmapEx& rBmpEx, Base3DTextureKind=Base3DTextureColor, Base3DTextureMode=Base3DTextureReplace, Base3DTextureFilter=Base3DTextureNearest, Base3DTextureWrap eS=Base3DTextureSingle, Base3DTextureWrap eT=Base3DTextureSingle); virtual ~B3dTexture(); // Interne Zugriffsfunktion auf die BitMapFarben inline const BitmapColor GetBitmapColor(long nX, long nY); inline const sal_uInt8 GetBitmapTransparency(long nX, long nY); // Generate switch val for optimized own texture mapping void SetSwitchVal(); // time stamp and texture cache methods void Touch() { maTimeStamp = Time() + Time(B3D_TEXTURE_LIFETIME); } const Time& GetTimeStamp() const { return maTimeStamp; } public: // Zugriff auf die Attribute der Textur TextureAttributes& GetAttributes(); // Zugriff auf Bitmap Bitmap& GetBitmap() { return aBitmap; } AlphaMask& GetAlphaMask() { return aAlphaMask; } BitmapEx GetBitmapEx() { return BitmapEx(aBitmap, aAlphaMask); } const Size GetBitmapSize() { return aBitmap.GetSizePixel(); } // Texturfunktion void ModifyColor(Color& rCol, double fS, double fT); // Art der Pixeldaten lesen/bestimmen void SetTextureKind(Base3DTextureKind eNew); Base3DTextureKind GetTextureKind() { return eKind; } // Texturmodus lesen/bestimmen void SetTextureMode(Base3DTextureMode eNew); Base3DTextureMode GetTextureMode() { return eMode; } // Filtermodus lesen/bestimmen void SetTextureFilter(Base3DTextureFilter eNew); Base3DTextureFilter GetTextureFilter() { return eFilter; } // Wrapping fuer beide Freiheitsgrade lesen/bestimmen void SetTextureWrapS(Base3DTextureWrap eNew); Base3DTextureWrap GetTextureWrapS() { return eWrapS; } void SetTextureWrapT(Base3DTextureWrap eNew); Base3DTextureWrap GetTextureWrapT() { return eWrapT; } // Blend-Color lesen/bestimmen void SetBlendColor(Color rNew); Color GetBlendColor(); // Textur-Ersatz-Color lesen/bestimmen void SetTextureColor(Color rNew); Color GetTextureColor(); protected: // Zugriff auf Konstruktor/Destruktor nur fuer die verwaltenden Klassen friend class Base3D; friend class Base3DOpenGL; friend class B3dGlobalData; friend class B3dTextureStore; }; /************************************************************************* |* |* erweiterte Klasse fuer Texturen in Base3DOpenGL |* \************************************************************************/ class B3dTextureOpenGL : public B3dTexture { private: // Name dieser Textur in OpenGL GLuint nTextureName; // Konstruktor / Destruktor B3dTextureOpenGL(TextureAttributes& rAtt, BitmapEx& rBmpEx, OpenGL& rOGL, Base3DTextureKind=Base3DTextureColor, Base3DTextureMode=Base3DTextureReplace, Base3DTextureFilter=Base3DTextureNearest, Base3DTextureWrap eS=Base3DTextureClamp, Base3DTextureWrap eT=Base3DTextureClamp); virtual ~B3dTextureOpenGL(); // In OpenGL die Textur zerstoeren void DestroyOpenGLTexture(OpenGL&); public: // Setze diese Textur in OpenGL als aktuelle Textur void MakeCurrentTexture(OpenGL&); // Erzeuge diese Textur als OpenGL-Textur void CreateOpenGLTexture(OpenGL&); protected: // Zugriff auf Konstruktor/Destruktor nur fuer die verwaltenden Klassen friend class Base3D; friend class Base3DOpenGL; friend class B3dTextureStore; }; #endif // _B3D_B3DTEX_HXX <commit_msg>INTEGRATION: CWS warnings01 (1.5.24); FILE MERGED 2005/10/27 14:32:48 sj 1.5.24.1: #i55991# warning free code<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: b3dtex.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: hr $ $Date: 2006-06-19 21:35:19 $ * * 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 _B3D_B3DTEX_HXX #define _B3D_B3DTEX_HXX #ifndef _SV_OPENGL_HXX #include <vcl/opengl.hxx> #endif #ifndef _SV_BITMAPEX_HXX #include <vcl/bitmapex.hxx> #endif #ifndef _TOOLS_COLOR_HXX #include <tools/color.hxx> #endif #ifndef _SV_SALBTYPE_HXX #include <vcl/salbtype.hxx> #endif #ifndef _TOOLS_TIME_HXX #include <tools/time.hxx> #endif // Vorausdeklarationen class BitmapReadAccess; class BitmapColor; /************************************************************************* |* |* define for lifetime of a texture in texture cache. |* Parameter of Time(...) call, so hrs, min, sec, 100thsec. |* Timer for cache uses ten secs delays |* \************************************************************************/ #define B3D_TEXTURE_LIFETIME 0, 1, 0 /************************************************************************* |* |* Long-Zeiger fuer OpenGL Texturdatenuebergabe |* \************************************************************************/ #ifdef WIN typedef UINT8 huge* GL_UINT8; #else typedef UINT8* GL_UINT8; #endif /************************************************************************* |* |* Art der Pixeldaten der Textur |* \************************************************************************/ enum Base3DTextureKind { Base3DTextureLuminance = 1, Base3DTextureIntensity, Base3DTextureColor }; /************************************************************************* |* |* Modus der Textur |* \************************************************************************/ enum Base3DTextureMode { Base3DTextureReplace = 1, Base3DTextureModulate, Base3DTextureBlend }; /************************************************************************* |* |* Filtermodus der Textur |* \************************************************************************/ enum Base3DTextureFilter { Base3DTextureNearest = 1, Base3DTextureLinear }; /************************************************************************* |* |* Wrapping-Modus |* \************************************************************************/ enum Base3DTextureWrap { Base3DTextureClamp = 1, Base3DTextureRepeat, Base3DTextureSingle }; /************************************************************************* |* |* Defines fuer Maskenbildung um Entscheidung innerhalb von ModifyColor |* zu beschleunigen |* \************************************************************************/ #define B3D_TXT_KIND_LUM 0x00 #define B3D_TXT_KIND_INT 0x01 #define B3D_TXT_KIND_COL 0x02 #define B3D_TXT_MODE_REP 0x04 #define B3D_TXT_MODE_MOD 0x08 #define B3D_TXT_MODE_BND 0x0C #define B3D_TXT_FLTR_NEA 0x10 /************************************************************************* |* |* Klassen fuer TexturAttribute beim Anfordern von Texturen |* \************************************************************************/ #define TEXTURE_ATTRIBUTE_TYPE_COLOR 0x0000 #define TEXTURE_ATTRIBUTE_TYPE_BITMAP 0x0001 #define TEXTURE_ATTRIBUTE_TYPE_GRADIENT 0x0002 #define TEXTURE_ATTRIBUTE_TYPE_HATCH 0x0003 class TextureAttributes { private: void* mpFloatTrans; BOOL mbGhosted; public: TextureAttributes(BOOL bGhosted, void* pFT); virtual ~TextureAttributes(){}; virtual BOOL operator==(const TextureAttributes&) const; virtual UINT16 GetTextureAttributeType() const =0; BOOL GetGhostedAttribute() { return mbGhosted; } void* GetFloatTransAttribute() { return mpFloatTrans; } }; class TextureAttributesColor : public TextureAttributes { private: Color maColorAttribute; public: TextureAttributesColor(BOOL bGhosted, void* pFT, Color aColor); virtual BOOL operator==(const TextureAttributes&) const; virtual UINT16 GetTextureAttributeType() const; Color GetColorAttribute() { return maColorAttribute; } }; class TextureAttributesBitmap : public TextureAttributes { private: Bitmap maBitmapAttribute; public: TextureAttributesBitmap(BOOL bGhosted, void* pFT, Bitmap aBmp); virtual BOOL operator==(const TextureAttributes&) const; virtual UINT16 GetTextureAttributeType() const; Bitmap GetBitmapAttribute() { return maBitmapAttribute; } }; class TextureAttributesGradient : public TextureAttributes { private: void* mpFill; void* mpStepCount; public: TextureAttributesGradient(BOOL bGhosted, void* pFT, void* pF, void *pSC); virtual BOOL operator==(const TextureAttributes&) const; virtual UINT16 GetTextureAttributeType() const; void* GetFillAttribute() { return mpFill; } void* GetStepCountAttribute() { return mpStepCount; } }; class TextureAttributesHatch : public TextureAttributes { private: void* mpFill; public: TextureAttributesHatch(BOOL bGhosted, void* pFT, void* pF); virtual BOOL operator==(const TextureAttributes&) const; virtual UINT16 GetTextureAttributeType() const; void* GetHatchFillAttribute() { return mpFill; } }; /************************************************************************* |* |* Klasse fuer Texturen in Base3D |* \************************************************************************/ class B3dTexture { protected: // Die Bitmap(s) der Textur Bitmap aBitmap; AlphaMask aAlphaMask; BitmapReadAccess* pReadAccess; BitmapReadAccess* pAlphaReadAccess; // Attribute bei der Generierung TextureAttributes* pAttributes; // Gibt die Haeufigkeit der Benutzung wieder Time maTimeStamp; // Farbe fuer Base3DTextureBlend - Modus BitmapColor aColBlend; // Farbe, wenn keine Textur an einer Stelle liegt BitmapColor aColTexture; // Art der Textur Base3DTextureKind eKind; // Modus der Textur Base3DTextureMode eMode; // Filter Base3DTextureFilter eFilter; // Wrapping-Modes fuer beide Freiheitsgrade Base3DTextureWrap eWrapS; Base3DTextureWrap eWrapT; // Entscheidungsvariable UINT8 nSwitchVal; // Vorbestimmbare interne booleans unsigned bTextureKindChanged : 1; // Konstruktor / Destruktor B3dTexture(TextureAttributes& rAtt, BitmapEx& rBmpEx, Base3DTextureKind=Base3DTextureColor, Base3DTextureMode=Base3DTextureReplace, Base3DTextureFilter=Base3DTextureNearest, Base3DTextureWrap eS=Base3DTextureSingle, Base3DTextureWrap eT=Base3DTextureSingle); virtual ~B3dTexture(); // Interne Zugriffsfunktion auf die BitMapFarben inline const BitmapColor GetBitmapColor(long nX, long nY); inline const sal_uInt8 GetBitmapTransparency(long nX, long nY); // Generate switch val for optimized own texture mapping void SetSwitchVal(); // time stamp and texture cache methods void Touch() { maTimeStamp = Time() + Time(B3D_TEXTURE_LIFETIME); } const Time& GetTimeStamp() const { return maTimeStamp; } public: // Zugriff auf die Attribute der Textur TextureAttributes& GetAttributes(); // Zugriff auf Bitmap Bitmap& GetBitmap() { return aBitmap; } AlphaMask& GetAlphaMask() { return aAlphaMask; } BitmapEx GetBitmapEx() { return BitmapEx(aBitmap, aAlphaMask); } const Size GetBitmapSize() { return aBitmap.GetSizePixel(); } // Texturfunktion void ModifyColor(Color& rCol, double fS, double fT); // Art der Pixeldaten lesen/bestimmen void SetTextureKind(Base3DTextureKind eNew); Base3DTextureKind GetTextureKind() { return eKind; } // Texturmodus lesen/bestimmen void SetTextureMode(Base3DTextureMode eNew); Base3DTextureMode GetTextureMode() { return eMode; } // Filtermodus lesen/bestimmen void SetTextureFilter(Base3DTextureFilter eNew); Base3DTextureFilter GetTextureFilter() { return eFilter; } // Wrapping fuer beide Freiheitsgrade lesen/bestimmen void SetTextureWrapS(Base3DTextureWrap eNew); Base3DTextureWrap GetTextureWrapS() { return eWrapS; } void SetTextureWrapT(Base3DTextureWrap eNew); Base3DTextureWrap GetTextureWrapT() { return eWrapT; } // Blend-Color lesen/bestimmen void SetBlendColor(Color rNew); Color GetBlendColor(); // Textur-Ersatz-Color lesen/bestimmen void SetTextureColor(Color rNew); Color GetTextureColor(); protected: // Zugriff auf Konstruktor/Destruktor nur fuer die verwaltenden Klassen friend class Base3D; friend class Base3DOpenGL; friend class B3dGlobalData; friend class B3dTextureStore; }; /************************************************************************* |* |* erweiterte Klasse fuer Texturen in Base3DOpenGL |* \************************************************************************/ class B3dTextureOpenGL : public B3dTexture { private: // Name dieser Textur in OpenGL GLuint nTextureName; // Konstruktor / Destruktor B3dTextureOpenGL(TextureAttributes& rAtt, BitmapEx& rBmpEx, OpenGL& rOGL, Base3DTextureKind=Base3DTextureColor, Base3DTextureMode=Base3DTextureReplace, Base3DTextureFilter=Base3DTextureNearest, Base3DTextureWrap eS=Base3DTextureClamp, Base3DTextureWrap eT=Base3DTextureClamp); virtual ~B3dTextureOpenGL(); // In OpenGL die Textur zerstoeren void DestroyOpenGLTexture(OpenGL&); public: // Setze diese Textur in OpenGL als aktuelle Textur void MakeCurrentTexture(OpenGL&); // Erzeuge diese Textur als OpenGL-Textur void CreateOpenGLTexture(OpenGL&); protected: // Zugriff auf Konstruktor/Destruktor nur fuer die verwaltenden Klassen friend class Base3D; friend class Base3DOpenGL; friend class B3dTextureStore; }; #endif // _B3D_B3DTEX_HXX <|endoftext|>
<commit_before>/** table.cc --- * * Copyright (C) 2010 OpenCog Foundation * * Author: Nil Geisweiller <ngeiswei@gmail.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * This program 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 Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "table.h" #include <iomanip> #include <boost/range/algorithm/for_each.hpp> #include <boost/range/algorithm/transform.hpp> #include <opencog/util/dorepeat.h> #include <opencog/util/Logger.h> #include "ann.h" #include "simple_nn.h" #include "convert_ann_combo.h" namespace opencog { namespace combo { using namespace std; using namespace boost; using namespace boost::adaptors; // ------------------------------------------------------- ITable::ITable() {} ITable::ITable(const ITable::super& mat, vector<string> il) : super(mat), labels(il) {} ITable::ITable(const type_tree& tt, int nsamples, contin_t min_contin, contin_t max_contin) { arity_t barity = boolean_arity(tt), carity = contin_arity(tt); if (nsamples < 0) nsamples = std::max(pow2(barity), sample_count(carity)); // in that case the boolean inputs are not picked randomly but // instead are enumerated bool comp_tt = nsamples == (int)pow2(barity); // Populate the matrix. auto root = tt.begin(); for (int i = 0; i < nsamples; ++i) { size_t bidx = 0; // counter used to enumerate all // booleans vertex_seq vs; foreach (type_node n, make_pair(root.begin(), root.last_child())) if (n == id::boolean_type) vs.push_back(bool_to_vertex(comp_tt? i & (1 << bidx++) : randGen().randint(2))); else if (n == id::contin_type) vs.push_back((max_contin - min_contin) * randGen().randdouble() + min_contin); else if (n == id::enum_type) vs.push_back(enum_t::get_random_enum()); else if (n == id::unknown_type) vs.push_back(vertex()); // push default vertex else OC_ASSERT(false, "Not implemented yet"); // input vector push_back(vs); } } // ------------------------------------------------------- void ITable::set_labels(const vector<string>& il) { labels = il; } static const std::string default_input_label("i"); vector<string> ITable::get_default_labels() const { string_seq res; for (arity_t i = 1; i <= get_arity(); ++i) res.push_back(default_input_label + boost::lexical_cast<std::string>(i)); return res; } const vector<string>& ITable::get_labels() const { if (labels.empty() and !super::empty()) // return default labels labels = get_default_labels(); return labels; } void ITable::set_types(const vector<type_node>& il) { types = il; } const vector<type_node>& ITable::get_types() const { if (types.empty() and !super::empty()) { arity_t arity = get_arity(); types.resize(arity); for (arity_t i=0; i<arity; i++) { types[i] = id::unknown_type; } } return types; } // ------------------------------------------------------- void ITable::insert_col(const std::string& clab, const vertex_seq& col, int off) { // insert label labels.insert(off >= 0 ? labels.begin() + off : labels.end(), clab); // insert values if (empty()) { OC_ASSERT(off < 0); foreach (const auto& v, col) push_back({v}); return; } OC_ASSERT (col.size() == size(), "Incorrect column length!"); for (unsigned i = 0; i < col.size(); i++) { auto& row = (*this)[i]; row.insert(off >= 0 ? row.begin() + off : row.end(), col[i]); } } vector<vertex> ITable::get_column_data(const std::string& name) const { vector<vertex> col; auto pos = std::find(labels.begin(), labels.end(), name); if (pos == labels.end()) return col; size_t off = distance(labels.begin(), pos); foreach (const auto& row, *this) col.push_back(row[off]); return col; } void ITable::delete_column(const string& name) { auto pos = std::find(labels.begin(), labels.end(), name); if (pos == labels.end()) return; size_t off = distance(labels.begin(), pos); // Delete the column foreach (vertex_seq& row, *this) row.erase(row.begin() + off); // Delete the label as well. if (!labels.empty()) labels.erase(labels.begin() + off); if (!types.empty()) types.erase(types.begin() + off); } void ITable::delete_columns(const vector<string>& ignore_features) { foreach(const string& feat, ignore_features) delete_column(feat); } // ------------------------------------------------------- OTable::OTable(const string& ol) : label(ol) {} OTable::OTable(const super& ot, const string& ol) : super(ot), label(ol) {} OTable::OTable(const combo_tree& tr, const ITable& itable, const string& ol) : label(ol) { OC_ASSERT(!tr.empty()); if (is_ann_type(*tr.begin())) { // we treat ANN differently because they must be decoded // before being evaluated. Also note that if there are memory // neurones then the state of the network is evolving at each // input, so the order within itable does matter ann net = tree_transform().decodify_tree(tr); int depth = net.feedforward_depth(); foreach(const vertex_seq& vv, itable) { vector<contin_t> tmp(vv.size()); transform(vv, tmp.begin(), get_contin); tmp.push_back(1.0); // net uses that in case the function // to learn needs some kind of offset net.load_inputs(tmp); dorepeat(depth) net.propagate(); push_back(net.outputs[0]->activation); } } else { foreach(const vertex_seq& vs, itable) push_back(eval_throws_binding(vs, tr)); } } OTable::OTable(const combo_tree& tr, const CTable& ctable, const string& ol) : label(ol) { arity_set as = get_argument_abs_idx_set(tr); for_each(ctable | map_keys, [&](const vertex_seq& vs) { this->push_back(eval_throws_binding(vs, tr)); }); } void OTable::set_label(const string& ol) { label = ol; } const string& OTable::get_label() const { return label; } // ------------------------------------------------------- bool OTable::operator==(const OTable& rhs) const { const static contin_t epsilon = 1e-12; for(auto lit = begin(), rit = rhs.begin(); lit != end(); ++lit, ++rit) { if(is_contin(*lit) && is_contin(*rit)) { if(!isApproxEq(get_contin(*lit), get_contin(*rit), epsilon)) return false; } else if(*lit != *rit) return false; } return rhs.get_label() == label; } contin_t OTable::abs_distance(const OTable& ot) const { OC_ASSERT(ot.size() == size()); contin_t res = 0; for(const_iterator x = begin(), y = ot.begin(); x != end();) res += fabs(get_contin(*(x++)) - get_contin(*(y++))); return res; } contin_t OTable::sum_squared_error(const OTable& ot) const { OC_ASSERT(ot.size() == size()); contin_t res = 0; for(const_iterator x = begin(), y = ot.begin(); x != end();) res += sq(get_contin(*(x++)) - get_contin(*(y++))); return res; } contin_t OTable::mean_squared_error(const OTable& ot) const { OC_ASSERT(ot.size() == size() && size() > 0); return sum_squared_error(ot) / ot.size(); } contin_t OTable::root_mean_square_error(const OTable& ot) const { OC_ASSERT(ot.size() == size() && size() > 0); return sqrt(mean_squared_error(ot)); } // ------------------------------------------------------- Table::Table() {} Table::Table(const OTable& otable_, const ITable& itable_, const type_tree& tt_) : tt(tt_), itable(itable_), otable(otable_) {} Table::Table(const combo_tree& tr, int nsamples, contin_t min_contin, contin_t max_contin) : tt(infer_type_tree(tr)), itable(tt, nsamples, min_contin, max_contin), otable(tr, itable) {} vector<string> Table::get_labels() const { vector<string> labels = itable.get_labels(); labels.insert(labels.begin(), otable.get_label()); return labels; } CTable Table::compressed() const { // Logger logger().debug("Compress the dataset, current size is %d", itable.size()); // ~Logger CTable res(otable.get_label(), itable.get_labels()); // assign type_tree res.tt = tt; ITable::const_iterator in_it = itable.begin(); OTable::const_iterator out_it = otable.begin(); for(; in_it != itable.end(); ++in_it, ++out_it) ++res[*in_it][*out_it]; // Logger logger().debug("Size of the compressed dataset is %d", res.size()); // ~Logger return res; } // ------------------------------------------------------- vector<string> CTable::get_labels() const { vector<string> labels = ilabels; labels.insert(labels.begin(), olabel); return labels; } // ------------------------------------------------------- complete_truth_table::size_type complete_truth_table::hamming_distance(const complete_truth_table& other) const { OC_ASSERT(other.size() == size(), "complete_truth_tables size should be the same."); size_type res = 0; for (const_iterator x = begin(), y = other.begin();x != end();) res += (*x++ != *y++); return res; } bool complete_truth_table::same_complete_truth_table(const combo_tree& tr) const { const_iterator cit = begin(); for (int i = 0; cit != end(); ++i, ++cit) { for (int j = 0; j < _arity; ++j) bmap[j] = bool_to_vertex((i >> j) % 2); if (*cit != vertex_to_bool(eval_binding(bmap, tr))) return false; } return true; } // ------------------------------------------------------- double OTEntropy(const OTable& ot) { // Compute the probability distributions Counter<vertex, unsigned> counter(ot); vector<double> py(counter.size()); double total = ot.size(); transform(counter | map_values, py.begin(), [&](unsigned c) { return c/total; }); // Compute the entropy return entropy(py); } }} // ~namespaces combo opencog <commit_msg>combo table: bugfix in another recently mangled routine.<commit_after>/** table.cc --- * * Copyright (C) 2010 OpenCog Foundation * * Author: Nil Geisweiller <ngeiswei@gmail.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * This program 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 Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "table.h" #include <iomanip> #include <boost/range/algorithm/for_each.hpp> #include <boost/range/algorithm/transform.hpp> #include <opencog/util/dorepeat.h> #include <opencog/util/Logger.h> #include "ann.h" #include "simple_nn.h" #include "convert_ann_combo.h" namespace opencog { namespace combo { using namespace std; using namespace boost; using namespace boost::adaptors; // ------------------------------------------------------- ITable::ITable() {} ITable::ITable(const ITable::super& mat, vector<string> il) : super(mat), labels(il) {} ITable::ITable(const type_tree& tt, int nsamples, contin_t min_contin, contin_t max_contin) { arity_t barity = boolean_arity(tt), carity = contin_arity(tt); if (nsamples < 0) nsamples = std::max(pow2(barity), sample_count(carity)); // in that case the boolean inputs are not picked randomly but // instead are enumerated bool comp_tt = nsamples == (int)pow2(barity); // Populate the matrix. auto root = tt.begin(); for (int i = 0; i < nsamples; ++i) { size_t bidx = 0; // counter used to enumerate all // booleans vertex_seq vs; foreach (type_node n, make_pair(root.begin(), root.last_child())) if (n == id::boolean_type) vs.push_back(bool_to_vertex(comp_tt? i & (1 << bidx++) : randGen().randint(2))); else if (n == id::contin_type) vs.push_back((max_contin - min_contin) * randGen().randdouble() + min_contin); else if (n == id::enum_type) vs.push_back(enum_t::get_random_enum()); else if (n == id::unknown_type) vs.push_back(vertex()); // push default vertex else OC_ASSERT(false, "Not implemented yet"); // input vector push_back(vs); } } // ------------------------------------------------------- void ITable::set_labels(const vector<string>& il) { labels = il; } static const std::string default_input_label("i"); vector<string> ITable::get_default_labels() const { string_seq res; for (arity_t i = 1; i <= get_arity(); ++i) res.push_back(default_input_label + boost::lexical_cast<std::string>(i)); return res; } const vector<string>& ITable::get_labels() const { if (labels.empty() and !super::empty()) // return default labels labels = get_default_labels(); return labels; } void ITable::set_types(const vector<type_node>& il) { types = il; } const vector<type_node>& ITable::get_types() const { if (types.empty() and !super::empty()) { arity_t arity = get_arity(); types.resize(arity); for (arity_t i=0; i<arity; i++) { types[i] = id::unknown_type; } } return types; } // ------------------------------------------------------- void ITable::insert_col(const std::string& clab, const vertex_seq& col, int off) { // insert label labels.insert(off >= 0 ? labels.begin() + off : labels.end(), clab); // insert values if (empty()) { OC_ASSERT(off < 0); foreach (const auto& v, col) push_back({v}); return; } OC_ASSERT (col.size() == size(), "Incorrect column length!"); for (unsigned i = 0; i < col.size(); i++) { auto& row = (*this)[i]; row.insert(off >= 0 ? row.begin() + off : row.end(), col[i]); } } vector<vertex> ITable::get_column_data(const std::string& name) const { vector<vertex> col; // If the name is empty, get column zero. size_t off = 0; if (!name.empty()) { auto pos = std::find(labels.begin(), labels.end(), name); if (pos == labels.end()) return col; off = distance(labels.begin(), pos); } foreach (const auto& row, *this) col.push_back(row[off]); return col; } void ITable::delete_column(const string& name) { // If the name is empty, get column zero. size_t off = 0; if (!name.empty()) { auto pos = std::find(labels.begin(), labels.end(), name); if (pos == labels.end()) return; off = distance(labels.begin(), pos); } // Delete the column foreach (vertex_seq& row, *this) row.erase(row.begin() + off); // Delete the label as well. if (!labels.empty()) labels.erase(labels.begin() + off); if (!types.empty()) types.erase(types.begin() + off); } void ITable::delete_columns(const vector<string>& ignore_features) { foreach(const string& feat, ignore_features) delete_column(feat); } // ------------------------------------------------------- OTable::OTable(const string& ol) : label(ol) {} OTable::OTable(const super& ot, const string& ol) : super(ot), label(ol) {} OTable::OTable(const combo_tree& tr, const ITable& itable, const string& ol) : label(ol) { OC_ASSERT(!tr.empty()); if (is_ann_type(*tr.begin())) { // we treat ANN differently because they must be decoded // before being evaluated. Also note that if there are memory // neurones then the state of the network is evolving at each // input, so the order within itable does matter ann net = tree_transform().decodify_tree(tr); int depth = net.feedforward_depth(); foreach(const vertex_seq& vv, itable) { vector<contin_t> tmp(vv.size()); transform(vv, tmp.begin(), get_contin); tmp.push_back(1.0); // net uses that in case the function // to learn needs some kind of offset net.load_inputs(tmp); dorepeat(depth) net.propagate(); push_back(net.outputs[0]->activation); } } else { foreach(const vertex_seq& vs, itable) push_back(eval_throws_binding(vs, tr)); } } OTable::OTable(const combo_tree& tr, const CTable& ctable, const string& ol) : label(ol) { arity_set as = get_argument_abs_idx_set(tr); for_each(ctable | map_keys, [&](const vertex_seq& vs) { this->push_back(eval_throws_binding(vs, tr)); }); } void OTable::set_label(const string& ol) { if (ol.empty()) label = default_output_label; else label = ol; } const string& OTable::get_label() const { return label; } // ------------------------------------------------------- bool OTable::operator==(const OTable& rhs) const { const static contin_t epsilon = 1e-12; for(auto lit = begin(), rit = rhs.begin(); lit != end(); ++lit, ++rit) { if(is_contin(*lit) && is_contin(*rit)) { if(!isApproxEq(get_contin(*lit), get_contin(*rit), epsilon)) return false; } else if(*lit != *rit) return false; } return rhs.get_label() == label; } contin_t OTable::abs_distance(const OTable& ot) const { OC_ASSERT(ot.size() == size()); contin_t res = 0; for(const_iterator x = begin(), y = ot.begin(); x != end();) res += fabs(get_contin(*(x++)) - get_contin(*(y++))); return res; } contin_t OTable::sum_squared_error(const OTable& ot) const { OC_ASSERT(ot.size() == size()); contin_t res = 0; for(const_iterator x = begin(), y = ot.begin(); x != end();) res += sq(get_contin(*(x++)) - get_contin(*(y++))); return res; } contin_t OTable::mean_squared_error(const OTable& ot) const { OC_ASSERT(ot.size() == size() && size() > 0); return sum_squared_error(ot) / ot.size(); } contin_t OTable::root_mean_square_error(const OTable& ot) const { OC_ASSERT(ot.size() == size() && size() > 0); return sqrt(mean_squared_error(ot)); } // ------------------------------------------------------- Table::Table() {} Table::Table(const OTable& otable_, const ITable& itable_, const type_tree& tt_) : tt(tt_), itable(itable_), otable(otable_) {} Table::Table(const combo_tree& tr, int nsamples, contin_t min_contin, contin_t max_contin) : tt(infer_type_tree(tr)), itable(tt, nsamples, min_contin, max_contin), otable(tr, itable) {} vector<string> Table::get_labels() const { vector<string> labels = itable.get_labels(); labels.insert(labels.begin(), otable.get_label()); return labels; } CTable Table::compressed() const { // Logger logger().debug("Compress the dataset, current size is %d", itable.size()); // ~Logger CTable res(otable.get_label(), itable.get_labels()); // assign type_tree res.tt = tt; ITable::const_iterator in_it = itable.begin(); OTable::const_iterator out_it = otable.begin(); for(; in_it != itable.end(); ++in_it, ++out_it) ++res[*in_it][*out_it]; // Logger logger().debug("Size of the compressed dataset is %d", res.size()); // ~Logger return res; } // ------------------------------------------------------- vector<string> CTable::get_labels() const { vector<string> labels = ilabels; labels.insert(labels.begin(), olabel); return labels; } // ------------------------------------------------------- complete_truth_table::size_type complete_truth_table::hamming_distance(const complete_truth_table& other) const { OC_ASSERT(other.size() == size(), "complete_truth_tables size should be the same."); size_type res = 0; for (const_iterator x = begin(), y = other.begin();x != end();) res += (*x++ != *y++); return res; } bool complete_truth_table::same_complete_truth_table(const combo_tree& tr) const { const_iterator cit = begin(); for (int i = 0; cit != end(); ++i, ++cit) { for (int j = 0; j < _arity; ++j) bmap[j] = bool_to_vertex((i >> j) % 2); if (*cit != vertex_to_bool(eval_binding(bmap, tr))) return false; } return true; } // ------------------------------------------------------- double OTEntropy(const OTable& ot) { // Compute the probability distributions Counter<vertex, unsigned> counter(ot); vector<double> py(counter.size()); double total = ot.size(); transform(counter | map_values, py.begin(), [&](unsigned c) { return c/total; }); // Compute the entropy return entropy(py); } }} // ~namespaces combo opencog <|endoftext|>
<commit_before> #include "ksp_plugin/vessel.hpp" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "physics/mock_ephemeris.hpp" namespace principia { using physics::MockEphemeris; using quantities::si::Kilogram; using quantities::si::Metre; using quantities::si::Second; namespace ksp_plugin { // TODO(egg): We would want to use a real ephemeris to properly exercise the // limit cases. class VesselTest : public testing::Test { protected: VesselTest() : body_(1 * Kilogram), parent_(&body_), adaptive_parameters_( DormandElMikkawyPrince1986RKN434FM<Position<Barycentric>>(), /*max_steps=*/1, /*length_integration_tolerance=*/1 * Metre, /*speed_integration_tolerance=*/1 * Metre / Second), fixed_parameters_( McLachlanAtela1992Order5Optimal<Position<Barycentric>>(), /*step=*/1 * Second), vessel_(make_not_null_unique<Vessel>(&parent_, &ephemeris_, adaptive_parameters_, fixed_parameters_)) {} MassiveBody body_; Celestial parent_; MockEphemeris<Barycentric> ephemeris_; Ephemeris<Barycentric>::AdaptiveStepParameters const adaptive_parameters_; Ephemeris<Barycentric>::FixedStepParameters const fixed_parameters_; not_null<std::unique_ptr<Vessel>> vessel_; DegreesOfFreedom<Barycentric> d1_ = {Barycentric::origin + Displacement<Barycentric>({1 * Metre, 2 * Metre, 3 * Metre}), Velocity<Barycentric>({4 * Metre / Second, 5 * Metre / Second, 6 * Metre / Second})}; DegreesOfFreedom<Barycentric> d2_ = {Barycentric::origin + Displacement<Barycentric>({11 * Metre, 12 * Metre, 13 * Metre}), Velocity<Barycentric>({14 * Metre / Second, 15 * Metre / Second, 16 * Metre / Second})}; Instant const t1_ = kUniversalTimeEpoch; Instant const t2_ = kUniversalTimeEpoch + 42.3 * Second; }; using VesselDeathTest = VesselTest; TEST_F(VesselDeathTest, Uninitialized) { EXPECT_DEATH({ vessel_->history(); }, "is_initialized"); EXPECT_DEATH({ vessel_->prolongation(); }, "is_initialized"); } TEST_F(VesselTest, Initialization) { EXPECT_FALSE(vessel_->is_initialized()); vessel_->CreateHistoryAndForkProlongation(t2_, d2_); EXPECT_TRUE(vessel_->is_initialized()); auto const& prolongation = vessel_->prolongation(); EXPECT_EQ(t2_, prolongation.last().time()); auto const& history = vessel_->history(); EXPECT_EQ(t2_, history.last().time()); EXPECT_FALSE(vessel_->has_flight_plan()); EXPECT_FALSE(vessel_->has_prediction()); } TEST_F(VesselTest, Dirty) { EXPECT_FALSE(vessel_->is_dirty()); vessel_->set_dirty(); EXPECT_TRUE(vessel_->is_dirty()); } TEST_F(VesselTest, Parent) { MassiveBody body(2 * Kilogram); Celestial celestial(&body); EXPECT_EQ(&parent_, vessel_->parent()); vessel_->set_parent(&celestial); EXPECT_EQ(&celestial, vessel_->parent()); } TEST_F(VesselTest, AdvanceTime) { vessel_->CreateHistoryAndForkProlongation(t1_, d1_); vessel_->AdvanceTimeNotInBubble(t2_); EXPECT_EQ(kUniversalTimeEpoch + 42 * Second, vessel_->history().last().time()); EXPECT_EQ(t2_, vessel_->prolongation().last().time()); } TEST_F(VesselDeathTest, SerializationError) { EXPECT_DEATH({ serialization::Vessel message; vessel_->WriteToMessage(&message); }, "is_initialized"); EXPECT_DEATH({ serialization::Vessel message; Vessel::ReadFromMessage(message, &ephemeris_, &parent_); }, "message.has_history"); } TEST_F(VesselTest, SerializationSuccess) { serialization::Vessel message; EXPECT_FALSE(message.has_history()); vessel_->CreateHistoryAndForkProlongation(t2_, d2_); vessel_->WriteToMessage(&message); EXPECT_TRUE(message.has_history()); vessel_ = Vessel::ReadFromMessage(message, &ephemeris_, &parent_); EXPECT_TRUE(vessel_->is_initialized()); } } // namespace ksp_plugin } // namespace principia <commit_msg>Try to use a solar system.<commit_after> #include "ksp_plugin/vessel.hpp" #include "astronomy/frames.hpp" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "physics/ephemeris.hpp" #include "physics/solar_system.hpp" namespace principia { using astronomy::ICRFJ2000Equator; using physics::Ephemeris; using physics::SolarSystem; using quantities::si::Kilogram; using quantities::si::Metre; using quantities::si::Second; namespace ksp_plugin { // TODO(egg): We would want to use a real ephemeris to properly exercise the // limit cases. class VesselTest : public testing::Test { protected: VesselTest() : adaptive_parameters_( DormandElMikkawyPrince1986RKN434FM<Position<ICRFJ2000Equator>>(), /*max_steps=*/1, /*length_integration_tolerance=*/1 * Metre, /*speed_integration_tolerance=*/1 * Metre / Second), ephemeris_fixed_parameters_( McLachlanAtela1992Order5Optimal<Position<ICRFJ2000Equator>>(), /*step=*/10 * Second), history_fixed_parameters_( McLachlanAtela1992Order5Optimal<Position<ICRFJ2000Equator>>(), /*step=*/1 * Second) { solar_system_.Initialize( SOLUTION_DIR / "astronomy" / "gravity_model.proto.txt", SOLUTION_DIR / "astronomy" / "initial_state_jd_2433282_500000000.proto.txt"); t0_ = solar_system_.epoch(); ephemeris_ = solar_system_.MakeEphemeris( /*fitting_tolerance=*/1 * Milli(Metre), ephemeris_fixed_parameters_); vessel_ = std::make_unique<Vessel>( solar_system_.massive_body(*ephemeris_, "Earth"), &ephemeris_, adaptive_parameters_, history_fixed_parameters_); } SolarSystem<ICRFJ2000Equator> solar_system_; std::unique_ptr<Ephemeris<ICRFJ2000Equator>> ephemeris_; Ephemeris<ICRFJ2000Equator>::AdaptiveStepParameters const adaptive_parameters_; Ephemeris<ICRFJ2000Equator>::FixedStepParameters const ephemeris_fixed_parameters_; Ephemeris<ICRFJ2000Equator>::FixedStepParameters const history_fixed_parameters_; std::unique_ptr<Vessel> vessel_; DegreesOfFreedom<ICRFJ2000Equator> d1_ = { ICRFJ2000Equator::origin + Displacement<ICRFJ2000Equator>({1 * Metre, 2 * Metre, 3 * Metre}), Velocity<ICRFJ2000Equator>( {4 * Metre / Second, 5 * Metre / Second, 6 * Metre / Second})}; DegreesOfFreedom<ICRFJ2000Equator> d2_ = { ICRFJ2000Equator::origin + Displacement<ICRFJ2000Equator>({11 * Metre, 12 * Metre, 13 * Metre}), Velocity<ICRFJ2000Equator>( {14 * Metre / Second, 15 * Metre / Second, 16 * Metre / Second})}; Instant t0_; Instant const t1_ = kUniversalTimeEpoch; Instant const t2_ = kUniversalTimeEpoch + 42.3 * Second; }; using VesselDeathTest = VesselTest; TEST_F(VesselDeathTest, Uninitialized) { EXPECT_DEATH({ vessel_->history(); }, "is_initialized"); EXPECT_DEATH({ vessel_->prolongation(); }, "is_initialized"); } TEST_F(VesselTest, Initialization) { EXPECT_FALSE(vessel_->is_initialized()); vessel_->CreateHistoryAndForkProlongation(t2_, d2_); EXPECT_TRUE(vessel_->is_initialized()); auto const& prolongation = vessel_->prolongation(); EXPECT_EQ(t2_, prolongation.last().time()); auto const& history = vessel_->history(); EXPECT_EQ(t2_, history.last().time()); EXPECT_FALSE(vessel_->has_flight_plan()); EXPECT_FALSE(vessel_->has_prediction()); } TEST_F(VesselTest, Dirty) { EXPECT_FALSE(vessel_->is_dirty()); vessel_->set_dirty(); EXPECT_TRUE(vessel_->is_dirty()); } TEST_F(VesselTest, Parent) { MassiveBody body(2 * Kilogram); Celestial celestial(&body); EXPECT_EQ(&parent_, vessel_->parent()); vessel_->set_parent(&celestial); EXPECT_EQ(&celestial, vessel_->parent()); } TEST_F(VesselTest, AdvanceTime) { vessel_->CreateHistoryAndForkProlongation(t1_, d1_); vessel_->AdvanceTimeNotInBubble(t2_); EXPECT_EQ(kUniversalTimeEpoch + 42 * Second, vessel_->history().last().time()); EXPECT_EQ(t2_, vessel_->prolongation().last().time()); } TEST_F(VesselDeathTest, SerializationError) { EXPECT_DEATH({ serialization::Vessel message; vessel_->WriteToMessage(&message); }, "is_initialized"); EXPECT_DEATH({ serialization::Vessel message; Vessel::ReadFromMessage(message, &ephemeris_, &parent_); }, "message.has_history"); } TEST_F(VesselTest, SerializationSuccess) { serialization::Vessel message; EXPECT_FALSE(message.has_history()); vessel_->CreateHistoryAndForkProlongation(t2_, d2_); vessel_->WriteToMessage(&message); EXPECT_TRUE(message.has_history()); vessel_ = Vessel::ReadFromMessage(message, &ephemeris_, &parent_); EXPECT_TRUE(vessel_->is_initialized()); } } // namespace ksp_plugin } // namespace principia <|endoftext|>
<commit_before>#include "googledataresource.h" #include "settings.h" #include "settingsadaptor.h" #include <QtDBus/QDBusConnection> #include <kabc/addressee.h> #include <kabc/phonenumber.h> #include <kabc/key.h> #include <kabc/errorhandler.h> #include <qstring.h> #include <KWindowSystem> #include <akonadi/changerecorder.h> #include <akonadi/itemfetchscope.h> #include <KUrl> extern "C" { #include <gcalendar.h> #include <gcontact.h> #include <gcal_status.h> } /** FIXME: for some reason the 'retrieveItem' functions is not being called. * this makes the entries to lack its contents (name, email, etc). * I should investigate why and fix, for while this is a workaround: * I report the payload in the 'retrieveItems' function. */ #define ITEM_BUG_WTF using namespace Akonadi; GoogleDataResource::GoogleDataResource( const QString &id ) : ResourceBase(id), dlgConf(0), authenticated(false) { new SettingsAdaptor( Settings::self() ); QDBusConnection::sessionBus().registerObject( QLatin1String( "/Settings" ), Settings::self(), QDBusConnection::ExportAdaptors ); changeRecorder()->itemFetchScope().fetchFullPayload(); if (!(gcal = gcal_new(GCONTACT))) exit(1); gcal_set_store_xml(gcal, 1); all_contacts.length = 0; all_contacts.entries = NULL; } GoogleDataResource::~GoogleDataResource() { gcal_delete(gcal); gcal_cleanup_contacts(&all_contacts); if (dlgConf) delete dlgConf; } void GoogleDataResource::retrieveCollections() { if (!authenticated) { kError() << "No authentication for Google Contacts available"; const QString message = i18nc("@info:status", "Not yet authenticated for" " use of Google Contacts"); emit error(message); emit status(Broken, message); return; } Collection c; c.setParent(Collection::root()); c.setRemoteId("google-contacts"); c.setName(name()); QStringList mimeTypes; mimeTypes << "text/directory"; c.setContentMimeTypes(mimeTypes); Collection::List list; list << c; collectionsRetrieved(list); } void GoogleDataResource::retrieveItems( const Akonadi::Collection &collection ) { Q_UNUSED( collection ); Item::List items; int result; if (!authenticated) { kError() << "No authentication for Google Contacts available"; const QString message = i18nc("@info:status", "Not yet authenticated for" " use of Google Contacts"); emit error(message); emit status(Broken, message); return; } /* Downloading the contacts can be slow and it is blocking. Will * it mess up with akonadi? */ if ((result = gcal_get_contacts(gcal, &all_contacts))) exit(1); /* Each google entry has a unique ID and edit_url */ for (size_t i = 0; i < all_contacts.length; ++i) { Item item(QLatin1String("text/directory")); gcal_contact_t contact = gcal_contact_element(&all_contacts, i); #ifdef ITEM_BUG_WTF KABC::Addressee addressee; KABC::PhoneNumber number; QString temp; /* name */ temp = gcal_contact_get_title(contact); addressee.setNameFromString(temp); /* email */ temp = gcal_contact_get_email(contact); addressee.insertEmail(temp, true); /* TODO: telefone, address, etc */ item.setPayload<KABC::Addressee>(addressee); /* remoteID: etag+edit_url */ KUrl urlEtag(gcal_contact_get_url(contact)); urlEtag.addQueryItem("etag", gcal_contact_get_etag(contact)); #endif item.setRemoteId(urlEtag.url()); items << item; } itemsRetrieved(items); } bool GoogleDataResource::retrieveItem( const Akonadi::Item &item, const QSet<QByteArray> &parts ) { Q_UNUSED( parts ); const QString entry_id = item.remoteId(); QString temp; Item newItem(item); gcal_contact_t contact; KABC::Addressee addressee; KABC::PhoneNumber number; if (!authenticated) { kError() << "No authentication for Google Contacts available"; const QString message = i18nc("@info:status", "Not yet authenticated for" " use of Google Contacts"); emit error(message); emit status(Broken, message); return false; } /* * And another question, are the requests in the same sequence that * I informed in 'retrieveItems'? For while, I try to locate the entry... */ for (size_t i = 0; i < all_contacts.length; ++i) { contact = gcal_contact_element(&all_contacts, i); if (entry_id == gcal_contact_get_id(contact)) { /* name */ temp = gcal_contact_get_title(contact); addressee.setNameFromString(temp); /* email */ temp = gcal_contact_get_email(contact); addressee.insertEmail(temp, true); /* TODO: telefone, address, etc */ /* remoteID: etag+edit_url */ KUrl urlEtag(gcal_contact_get_url(contact)); urlEtag.addQueryItem("etag", gcal_contact_get_etag(contact)); newItem.setPayload<KABC::Addressee>(addressee); newItem.setRemoteId(urlEtag.url()); itemRetrieved(newItem); return true; } } return false; } void GoogleDataResource::aboutToQuit() { // TODO: any cleanup you need to do while there is still an active // event loop. The resource will terminate after this method returns } void GoogleDataResource::configure( WId windowId ) { Q_UNUSED( windowId ); char *user, *pass; int result = -1; QByteArray byteUser, bytePass; if (!dlgConf) dlgConf = new dlgGoogleDataConf; if (windowId && dlgConf) KWindowSystem::setMainWindow(dlgConf, windowId); dlgConf->exec(); byteUser = dlgConf->eAccount->text().toLocal8Bit(); bytePass = dlgConf->ePass->text().toLocal8Bit(); user = const_cast<char *>(byteUser.constData()); pass = const_cast<char *>(bytePass.constData()); if (user) if (pass) result = gcal_get_authentication(gcal, user, pass); /* TODO: in case of authentication error, display an error * message. */ if (!result) authenticated = true; synchronize(); } void GoogleDataResource::itemAdded( const Akonadi::Item &item, const Akonadi::Collection &collection ) { Q_UNUSED(collection); KABC::Addressee addressee; gcal_contact_t contact; QString temp; QByteArray t_byte; Item newItem; int result; if (!authenticated) { kError() << "No authentication for Google Contacts available"; const QString message = i18nc("@info:status", "Not yet authenticated for" " use of Google Contacts"); emit error(message); emit status(Broken, message); return; } if (item.hasPayload<KABC::Addressee>()) addressee = item.payload<KABC::Addressee>(); if (!(contact = gcal_contact_new(NULL))) exit(1); temp = addressee.realName(); t_byte = temp.toLocal8Bit(); gcal_contact_set_title(contact, const_cast<char *>(t_byte.constData())); temp = addressee.fullEmail(); t_byte = temp.toLocal8Bit(); gcal_contact_set_email(contact, const_cast<char *>(t_byte.constData())); /* TODO: add remaining fields */ if ((result = gcal_add_contact(gcal, contact))) { kError() << "Failed adding new contact" << "name: " << addressee.realName() << "email: " << addressee.fullEmail(); const QString message = i18nc("@info:status", "Failed adding new contact"); emit error(message); emit status(Broken, message); } /* remoteID: etag+edit_url */ KUrl urlEtag(gcal_contact_get_url(contact)); urlEtag.addQueryItem("etag", gcal_contact_get_etag(contact)); //FIXME: this guy is const... how to supply the etag/url? //item.setRemoteId(urlEtag.url()); /* cleanup */ gcal_contact_delete(contact); } void GoogleDataResource::itemChanged( const Akonadi::Item &item, const QSet<QByteArray> &parts ) { Q_UNUSED(parts); KABC::Addressee addressee; gcal_contact_t contact; QByteArray t_byte; QString temp; int result; if (!authenticated) { kError() << "No authentication for Google Contacts available"; const QString message = i18nc("@info:status", "Not yet authenticated for" " use of Google Contacts"); emit error(message); emit status(Broken, message); return; } if (item.hasPayload<KABC::Addressee>()) addressee = item.payload<KABC::Addressee>(); if (!(contact = gcal_contact_new(NULL))) exit(1); temp = addressee.realName(); t_byte = temp.toLocal8Bit(); gcal_contact_set_title(contact, const_cast<char *>(t_byte.constData())); temp = addressee.fullEmail(); t_byte = temp.toLocal8Bit(); gcal_contact_set_email(contact, const_cast<char *>(t_byte.constData())); /* TODO: add remaining fields */ KUrl url(item.remoteId()); temp = url.queryItem("etag"); t_byte = temp.toAscii(); gcal_contact_set_etag(contact, const_cast<char *>(t_byte.constData())); url.removeQueryItem("etag"); temp = url.url(); t_byte = temp.toAscii(); gcal_contact_set_url(contact, const_cast<char *>(t_byte.constData())); if ((result = gcal_update_contact(gcal, contact))) { kError() << "Failed editing contact"; const QString message = i18nc("@info:status", "Failed editing new contact"); emit error(message); emit status(Broken, message); } /* remoteID: etag+edit_url */ KUrl urlEtag(gcal_contact_get_url(contact)); urlEtag.addQueryItem("etag", gcal_contact_get_etag(contact)); //FIXME: this guy is const... how to supply the etag/url? //item.setRemoteId(urlEtag.url()); gcal_contact_delete(contact); } void GoogleDataResource::itemRemoved( const Akonadi::Item &item ) { KABC::Addressee addressee; gcal_contact_t contact; QString temp; QByteArray t_byte; int result; if (!authenticated) { kError() << "No authentication for Google Contacts available"; const QString message = i18nc("@info:status", "Not yet authenticated for" " use of Google Contacts"); emit error(message); emit status(Broken, message); return; } if (!(contact = gcal_contact_new(NULL))) { kError() << "Memory allocation error!"; const QString message = i18nc("@info:status", "Failed to create gcal_contact"); emit error(message); emit status(Broken, message); return; } KUrl url(item.remoteId()); temp = url.queryItem("etag"); t_byte = temp.toAscii(); gcal_contact_set_etag(contact, const_cast<char *>(t_byte.constData())); url.removeQueryItem("etag"); temp = url.url(); t_byte = temp.toAscii(); gcal_contact_set_url(contact, const_cast<char *>(t_byte.constData())); if ((result = gcal_erase_contact(gcal, contact))) { kError() << "Failed deleting contact"; const QString message = i18nc("@info:status", "Failed deleting new contact"); emit error(message); emit status(Broken, message); } gcal_contact_delete(contact); } AKONADI_RESOURCE_MAIN( GoogleDataResource ) #include "googledataresource.moc" <commit_msg>Better error handling.<commit_after>#include "googledataresource.h" #include "settings.h" #include "settingsadaptor.h" #include <QtDBus/QDBusConnection> #include <kabc/addressee.h> #include <kabc/phonenumber.h> #include <kabc/key.h> #include <kabc/errorhandler.h> #include <qstring.h> #include <KWindowSystem> #include <akonadi/changerecorder.h> #include <akonadi/itemfetchscope.h> #include <KUrl> extern "C" { #include <gcalendar.h> #include <gcontact.h> #include <gcal_status.h> } /** FIXME: for some reason the 'retrieveItem' functions is not being called. * this makes the entries to lack its contents (name, email, etc). * I should investigate why and fix, for while this is a workaround: * I report the payload in the 'retrieveItems' function. */ #define ITEM_BUG_WTF using namespace Akonadi; GoogleDataResource::GoogleDataResource( const QString &id ) : ResourceBase(id), dlgConf(0), authenticated(false) { new SettingsAdaptor( Settings::self() ); QDBusConnection::sessionBus().registerObject( QLatin1String( "/Settings" ), Settings::self(), QDBusConnection::ExportAdaptors ); changeRecorder()->itemFetchScope().fetchFullPayload(); if (!(gcal = gcal_new(GCONTACT))) exit(1); gcal_set_store_xml(gcal, 1); all_contacts.length = 0; all_contacts.entries = NULL; } GoogleDataResource::~GoogleDataResource() { gcal_delete(gcal); gcal_cleanup_contacts(&all_contacts); if (dlgConf) delete dlgConf; } void GoogleDataResource::retrieveCollections() { if (!authenticated) { kError() << "No authentication for Google Contacts available"; const QString message = i18nc("@info:status", "Not yet authenticated for" " use of Google Contacts"); emit error(message); emit status(Broken, message); return; } Collection c; c.setParent(Collection::root()); c.setRemoteId("google-contacts"); c.setName(name()); QStringList mimeTypes; mimeTypes << "text/directory"; c.setContentMimeTypes(mimeTypes); Collection::List list; list << c; collectionsRetrieved(list); } void GoogleDataResource::retrieveItems( const Akonadi::Collection &collection ) { Q_UNUSED( collection ); Item::List items; int result; if (!authenticated) { kError() << "No authentication for Google Contacts available"; const QString message = i18nc("@info:status", "Not yet authenticated for" " use of Google Contacts"); emit error(message); emit status(Broken, message); return; } /* Downloading the contacts can be slow and it is blocking. Will * it mess up with akonadi? */ if ((result = gcal_get_contacts(gcal, &all_contacts))) exit(1); /* Each google entry has a unique ID and edit_url */ for (size_t i = 0; i < all_contacts.length; ++i) { Item item(QLatin1String("text/directory")); gcal_contact_t contact = gcal_contact_element(&all_contacts, i); #ifdef ITEM_BUG_WTF KABC::Addressee addressee; KABC::PhoneNumber number; QString temp; /* name */ temp = gcal_contact_get_title(contact); addressee.setNameFromString(temp); /* email */ temp = gcal_contact_get_email(contact); addressee.insertEmail(temp, true); /* TODO: telefone, address, etc */ item.setPayload<KABC::Addressee>(addressee); /* remoteID: etag+edit_url */ KUrl urlEtag(gcal_contact_get_url(contact)); urlEtag.addQueryItem("etag", gcal_contact_get_etag(contact)); #endif item.setRemoteId(urlEtag.url()); items << item; } itemsRetrieved(items); } bool GoogleDataResource::retrieveItem( const Akonadi::Item &item, const QSet<QByteArray> &parts ) { Q_UNUSED( parts ); const QString entry_id = item.remoteId(); QString temp; Item newItem(item); gcal_contact_t contact; KABC::Addressee addressee; KABC::PhoneNumber number; if (!authenticated) { kError() << "No authentication for Google Contacts available"; const QString message = i18nc("@info:status", "Not yet authenticated for" " use of Google Contacts"); emit error(message); emit status(Broken, message); return false; } /* * And another question, are the requests in the same sequence that * I informed in 'retrieveItems'? For while, I try to locate the entry... */ for (size_t i = 0; i < all_contacts.length; ++i) { contact = gcal_contact_element(&all_contacts, i); if (entry_id == gcal_contact_get_id(contact)) { /* name */ temp = gcal_contact_get_title(contact); addressee.setNameFromString(temp); /* email */ temp = gcal_contact_get_email(contact); addressee.insertEmail(temp, true); /* TODO: telefone, address, etc */ /* remoteID: etag+edit_url */ KUrl urlEtag(gcal_contact_get_url(contact)); urlEtag.addQueryItem("etag", gcal_contact_get_etag(contact)); newItem.setPayload<KABC::Addressee>(addressee); newItem.setRemoteId(urlEtag.url()); itemRetrieved(newItem); return true; } } return false; } void GoogleDataResource::aboutToQuit() { // TODO: any cleanup you need to do while there is still an active // event loop. The resource will terminate after this method returns } void GoogleDataResource::configure( WId windowId ) { Q_UNUSED( windowId ); char *user, *pass; int result = -1; QByteArray byteUser, bytePass; if (!dlgConf) dlgConf = new dlgGoogleDataConf; if (windowId && dlgConf) KWindowSystem::setMainWindow(dlgConf, windowId); dlgConf->exec(); byteUser = dlgConf->eAccount->text().toLocal8Bit(); bytePass = dlgConf->ePass->text().toLocal8Bit(); user = const_cast<char *>(byteUser.constData()); pass = const_cast<char *>(bytePass.constData()); if (user) if (pass) result = gcal_get_authentication(gcal, user, pass); /* TODO: in case of authentication error, display an error * message. */ if (!result) authenticated = true; synchronize(); } void GoogleDataResource::itemAdded( const Akonadi::Item &item, const Akonadi::Collection &collection ) { Q_UNUSED(collection); KABC::Addressee addressee; gcal_contact_t contact; QString temp; QByteArray t_byte; Item newItem; int result; if (!authenticated) { kError() << "No authentication for Google Contacts available"; const QString message = i18nc("@info:status", "Not yet authenticated for" " use of Google Contacts"); emit error(message); emit status(Broken, message); return; } if (item.hasPayload<KABC::Addressee>()) addressee = item.payload<KABC::Addressee>(); if (!(contact = gcal_contact_new(NULL))) exit(1); temp = addressee.realName(); t_byte = temp.toLocal8Bit(); gcal_contact_set_title(contact, const_cast<char *>(t_byte.constData())); temp = addressee.fullEmail(); t_byte = temp.toLocal8Bit(); gcal_contact_set_email(contact, const_cast<char *>(t_byte.constData())); /* TODO: add remaining fields */ if ((result = gcal_add_contact(gcal, contact))) { kError() << "Failed adding new contact" << "name: " << addressee.realName() << "email: " << addressee.fullEmail(); const QString message = i18nc("@info:status", "Failed adding new contact"); emit error(message); emit status(Broken, message); } /* remoteID: etag+edit_url */ KUrl urlEtag(gcal_contact_get_url(contact)); urlEtag.addQueryItem("etag", gcal_contact_get_etag(contact)); //FIXME: this guy is const... how to supply the etag/url? //item.setRemoteId(urlEtag.url()); /* cleanup */ gcal_contact_delete(contact); } void GoogleDataResource::itemChanged( const Akonadi::Item &item, const QSet<QByteArray> &parts ) { Q_UNUSED(parts); KABC::Addressee addressee; gcal_contact_t contact; QByteArray t_byte; QString temp; int result; if (!authenticated) { kError() << "No authentication for Google Contacts available"; const QString message = i18nc("@info:status", "Not yet authenticated for" " use of Google Contacts"); emit error(message); emit status(Broken, message); return; } if (item.hasPayload<KABC::Addressee>()) addressee = item.payload<KABC::Addressee>(); if (!(contact = gcal_contact_new(NULL))) { kError() << "Memory allocation error!"; const QString message = i18nc("@info:status", "Failed to create gcal_contact"); emit error(message); emit status(Broken, message); return; } temp = addressee.realName(); t_byte = temp.toLocal8Bit(); gcal_contact_set_title(contact, const_cast<char *>(t_byte.constData())); temp = addressee.fullEmail(); t_byte = temp.toLocal8Bit(); gcal_contact_set_email(contact, const_cast<char *>(t_byte.constData())); /* TODO: add remaining fields */ KUrl url(item.remoteId()); temp = url.queryItem("etag"); t_byte = temp.toAscii(); gcal_contact_set_etag(contact, const_cast<char *>(t_byte.constData())); url.removeQueryItem("etag"); temp = url.url(); t_byte = temp.toAscii(); gcal_contact_set_url(contact, const_cast<char *>(t_byte.constData())); if ((result = gcal_update_contact(gcal, contact))) { kError() << "Failed editing contact"; const QString message = i18nc("@info:status", "Failed editing new contact"); emit error(message); emit status(Broken, message); } /* remoteID: etag+edit_url */ KUrl urlEtag(gcal_contact_get_url(contact)); urlEtag.addQueryItem("etag", gcal_contact_get_etag(contact)); //FIXME: this guy is const... how to supply the etag/url? //item.setRemoteId(urlEtag.url()); gcal_contact_delete(contact); } void GoogleDataResource::itemRemoved( const Akonadi::Item &item ) { KABC::Addressee addressee; gcal_contact_t contact; QString temp; QByteArray t_byte; int result; if (!authenticated) { kError() << "No authentication for Google Contacts available"; const QString message = i18nc("@info:status", "Not yet authenticated for" " use of Google Contacts"); emit error(message); emit status(Broken, message); return; } if (!(contact = gcal_contact_new(NULL))) { kError() << "Memory allocation error!"; const QString message = i18nc("@info:status", "Failed to create gcal_contact"); emit error(message); emit status(Broken, message); return; } KUrl url(item.remoteId()); temp = url.queryItem("etag"); t_byte = temp.toAscii(); gcal_contact_set_etag(contact, const_cast<char *>(t_byte.constData())); url.removeQueryItem("etag"); temp = url.url(); t_byte = temp.toAscii(); gcal_contact_set_url(contact, const_cast<char *>(t_byte.constData())); if ((result = gcal_erase_contact(gcal, contact))) { kError() << "Failed deleting contact"; const QString message = i18nc("@info:status", "Failed deleting new contact"); emit error(message); emit status(Broken, message); } gcal_contact_delete(contact); } AKONADI_RESOURCE_MAIN( GoogleDataResource ) #include "googledataresource.moc" <|endoftext|>
<commit_before>#include "googledataresource.h" #include "settings.h" #include "settingsadaptor.h" #include <QtDBus/QDBusConnection> #include <kabc/addressee.h> #include <kabc/phonenumber.h> #include <kabc/key.h> extern "C" { #include <gcalendar.h> #include <gcontact.h> #include <gcal_status.h> } using namespace Akonadi; googledataResource::googledataResource( const QString &id ) : ResourceBase( id ) { new SettingsAdaptor( Settings::self() ); QDBusConnection::sessionBus().registerObject( QLatin1String( "/Settings" ), Settings::self(), QDBusConnection::ExportAdaptors ); if (!(gcal = gcal_new(GCONTACT))) exit(1); gcal_set_store_xml(gcal, 1); } googledataResource::~googledataResource() { gcal_delete(gcal); gcal_cleanup_contacts(&all_contacts); } void googledataResource::retrieveCollections() { // TODO: this method is called when Akonadi wants to have all the // collections your resource provides. // Be sure to set the remote ID and the content MIME types } void googledataResource::retrieveItems( const Akonadi::Collection &collection ) { Q_UNUSED( collection ); Item::List items; int result; /* Downloading the contacts can be slow and it is blocking. Will * it mess up with akonadi? */ if ((result = gcal_get_contacts(gcal, &all_contacts))) exit(1); /* Each google entry has a unique ID and edit_url */ for (size_t i = 0; i < all_contacts.length; ++i) { Item item(QLatin1String("what_is_the_mime_type?")); gcal_contact_t contact = gcal_contact_element(&all_contacts, i); item.setRemoteId(gcal_contact_get_id(contact)); items << item; } itemsRetrieved(items); } bool googledataResource::retrieveItem( const Akonadi::Item &item, const QSet<QByteArray> &parts ) { Q_UNUSED( parts ); const QString entry_id = item.remoteId(); QString temp; Item newItem(item); gcal_contact_t contact; KABC::Addressee addressee; KABC::PhoneNumber number; KABC::Key key; /* * And another question, are the requests in the same sequence that * I informed in 'retrieveItems'? For while, I try to locate the entry... */ for (size_t i = 0; i < all_contacts.length; ++i) { contact = gcal_contact_element(&all_contacts, i); if (entry_id == gcal_contact_get_id(contact)) { /* name */ temp = gcal_contact_get_title(contact); addressee.setNameFromString(temp); /* email */ temp = gcal_contact_get_email(contact); addressee.insertEmail(temp, true); /* edit url: required to do edit/delete */ temp = gcal_contact_get_url(contact); addressee.setUid(temp); /* ETag: required by Google Data protocol 2.0 */ temp = gcal_contact_get_etag(contact); key.setId(temp); addressee.insertKey(key); /* TODO: telefone, address, etc */ newItem.setPayload<KABC::Addressee>(addressee); return true; } } return false; } void googledataResource::aboutToQuit() { // TODO: any cleanup you need to do while there is still an active // event loop. The resource will terminate after this method returns } void googledataResource::configure( WId windowId ) { Q_UNUSED( windowId ); /* TODO: * what kind of dialog to collect google acount username + password ? */ synchronize(); } void googledataResource::itemAdded( const Akonadi::Item &item, const Akonadi::Collection &collection ) { Q_UNUSED( item ); Q_UNUSED( collection ); // TODO: this method is called when somebody else, e.g. a client application, // has created an item in a collection managed by your resource. // NOTE: There is an equivalent method for collections, but it isn't part // of this template code to keep it simple } void googledataResource::itemChanged( const Akonadi::Item &item, const QSet<QByteArray> &parts ) { Q_UNUSED( item ); Q_UNUSED( parts ); // TODO: this method is called when somebody else, e.g. a client application, // has changed an item managed by your resource. // NOTE: There is an equivalent method for collections, but it isn't part // of this template code to keep it simple } void googledataResource::itemRemoved( const Akonadi::Item &item ) { Q_UNUSED( item ); // TODO: this method is called when somebody else, e.g. a client application, // has deleted an item managed by your resource. // NOTE: There is an equivalent method for collections, but it isn't part // of this template code to keep it simple } AKONADI_RESOURCE_MAIN( googledataResource ) #include "googledataresource.moc" <commit_msg>Setting mime-type for items (thanks Igor for suggestion).<commit_after>#include "googledataresource.h" #include "settings.h" #include "settingsadaptor.h" #include <QtDBus/QDBusConnection> #include <kabc/addressee.h> #include <kabc/phonenumber.h> #include <kabc/key.h> extern "C" { #include <gcalendar.h> #include <gcontact.h> #include <gcal_status.h> } using namespace Akonadi; googledataResource::googledataResource( const QString &id ) : ResourceBase( id ) { new SettingsAdaptor( Settings::self() ); QDBusConnection::sessionBus().registerObject( QLatin1String( "/Settings" ), Settings::self(), QDBusConnection::ExportAdaptors ); if (!(gcal = gcal_new(GCONTACT))) exit(1); gcal_set_store_xml(gcal, 1); } googledataResource::~googledataResource() { gcal_delete(gcal); gcal_cleanup_contacts(&all_contacts); } void googledataResource::retrieveCollections() { // TODO: this method is called when Akonadi wants to have all the // collections your resource provides. // Be sure to set the remote ID and the content MIME types } void googledataResource::retrieveItems( const Akonadi::Collection &collection ) { Q_UNUSED( collection ); Item::List items; int result; /* Downloading the contacts can be slow and it is blocking. Will * it mess up with akonadi? */ if ((result = gcal_get_contacts(gcal, &all_contacts))) exit(1); /* Each google entry has a unique ID and edit_url */ for (size_t i = 0; i < all_contacts.length; ++i) { Item item(QLatin1String("text/directory")); gcal_contact_t contact = gcal_contact_element(&all_contacts, i); item.setRemoteId(gcal_contact_get_id(contact)); items << item; } itemsRetrieved(items); } bool googledataResource::retrieveItem( const Akonadi::Item &item, const QSet<QByteArray> &parts ) { Q_UNUSED( parts ); const QString entry_id = item.remoteId(); QString temp; Item newItem(item); gcal_contact_t contact; KABC::Addressee addressee; KABC::PhoneNumber number; KABC::Key key; /* * And another question, are the requests in the same sequence that * I informed in 'retrieveItems'? For while, I try to locate the entry... */ for (size_t i = 0; i < all_contacts.length; ++i) { contact = gcal_contact_element(&all_contacts, i); if (entry_id == gcal_contact_get_id(contact)) { /* name */ temp = gcal_contact_get_title(contact); addressee.setNameFromString(temp); /* email */ temp = gcal_contact_get_email(contact); addressee.insertEmail(temp, true); /* edit url: required to do edit/delete */ temp = gcal_contact_get_url(contact); addressee.setUid(temp); /* ETag: required by Google Data protocol 2.0 */ temp = gcal_contact_get_etag(contact); key.setId(temp); addressee.insertKey(key); /* TODO: telefone, address, etc */ newItem.setPayload<KABC::Addressee>(addressee); return true; } } return false; } void googledataResource::aboutToQuit() { // TODO: any cleanup you need to do while there is still an active // event loop. The resource will terminate after this method returns } void googledataResource::configure( WId windowId ) { Q_UNUSED( windowId ); /* TODO: * what kind of dialog to collect google acount username + password ? */ synchronize(); } void googledataResource::itemAdded( const Akonadi::Item &item, const Akonadi::Collection &collection ) { Q_UNUSED( item ); Q_UNUSED( collection ); // TODO: this method is called when somebody else, e.g. a client application, // has created an item in a collection managed by your resource. // NOTE: There is an equivalent method for collections, but it isn't part // of this template code to keep it simple } void googledataResource::itemChanged( const Akonadi::Item &item, const QSet<QByteArray> &parts ) { Q_UNUSED( item ); Q_UNUSED( parts ); // TODO: this method is called when somebody else, e.g. a client application, // has changed an item managed by your resource. // NOTE: There is an equivalent method for collections, but it isn't part // of this template code to keep it simple } void googledataResource::itemRemoved( const Akonadi::Item &item ) { Q_UNUSED( item ); // TODO: this method is called when somebody else, e.g. a client application, // has deleted an item managed by your resource. // NOTE: There is an equivalent method for collections, but it isn't part // of this template code to keep it simple } AKONADI_RESOURCE_MAIN( googledataResource ) #include "googledataresource.moc" <|endoftext|>
<commit_before>#include "googledataresource.h" #include "settings.h" #include "settingsadaptor.h" #include <QtDBus/QDBusConnection> #include <kabc/addressee.h> #include <kabc/phonenumber.h> #include <kabc/key.h> extern "C" { #include <gcalendar.h> #include <gcontact.h> #include <gcal_status.h> } using namespace Akonadi; googledataResource::googledataResource( const QString &id ) : ResourceBase( id ) { new SettingsAdaptor( Settings::self() ); QDBusConnection::sessionBus().registerObject( QLatin1String( "/Settings" ), Settings::self(), QDBusConnection::ExportAdaptors ); if (!(gcal = gcal_new(GCONTACT))) exit(1); gcal_set_store_xml(gcal, 1); } googledataResource::~googledataResource() { gcal_delete(gcal); gcal_cleanup_contacts(&all_contacts); } void googledataResource::retrieveCollections() { // TODO: this method is called when Akonadi wants to have all the // collections your resource provides. // Be sure to set the remote ID and the content MIME types } void googledataResource::retrieveItems( const Akonadi::Collection &collection ) { Q_UNUSED( collection ); Item::List items; int result; /* Downloading the contacts can be slow and it is blocking. Will * it mess up with akonadi? */ if ((result = gcal_get_contacts(gcal, &all_contacts))) exit(1); /* Each google entry has a unique ID and edit_url */ for (size_t i = 0; i < all_contacts.length; ++i) { Item item(QLatin1String("text/directory")); gcal_contact_t contact = gcal_contact_element(&all_contacts, i); item.setRemoteId(gcal_contact_get_id(contact)); items << item; } itemsRetrieved(items); } bool googledataResource::retrieveItem( const Akonadi::Item &item, const QSet<QByteArray> &parts ) { Q_UNUSED( parts ); const QString entry_id = item.remoteId(); QString temp; Item newItem(item); gcal_contact_t contact; KABC::Addressee addressee; KABC::PhoneNumber number; KABC::Key key; /* * And another question, are the requests in the same sequence that * I informed in 'retrieveItems'? For while, I try to locate the entry... */ for (size_t i = 0; i < all_contacts.length; ++i) { contact = gcal_contact_element(&all_contacts, i); if (entry_id == gcal_contact_get_id(contact)) { /* name */ temp = gcal_contact_get_title(contact); addressee.setNameFromString(temp); /* email */ temp = gcal_contact_get_email(contact); addressee.insertEmail(temp, true); /* edit url: required to do edit/delete */ temp = gcal_contact_get_url(contact); addressee.setUid(temp); /* ETag: required by Google Data protocol 2.0 */ temp = gcal_contact_get_etag(contact); key.setId(temp); addressee.insertKey(key); /* TODO: telefone, address, etc */ newItem.setPayload<KABC::Addressee>(addressee); return true; } } return false; } void googledataResource::aboutToQuit() { // TODO: any cleanup you need to do while there is still an active // event loop. The resource will terminate after this method returns } void googledataResource::configure( WId windowId ) { Q_UNUSED( windowId ); /* TODO: * what kind of dialog to collect google acount username + password ? */ synchronize(); } void googledataResource::itemAdded( const Akonadi::Item &item, const Akonadi::Collection &collection ) { Q_UNUSED( item ); Q_UNUSED( collection ); // TODO: this method is called when somebody else, e.g. a client application, // has created an item in a collection managed by your resource. // NOTE: There is an equivalent method for collections, but it isn't part // of this template code to keep it simple } void googledataResource::itemChanged( const Akonadi::Item &item, const QSet<QByteArray> &parts ) { Q_UNUSED( item ); Q_UNUSED( parts ); // TODO: this method is called when somebody else, e.g. a client application, // has changed an item managed by your resource. // NOTE: There is an equivalent method for collections, but it isn't part // of this template code to keep it simple } void googledataResource::itemRemoved( const Akonadi::Item &item ) { Q_UNUSED( item ); // TODO: this method is called when somebody else, e.g. a client application, // has deleted an item managed by your resource. // NOTE: There is an equivalent method for collections, but it isn't part // of this template code to keep it simple } AKONADI_RESOURCE_MAIN( googledataResource ) #include "googledataresource.moc" <commit_msg>Returning a collection (just copy-and-paste from akonadi resource tutorial).<commit_after>#include "googledataresource.h" #include "settings.h" #include "settingsadaptor.h" #include <QtDBus/QDBusConnection> #include <kabc/addressee.h> #include <kabc/phonenumber.h> #include <kabc/key.h> extern "C" { #include <gcalendar.h> #include <gcontact.h> #include <gcal_status.h> } using namespace Akonadi; googledataResource::googledataResource( const QString &id ) : ResourceBase( id ) { new SettingsAdaptor( Settings::self() ); QDBusConnection::sessionBus().registerObject( QLatin1String( "/Settings" ), Settings::self(), QDBusConnection::ExportAdaptors ); if (!(gcal = gcal_new(GCONTACT))) exit(1); gcal_set_store_xml(gcal, 1); } googledataResource::~googledataResource() { gcal_delete(gcal); gcal_cleanup_contacts(&all_contacts); } void googledataResource::retrieveCollections() { Collection c; c.setParent(Collection::root()); c.setRemoteId(Settings::self()->path()); c.setName(name()); QStringList mimeTypes; mimeTypes << "text/directory"; c.setContentMimeTypes(mimeTypes); Collection::List list; list << c; collectionsRetrieved(list); } void googledataResource::retrieveItems( const Akonadi::Collection &collection ) { Q_UNUSED( collection ); Item::List items; int result; /* Downloading the contacts can be slow and it is blocking. Will * it mess up with akonadi? */ if ((result = gcal_get_contacts(gcal, &all_contacts))) exit(1); /* Each google entry has a unique ID and edit_url */ for (size_t i = 0; i < all_contacts.length; ++i) { Item item(QLatin1String("text/directory")); gcal_contact_t contact = gcal_contact_element(&all_contacts, i); item.setRemoteId(gcal_contact_get_id(contact)); items << item; } itemsRetrieved(items); } bool googledataResource::retrieveItem( const Akonadi::Item &item, const QSet<QByteArray> &parts ) { Q_UNUSED( parts ); const QString entry_id = item.remoteId(); QString temp; Item newItem(item); gcal_contact_t contact; KABC::Addressee addressee; KABC::PhoneNumber number; KABC::Key key; /* * And another question, are the requests in the same sequence that * I informed in 'retrieveItems'? For while, I try to locate the entry... */ for (size_t i = 0; i < all_contacts.length; ++i) { contact = gcal_contact_element(&all_contacts, i); if (entry_id == gcal_contact_get_id(contact)) { /* name */ temp = gcal_contact_get_title(contact); addressee.setNameFromString(temp); /* email */ temp = gcal_contact_get_email(contact); addressee.insertEmail(temp, true); /* edit url: required to do edit/delete */ temp = gcal_contact_get_url(contact); addressee.setUid(temp); /* ETag: required by Google Data protocol 2.0 */ temp = gcal_contact_get_etag(contact); key.setId(temp); addressee.insertKey(key); /* TODO: telefone, address, etc */ newItem.setPayload<KABC::Addressee>(addressee); return true; } } return false; } void googledataResource::aboutToQuit() { // TODO: any cleanup you need to do while there is still an active // event loop. The resource will terminate after this method returns } void googledataResource::configure( WId windowId ) { Q_UNUSED( windowId ); /* TODO: * what kind of dialog to collect google acount username + password ? */ synchronize(); } void googledataResource::itemAdded( const Akonadi::Item &item, const Akonadi::Collection &collection ) { Q_UNUSED( item ); Q_UNUSED( collection ); // TODO: this method is called when somebody else, e.g. a client application, // has created an item in a collection managed by your resource. // NOTE: There is an equivalent method for collections, but it isn't part // of this template code to keep it simple } void googledataResource::itemChanged( const Akonadi::Item &item, const QSet<QByteArray> &parts ) { Q_UNUSED( item ); Q_UNUSED( parts ); // TODO: this method is called when somebody else, e.g. a client application, // has changed an item managed by your resource. // NOTE: There is an equivalent method for collections, but it isn't part // of this template code to keep it simple } void googledataResource::itemRemoved( const Akonadi::Item &item ) { Q_UNUSED( item ); // TODO: this method is called when somebody else, e.g. a client application, // has deleted an item managed by your resource. // NOTE: There is an equivalent method for collections, but it isn't part // of this template code to keep it simple } AKONADI_RESOURCE_MAIN( googledataResource ) #include "googledataresource.moc" <|endoftext|>
<commit_before>// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "atom/common/api/atom_bindings.h" #include <algorithm> #include <iostream> #include <string> #include "atom/common/atom_version.h" #include "atom/common/chrome_version.h" #include "atom/common/native_mate_converters/string16_converter.h" #include "atom/common/node_includes.h" #include "base/logging.h" #include "base/process/process_metrics.h" #include "base/sys_info.h" #include "native_mate/dictionary.h" namespace atom { namespace { // Dummy class type that used for crashing the program. struct DummyClass { bool crash; }; v8::Local<v8::Value> GetCPUUsage(v8::Isolate* isolate) { std::unique_ptr<base::ProcessMetrics> metrics( base::ProcessMetrics::CreateCurrentProcessMetrics()); mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate); int processor_count = base::SysInfo::NumberOfProcessors(); dict.Set("percentCPUUsage", metrics->GetPlatformIndependentCPUUsage() / processor_count); dict.Set("idleWakeupsPerSecond", metrics->GetIdleWakeupsPerSecond()); return dict.GetHandle(); } v8::Local<v8::Value> GetIOCounters(v8::Isolate* isolate) { std::unique_ptr<base::ProcessMetrics> metrics( base::ProcessMetrics::CreateCurrentProcessMetrics()); base::IoCounters io_counters; const bool got_counters = metrics->GetIOCounters(&io_counters); mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate); if (got_counters) { dict.Set("readOperationCount", io_counters.ReadOperationCount); dict.Set("writeOperationCount", io_counters.WriteOperationCount); dict.Set("otherOperationCount", io_counters.OtherOperationCount); dict.Set("readTransferCount", io_counters.ReadTransferCount); dict.Set("writeTransferCount", io_counters.WriteTransferCount); dict.Set("otherTransferCount", io_counters.OtherTransferCount); } return dict.GetHandle(); } // Called when there is a fatal error in V8, we just crash the process here so // we can get the stack trace. void FatalErrorCallback(const char* location, const char* message) { LOG(ERROR) << "Fatal error in V8: " << location << " " << message; AtomBindings::Crash(); } } // namespace AtomBindings::AtomBindings(uv_loop_t* loop) { uv_async_init(loop, &call_next_tick_async_, OnCallNextTick); call_next_tick_async_.data = this; } AtomBindings::~AtomBindings() { uv_close(reinterpret_cast<uv_handle_t*>(&call_next_tick_async_), nullptr); } void AtomBindings::BindTo(v8::Isolate* isolate, v8::Local<v8::Object> process) { v8::V8::SetFatalErrorHandler(FatalErrorCallback); mate::Dictionary dict(isolate, process); dict.SetMethod("crash", &AtomBindings::Crash); dict.SetMethod("hang", &Hang); dict.SetMethod("log", &Log); dict.SetMethod("getProcessMemoryInfo", &GetProcessMemoryInfo); dict.SetMethod("getSystemMemoryInfo", &GetSystemMemoryInfo); dict.SetMethod("getCPUUsage", &GetCPUUsage); dict.SetMethod("getIOCounters", &GetIOCounters); #if defined(OS_POSIX) dict.SetMethod("setFdLimit", &base::SetFdLimit); #endif dict.SetMethod("activateUvLoop", base::Bind(&AtomBindings::ActivateUVLoop, base::Unretained(this))); #if defined(MAS_BUILD) dict.Set("mas", true); #endif mate::Dictionary versions; if (dict.Get("versions", &versions)) { // TODO(kevinsawicki): Make read-only in 2.0 to match node versions.Set(ATOM_PROJECT_NAME, ATOM_VERSION_STRING); versions.Set("chrome", CHROME_VERSION_STRING); // TODO(kevinsawicki): Remove in 2.0 versions.Set("atom-shell", ATOM_VERSION_STRING); } } void AtomBindings::EnvironmentDestroyed(node::Environment* env) { auto it = std::find(pending_next_ticks_.begin(), pending_next_ticks_.end(), env); if (it != pending_next_ticks_.end()) pending_next_ticks_.erase(it); } void AtomBindings::ActivateUVLoop(v8::Isolate* isolate) { node::Environment* env = node::Environment::GetCurrent(isolate); if (std::find(pending_next_ticks_.begin(), pending_next_ticks_.end(), env) != pending_next_ticks_.end()) return; pending_next_ticks_.push_back(env); uv_async_send(&call_next_tick_async_); } // static void AtomBindings::OnCallNextTick(uv_async_t* handle) { AtomBindings* self = static_cast<AtomBindings*>(handle->data); for (std::list<node::Environment*>::const_iterator it = self->pending_next_ticks_.begin(); it != self->pending_next_ticks_.end(); ++it) { node::Environment* env = *it; // KickNextTick, copied from node.cc: node::Environment::AsyncCallbackScope callback_scope(env); if (callback_scope.in_makecallback()) continue; node::Environment::TickInfo* tick_info = env->tick_info(); if (tick_info->length() == 0) env->isolate()->RunMicrotasks(); v8::Local<v8::Object> process = env->process_object(); if (tick_info->length() == 0) tick_info->set_index(0); env->tick_callback_function()->Call(process, 0, nullptr).IsEmpty(); } self->pending_next_ticks_.clear(); } // static void AtomBindings::Log(const base::string16& message) { std::cout << message << std::flush; } // static void AtomBindings::Crash() { static_cast<DummyClass*>(nullptr)->crash = true; } // static void AtomBindings::Hang() { for (;;) base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(1)); } // static v8::Local<v8::Value> AtomBindings::GetProcessMemoryInfo(v8::Isolate* isolate) { std::unique_ptr<base::ProcessMetrics> metrics( base::ProcessMetrics::CreateCurrentProcessMetrics()); mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate); dict.Set("workingSetSize", static_cast<double>(metrics->GetWorkingSetSize() >> 10)); dict.Set("peakWorkingSetSize", static_cast<double>(metrics->GetPeakWorkingSetSize() >> 10)); size_t private_bytes, shared_bytes; if (metrics->GetMemoryBytes(&private_bytes, &shared_bytes)) { dict.Set("privateBytes", static_cast<double>(private_bytes >> 10)); dict.Set("sharedBytes", static_cast<double>(shared_bytes >> 10)); } return dict.GetHandle(); } // static v8::Local<v8::Value> AtomBindings::GetSystemMemoryInfo(v8::Isolate* isolate, mate::Arguments* args) { base::SystemMemoryInfoKB mem_info; if (!base::GetSystemMemoryInfo(&mem_info)) { args->ThrowError("Unable to retrieve system memory information"); return v8::Undefined(isolate); } mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate); dict.Set("total", mem_info.total); dict.Set("free", mem_info.free); // NB: These return bogus values on macOS #if !defined(OS_MACOSX) dict.Set("swapTotal", mem_info.swap_total); dict.Set("swapFree", mem_info.swap_free); #endif return dict.GetHandle(); } } // namespace atom <commit_msg>Removing extra bool<commit_after>// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "atom/common/api/atom_bindings.h" #include <algorithm> #include <iostream> #include <string> #include "atom/common/atom_version.h" #include "atom/common/chrome_version.h" #include "atom/common/native_mate_converters/string16_converter.h" #include "atom/common/node_includes.h" #include "base/logging.h" #include "base/process/process_metrics.h" #include "base/sys_info.h" #include "native_mate/dictionary.h" namespace atom { namespace { // Dummy class type that used for crashing the program. struct DummyClass { bool crash; }; v8::Local<v8::Value> GetCPUUsage(v8::Isolate* isolate) { std::unique_ptr<base::ProcessMetrics> metrics( base::ProcessMetrics::CreateCurrentProcessMetrics()); mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate); int processor_count = base::SysInfo::NumberOfProcessors(); dict.Set("percentCPUUsage", metrics->GetPlatformIndependentCPUUsage() / processor_count); dict.Set("idleWakeupsPerSecond", metrics->GetIdleWakeupsPerSecond()); return dict.GetHandle(); } v8::Local<v8::Value> GetIOCounters(v8::Isolate* isolate) { std::unique_ptr<base::ProcessMetrics> metrics( base::ProcessMetrics::CreateCurrentProcessMetrics()); base::IoCounters io_counters; mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate); if (metrics->GetIOCounters(&io_counters)) { dict.Set("readOperationCount", io_counters.ReadOperationCount); dict.Set("writeOperationCount", io_counters.WriteOperationCount); dict.Set("otherOperationCount", io_counters.OtherOperationCount); dict.Set("readTransferCount", io_counters.ReadTransferCount); dict.Set("writeTransferCount", io_counters.WriteTransferCount); dict.Set("otherTransferCount", io_counters.OtherTransferCount); } return dict.GetHandle(); } // Called when there is a fatal error in V8, we just crash the process here so // we can get the stack trace. void FatalErrorCallback(const char* location, const char* message) { LOG(ERROR) << "Fatal error in V8: " << location << " " << message; AtomBindings::Crash(); } } // namespace AtomBindings::AtomBindings(uv_loop_t* loop) { uv_async_init(loop, &call_next_tick_async_, OnCallNextTick); call_next_tick_async_.data = this; } AtomBindings::~AtomBindings() { uv_close(reinterpret_cast<uv_handle_t*>(&call_next_tick_async_), nullptr); } void AtomBindings::BindTo(v8::Isolate* isolate, v8::Local<v8::Object> process) { v8::V8::SetFatalErrorHandler(FatalErrorCallback); mate::Dictionary dict(isolate, process); dict.SetMethod("crash", &AtomBindings::Crash); dict.SetMethod("hang", &Hang); dict.SetMethod("log", &Log); dict.SetMethod("getProcessMemoryInfo", &GetProcessMemoryInfo); dict.SetMethod("getSystemMemoryInfo", &GetSystemMemoryInfo); dict.SetMethod("getCPUUsage", &GetCPUUsage); dict.SetMethod("getIOCounters", &GetIOCounters); #if defined(OS_POSIX) dict.SetMethod("setFdLimit", &base::SetFdLimit); #endif dict.SetMethod("activateUvLoop", base::Bind(&AtomBindings::ActivateUVLoop, base::Unretained(this))); #if defined(MAS_BUILD) dict.Set("mas", true); #endif mate::Dictionary versions; if (dict.Get("versions", &versions)) { // TODO(kevinsawicki): Make read-only in 2.0 to match node versions.Set(ATOM_PROJECT_NAME, ATOM_VERSION_STRING); versions.Set("chrome", CHROME_VERSION_STRING); // TODO(kevinsawicki): Remove in 2.0 versions.Set("atom-shell", ATOM_VERSION_STRING); } } void AtomBindings::EnvironmentDestroyed(node::Environment* env) { auto it = std::find(pending_next_ticks_.begin(), pending_next_ticks_.end(), env); if (it != pending_next_ticks_.end()) pending_next_ticks_.erase(it); } void AtomBindings::ActivateUVLoop(v8::Isolate* isolate) { node::Environment* env = node::Environment::GetCurrent(isolate); if (std::find(pending_next_ticks_.begin(), pending_next_ticks_.end(), env) != pending_next_ticks_.end()) return; pending_next_ticks_.push_back(env); uv_async_send(&call_next_tick_async_); } // static void AtomBindings::OnCallNextTick(uv_async_t* handle) { AtomBindings* self = static_cast<AtomBindings*>(handle->data); for (std::list<node::Environment*>::const_iterator it = self->pending_next_ticks_.begin(); it != self->pending_next_ticks_.end(); ++it) { node::Environment* env = *it; // KickNextTick, copied from node.cc: node::Environment::AsyncCallbackScope callback_scope(env); if (callback_scope.in_makecallback()) continue; node::Environment::TickInfo* tick_info = env->tick_info(); if (tick_info->length() == 0) env->isolate()->RunMicrotasks(); v8::Local<v8::Object> process = env->process_object(); if (tick_info->length() == 0) tick_info->set_index(0); env->tick_callback_function()->Call(process, 0, nullptr).IsEmpty(); } self->pending_next_ticks_.clear(); } // static void AtomBindings::Log(const base::string16& message) { std::cout << message << std::flush; } // static void AtomBindings::Crash() { static_cast<DummyClass*>(nullptr)->crash = true; } // static void AtomBindings::Hang() { for (;;) base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(1)); } // static v8::Local<v8::Value> AtomBindings::GetProcessMemoryInfo(v8::Isolate* isolate) { std::unique_ptr<base::ProcessMetrics> metrics( base::ProcessMetrics::CreateCurrentProcessMetrics()); mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate); dict.Set("workingSetSize", static_cast<double>(metrics->GetWorkingSetSize() >> 10)); dict.Set("peakWorkingSetSize", static_cast<double>(metrics->GetPeakWorkingSetSize() >> 10)); size_t private_bytes, shared_bytes; if (metrics->GetMemoryBytes(&private_bytes, &shared_bytes)) { dict.Set("privateBytes", static_cast<double>(private_bytes >> 10)); dict.Set("sharedBytes", static_cast<double>(shared_bytes >> 10)); } return dict.GetHandle(); } // static v8::Local<v8::Value> AtomBindings::GetSystemMemoryInfo(v8::Isolate* isolate, mate::Arguments* args) { base::SystemMemoryInfoKB mem_info; if (!base::GetSystemMemoryInfo(&mem_info)) { args->ThrowError("Unable to retrieve system memory information"); return v8::Undefined(isolate); } mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate); dict.Set("total", mem_info.total); dict.Set("free", mem_info.free); // NB: These return bogus values on macOS #if !defined(OS_MACOSX) dict.Set("swapTotal", mem_info.swap_total); dict.Set("swapFree", mem_info.swap_free); #endif return dict.GetHandle(); } } // namespace atom <|endoftext|>
<commit_before><commit_msg>Remove unused tab_contents variable.<commit_after><|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 "chrome/browser/dom_ui/browser_options_handler.h" #include "app/l10n_util.h" #include "base/basictypes.h" #include "base/scoped_ptr.h" #include "base/string_number_conversions.h" #include "base/utf_string_conversions.h" #include "base/values.h" #include "chrome/browser/custom_home_pages_table_model.h" #include "chrome/browser/profile.h" #include "chrome/browser/session_startup_pref.h" #include "chrome/installer/util/browser_distribution.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" BrowserOptionsHandler::BrowserOptionsHandler() : template_url_model_(NULL), startup_custom_pages_table_model_(NULL) { #if !defined(OS_MACOSX) default_browser_worker_ = new ShellIntegration::DefaultBrowserWorker(this); #endif } BrowserOptionsHandler::~BrowserOptionsHandler() { if (default_browser_worker_.get()) default_browser_worker_->ObserverDestroyed(); if (template_url_model_) template_url_model_->RemoveObserver(this); } void BrowserOptionsHandler::GetLocalizedValues( DictionaryValue* localized_strings) { DCHECK(localized_strings); localized_strings->SetString(L"startupGroupName", l10n_util::GetString(IDS_OPTIONS_STARTUP_GROUP_NAME)); localized_strings->SetString(L"startupShowDefaultAndNewTab", l10n_util::GetString(IDS_OPTIONS_STARTUP_SHOW_DEFAULT_AND_NEWTAB)); localized_strings->SetString(L"startupShowLastSession", l10n_util::GetString(IDS_OPTIONS_STARTUP_SHOW_LAST_SESSION)); localized_strings->SetString(L"startupShowPages", l10n_util::GetString(IDS_OPTIONS_STARTUP_SHOW_PAGES)); localized_strings->SetString(L"startupAddButton", l10n_util::GetString(IDS_OPTIONS_STARTUP_ADD_BUTTON)); localized_strings->SetString(L"startupRemoveButton", l10n_util::GetString(IDS_OPTIONS_STARTUP_REMOVE_BUTTON)); localized_strings->SetString(L"startupUseCurrent", l10n_util::GetString(IDS_OPTIONS_STARTUP_USE_CURRENT)); localized_strings->SetString(L"homepageGroupName", l10n_util::GetString(IDS_OPTIONS_HOMEPAGE_GROUP_NAME)); localized_strings->SetString(L"homepageUseNewTab", l10n_util::GetString(IDS_OPTIONS_HOMEPAGE_USE_NEWTAB)); localized_strings->SetString(L"homepageUseURL", l10n_util::GetString(IDS_OPTIONS_HOMEPAGE_USE_URL)); localized_strings->SetString(L"homepageShowButton", l10n_util::GetString(IDS_OPTIONS_HOMEPAGE_SHOW_BUTTON)); localized_strings->SetString(L"defaultSearchGroupName", l10n_util::GetString(IDS_OPTIONS_DEFAULTSEARCH_GROUP_NAME)); localized_strings->SetString(L"defaultSearchManageEnginesLink", l10n_util::GetString(IDS_OPTIONS_DEFAULTSEARCH_MANAGE_ENGINES_LINK)); localized_strings->SetString(L"defaultBrowserGroupName", l10n_util::GetString(IDS_OPTIONS_DEFAULTBROWSER_GROUP_NAME)); localized_strings->SetString(L"defaultBrowserUnknown", l10n_util::GetStringF(IDS_OPTIONS_DEFAULTBROWSER_UNKNOWN, l10n_util::GetString(IDS_PRODUCT_NAME))); localized_strings->SetString(L"defaultBrowserUseAsDefault", l10n_util::GetStringF(IDS_OPTIONS_DEFAULTBROWSER_USEASDEFAULT, l10n_util::GetString(IDS_PRODUCT_NAME))); } void BrowserOptionsHandler::RegisterMessages() { dom_ui_->RegisterMessageCallback( "becomeDefaultBrowser", NewCallback(this, &BrowserOptionsHandler::BecomeDefaultBrowser)); dom_ui_->RegisterMessageCallback( "setDefaultSearchEngine", NewCallback(this, &BrowserOptionsHandler::SetDefaultSearchEngine)); dom_ui_->RegisterMessageCallback( "removeStartupPages", NewCallback(this, &BrowserOptionsHandler::RemoveStartupPages)); dom_ui_->RegisterMessageCallback( "setStartupPagesToCurrentPages", NewCallback(this, &BrowserOptionsHandler::SetStartupPagesToCurrentPages)); } void BrowserOptionsHandler::Initialize() { UpdateDefaultBrowserState(); UpdateStartupPages(); UpdateSearchEngines(); } void BrowserOptionsHandler::UpdateDefaultBrowserState() { #if defined(OS_WIN) // Check for side-by-side first. if (!BrowserDistribution::GetDistribution()->CanSetAsDefault()) { SetDefaultBrowserUIString(IDS_OPTIONS_DEFAULTBROWSER_SXS); return; } #endif #if defined(OS_MACOSX) ShellIntegration::DefaultBrowserState state = ShellIntegration::IsDefaultBrowser(); int status_string_id; if (state == ShellIntegration::IS_DEFAULT_BROWSER) status_string_id = IDS_OPTIONS_DEFAULTBROWSER_DEFAULT; else if (state == ShellIntegration::NOT_DEFAULT_BROWSER) status_string_id = IDS_OPTIONS_DEFAULTBROWSER_NOTDEFAULT; else status_string_id = IDS_OPTIONS_DEFAULTBROWSER_UNKNOWN; SetDefaultBrowserUIString(status_string_id); #else default_browser_worker_->StartCheckDefaultBrowser(); #endif } void BrowserOptionsHandler::BecomeDefaultBrowser(const Value* value) { #if defined(OS_MACOSX) if (ShellIntegration::SetAsDefaultBrowser()) UpdateDefaultBrowserState(); #else default_browser_worker_->StartSetAsDefaultBrowser(); // Callback takes care of updating UI. #endif } int BrowserOptionsHandler::StatusStringIdForState( ShellIntegration::DefaultBrowserState state) { if (state == ShellIntegration::IS_DEFAULT_BROWSER) return IDS_OPTIONS_DEFAULTBROWSER_DEFAULT; if (state == ShellIntegration::NOT_DEFAULT_BROWSER) return IDS_OPTIONS_DEFAULTBROWSER_NOTDEFAULT; return IDS_OPTIONS_DEFAULTBROWSER_UNKNOWN; } void BrowserOptionsHandler::SetDefaultBrowserUIState( ShellIntegration::DefaultBrowserUIState state) { int status_string_id; if (state == ShellIntegration::STATE_IS_DEFAULT) status_string_id = IDS_OPTIONS_DEFAULTBROWSER_DEFAULT; else if (state == ShellIntegration::STATE_NOT_DEFAULT) status_string_id = IDS_OPTIONS_DEFAULTBROWSER_NOTDEFAULT; else if (state == ShellIntegration::STATE_UNKNOWN) status_string_id = IDS_OPTIONS_DEFAULTBROWSER_UNKNOWN; else return; // Still processing. SetDefaultBrowserUIString(status_string_id); } void BrowserOptionsHandler::SetDefaultBrowserUIString(int status_string_id) { scoped_ptr<Value> status_string(Value::CreateStringValue( l10n_util::GetStringF(status_string_id, l10n_util::GetString(IDS_PRODUCT_NAME)))); scoped_ptr<Value> is_default(Value::CreateBooleanValue( status_string_id == IDS_OPTIONS_DEFAULTBROWSER_DEFAULT)); dom_ui_->CallJavascriptFunction( L"BrowserOptions.updateDefaultBrowserState", *(status_string.get()), *(is_default.get())); } void BrowserOptionsHandler::OnTemplateURLModelChanged() { if (!template_url_model_ || !template_url_model_->loaded()) return; const TemplateURL* default_url = template_url_model_->GetDefaultSearchProvider(); int default_index = 0; ListValue search_engines; std::vector<const TemplateURL*> model_urls = template_url_model_->GetTemplateURLs(); for (size_t i = 0; i < model_urls.size(); ++i) { if (!model_urls[i]->ShowInDefaultList()) continue; DictionaryValue* entry = new DictionaryValue(); entry->SetString(L"name", model_urls[i]->short_name()); entry->SetInteger(L"index", i); search_engines.Append(entry); if (model_urls[i] == default_url) default_index = i; } scoped_ptr<Value> default_value(Value::CreateIntegerValue(default_index)); dom_ui_->CallJavascriptFunction(L"BrowserOptions.updateSearchEngines", search_engines, *(default_value.get())); } void BrowserOptionsHandler::SetDefaultSearchEngine(const Value* value) { if (!value || !value->IsType(Value::TYPE_LIST)) { NOTREACHED(); return; } const ListValue* param_values = static_cast<const ListValue*>(value); std::string string_value; if (param_values->GetSize() != 1 || !param_values->GetString(0, &string_value)) { NOTREACHED(); return; } int selected_index; base::StringToInt(string_value, &selected_index); std::vector<const TemplateURL*> model_urls = template_url_model_->GetTemplateURLs(); if (selected_index >= 0 && selected_index < static_cast<int>(model_urls.size())) template_url_model_->SetDefaultSearchProvider(model_urls[selected_index]); } void BrowserOptionsHandler::UpdateSearchEngines() { template_url_model_ = dom_ui_->GetProfile()->GetTemplateURLModel(); if (template_url_model_) { template_url_model_->Load(); template_url_model_->AddObserver(this); OnTemplateURLModelChanged(); } } void BrowserOptionsHandler::UpdateStartupPages() { Profile* profile = dom_ui_->GetProfile(); startup_custom_pages_table_model_.reset( new CustomHomePagesTableModel(profile)); startup_custom_pages_table_model_->SetObserver(this); const SessionStartupPref startup_pref = SessionStartupPref::GetStartupPref(profile->GetPrefs()); startup_custom_pages_table_model_->SetURLs(startup_pref.urls); } void BrowserOptionsHandler::OnModelChanged() { // TODO(stuartmorgan): Add support for showing favicons. ListValue startup_pages; int page_count = startup_custom_pages_table_model_->RowCount(); for (int i = 0; i < page_count; ++i) { DictionaryValue* entry = new DictionaryValue(); entry->SetString(L"title", startup_custom_pages_table_model_->GetText(i, 0)); entry->SetString(L"tooltip", startup_custom_pages_table_model_->GetTooltip(i)); startup_pages.Append(entry); } dom_ui_->CallJavascriptFunction(L"BrowserOptions.updateStartupPages", startup_pages); } void BrowserOptionsHandler::OnItemsChanged(int start, int length) { OnModelChanged(); } void BrowserOptionsHandler::OnItemsAdded(int start, int length) { OnModelChanged(); } void BrowserOptionsHandler::OnItemsRemoved(int start, int length) { OnModelChanged(); } void BrowserOptionsHandler::SetStartupPagesToCurrentPages(const Value* value) { startup_custom_pages_table_model_->SetToCurrentlyOpenPages(); SaveStartupPagesPref(); } void BrowserOptionsHandler::RemoveStartupPages(const Value* value) { if (!value || !value->IsType(Value::TYPE_LIST)) { NOTREACHED(); return; } const ListValue* param_values = static_cast<const ListValue*>(value); for (int i = param_values->GetSize() - 1; i >= 0; --i) { std::string string_value; if (!param_values->GetString(i, &string_value)) { NOTREACHED(); return; } int selected_index; base::StringToInt(string_value, &selected_index); if (selected_index < 0 || selected_index >= startup_custom_pages_table_model_->RowCount()) { NOTREACHED(); return; } startup_custom_pages_table_model_->Remove(selected_index); } SaveStartupPagesPref(); } void BrowserOptionsHandler::SaveStartupPagesPref() { PrefService* prefs = dom_ui_->GetProfile()->GetPrefs(); SessionStartupPref pref = SessionStartupPref::GetStartupPref(prefs); pref.urls = startup_custom_pages_table_model_->GetURLs(); SessionStartupPref::SetStartupPref(prefs, pref); } <commit_msg>Convert browser/dom_ui/browser_options_handler.cc to stop using wstrings/wchar_t*s.<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 "chrome/browser/dom_ui/browser_options_handler.h" #include "app/l10n_util.h" #include "base/basictypes.h" #include "base/scoped_ptr.h" #include "base/string_number_conversions.h" #include "base/utf_string_conversions.h" #include "base/values.h" #include "chrome/browser/custom_home_pages_table_model.h" #include "chrome/browser/profile.h" #include "chrome/browser/session_startup_pref.h" #include "chrome/installer/util/browser_distribution.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" BrowserOptionsHandler::BrowserOptionsHandler() : template_url_model_(NULL), startup_custom_pages_table_model_(NULL) { #if !defined(OS_MACOSX) default_browser_worker_ = new ShellIntegration::DefaultBrowserWorker(this); #endif } BrowserOptionsHandler::~BrowserOptionsHandler() { if (default_browser_worker_.get()) default_browser_worker_->ObserverDestroyed(); if (template_url_model_) template_url_model_->RemoveObserver(this); } void BrowserOptionsHandler::GetLocalizedValues( DictionaryValue* localized_strings) { DCHECK(localized_strings); localized_strings->SetString("startupGroupName", l10n_util::GetStringUTF16(IDS_OPTIONS_STARTUP_GROUP_NAME)); localized_strings->SetString("startupShowDefaultAndNewTab", l10n_util::GetStringUTF16(IDS_OPTIONS_STARTUP_SHOW_DEFAULT_AND_NEWTAB)); localized_strings->SetString("startupShowLastSession", l10n_util::GetStringUTF16(IDS_OPTIONS_STARTUP_SHOW_LAST_SESSION)); localized_strings->SetString("startupShowPages", l10n_util::GetStringUTF16(IDS_OPTIONS_STARTUP_SHOW_PAGES)); localized_strings->SetString("startupAddButton", l10n_util::GetStringUTF16(IDS_OPTIONS_STARTUP_ADD_BUTTON)); localized_strings->SetString("startupRemoveButton", l10n_util::GetStringUTF16(IDS_OPTIONS_STARTUP_REMOVE_BUTTON)); localized_strings->SetString("startupUseCurrent", l10n_util::GetStringUTF16(IDS_OPTIONS_STARTUP_USE_CURRENT)); localized_strings->SetString("homepageGroupName", l10n_util::GetStringUTF16(IDS_OPTIONS_HOMEPAGE_GROUP_NAME)); localized_strings->SetString("homepageUseNewTab", l10n_util::GetStringUTF16(IDS_OPTIONS_HOMEPAGE_USE_NEWTAB)); localized_strings->SetString("homepageUseURL", l10n_util::GetStringUTF16(IDS_OPTIONS_HOMEPAGE_USE_URL)); localized_strings->SetString("homepageShowButton", l10n_util::GetStringUTF16(IDS_OPTIONS_HOMEPAGE_SHOW_BUTTON)); localized_strings->SetString("defaultSearchGroupName", l10n_util::GetStringUTF16(IDS_OPTIONS_DEFAULTSEARCH_GROUP_NAME)); localized_strings->SetString("defaultSearchManageEnginesLink", l10n_util::GetStringUTF16(IDS_OPTIONS_DEFAULTSEARCH_MANAGE_ENGINES_LINK)); localized_strings->SetString("defaultBrowserGroupName", l10n_util::GetStringUTF16(IDS_OPTIONS_DEFAULTBROWSER_GROUP_NAME)); localized_strings->SetString("defaultBrowserUnknown", l10n_util::GetStringFUTF16(IDS_OPTIONS_DEFAULTBROWSER_UNKNOWN, l10n_util::GetStringUTF16(IDS_PRODUCT_NAME))); localized_strings->SetString("defaultBrowserUseAsDefault", l10n_util::GetStringFUTF16(IDS_OPTIONS_DEFAULTBROWSER_USEASDEFAULT, l10n_util::GetStringUTF16(IDS_PRODUCT_NAME))); } void BrowserOptionsHandler::RegisterMessages() { dom_ui_->RegisterMessageCallback( "becomeDefaultBrowser", NewCallback(this, &BrowserOptionsHandler::BecomeDefaultBrowser)); dom_ui_->RegisterMessageCallback( "setDefaultSearchEngine", NewCallback(this, &BrowserOptionsHandler::SetDefaultSearchEngine)); dom_ui_->RegisterMessageCallback( "removeStartupPages", NewCallback(this, &BrowserOptionsHandler::RemoveStartupPages)); dom_ui_->RegisterMessageCallback( "setStartupPagesToCurrentPages", NewCallback(this, &BrowserOptionsHandler::SetStartupPagesToCurrentPages)); } void BrowserOptionsHandler::Initialize() { UpdateDefaultBrowserState(); UpdateStartupPages(); UpdateSearchEngines(); } void BrowserOptionsHandler::UpdateDefaultBrowserState() { #if defined(OS_WIN) // Check for side-by-side first. if (!BrowserDistribution::GetDistribution()->CanSetAsDefault()) { SetDefaultBrowserUIString(IDS_OPTIONS_DEFAULTBROWSER_SXS); return; } #endif #if defined(OS_MACOSX) ShellIntegration::DefaultBrowserState state = ShellIntegration::IsDefaultBrowser(); int status_string_id; if (state == ShellIntegration::IS_DEFAULT_BROWSER) status_string_id = IDS_OPTIONS_DEFAULTBROWSER_DEFAULT; else if (state == ShellIntegration::NOT_DEFAULT_BROWSER) status_string_id = IDS_OPTIONS_DEFAULTBROWSER_NOTDEFAULT; else status_string_id = IDS_OPTIONS_DEFAULTBROWSER_UNKNOWN; SetDefaultBrowserUIString(status_string_id); #else default_browser_worker_->StartCheckDefaultBrowser(); #endif } void BrowserOptionsHandler::BecomeDefaultBrowser(const Value* value) { #if defined(OS_MACOSX) if (ShellIntegration::SetAsDefaultBrowser()) UpdateDefaultBrowserState(); #else default_browser_worker_->StartSetAsDefaultBrowser(); // Callback takes care of updating UI. #endif } int BrowserOptionsHandler::StatusStringIdForState( ShellIntegration::DefaultBrowserState state) { if (state == ShellIntegration::IS_DEFAULT_BROWSER) return IDS_OPTIONS_DEFAULTBROWSER_DEFAULT; if (state == ShellIntegration::NOT_DEFAULT_BROWSER) return IDS_OPTIONS_DEFAULTBROWSER_NOTDEFAULT; return IDS_OPTIONS_DEFAULTBROWSER_UNKNOWN; } void BrowserOptionsHandler::SetDefaultBrowserUIState( ShellIntegration::DefaultBrowserUIState state) { int status_string_id; if (state == ShellIntegration::STATE_IS_DEFAULT) status_string_id = IDS_OPTIONS_DEFAULTBROWSER_DEFAULT; else if (state == ShellIntegration::STATE_NOT_DEFAULT) status_string_id = IDS_OPTIONS_DEFAULTBROWSER_NOTDEFAULT; else if (state == ShellIntegration::STATE_UNKNOWN) status_string_id = IDS_OPTIONS_DEFAULTBROWSER_UNKNOWN; else return; // Still processing. SetDefaultBrowserUIString(status_string_id); } void BrowserOptionsHandler::SetDefaultBrowserUIString(int status_string_id) { scoped_ptr<Value> status_string(Value::CreateStringValue( l10n_util::GetStringFUTF16(status_string_id, l10n_util::GetStringUTF16(IDS_PRODUCT_NAME)))); scoped_ptr<Value> is_default(Value::CreateBooleanValue( status_string_id == IDS_OPTIONS_DEFAULTBROWSER_DEFAULT)); dom_ui_->CallJavascriptFunction( L"BrowserOptions.updateDefaultBrowserState", *(status_string.get()), *(is_default.get())); } void BrowserOptionsHandler::OnTemplateURLModelChanged() { if (!template_url_model_ || !template_url_model_->loaded()) return; const TemplateURL* default_url = template_url_model_->GetDefaultSearchProvider(); int default_index = 0; ListValue search_engines; std::vector<const TemplateURL*> model_urls = template_url_model_->GetTemplateURLs(); for (size_t i = 0; i < model_urls.size(); ++i) { if (!model_urls[i]->ShowInDefaultList()) continue; DictionaryValue* entry = new DictionaryValue(); entry->SetString("name", WideToUTF16Hack(model_urls[i]->short_name())); entry->SetInteger("index", i); search_engines.Append(entry); if (model_urls[i] == default_url) default_index = i; } scoped_ptr<Value> default_value(Value::CreateIntegerValue(default_index)); dom_ui_->CallJavascriptFunction(L"BrowserOptions.updateSearchEngines", search_engines, *(default_value.get())); } void BrowserOptionsHandler::SetDefaultSearchEngine(const Value* value) { if (!value || !value->IsType(Value::TYPE_LIST)) { NOTREACHED(); return; } const ListValue* param_values = static_cast<const ListValue*>(value); std::string string_value; if (param_values->GetSize() != 1 || !param_values->GetString(0, &string_value)) { NOTREACHED(); return; } int selected_index; base::StringToInt(string_value, &selected_index); std::vector<const TemplateURL*> model_urls = template_url_model_->GetTemplateURLs(); if (selected_index >= 0 && selected_index < static_cast<int>(model_urls.size())) template_url_model_->SetDefaultSearchProvider(model_urls[selected_index]); } void BrowserOptionsHandler::UpdateSearchEngines() { template_url_model_ = dom_ui_->GetProfile()->GetTemplateURLModel(); if (template_url_model_) { template_url_model_->Load(); template_url_model_->AddObserver(this); OnTemplateURLModelChanged(); } } void BrowserOptionsHandler::UpdateStartupPages() { Profile* profile = dom_ui_->GetProfile(); startup_custom_pages_table_model_.reset( new CustomHomePagesTableModel(profile)); startup_custom_pages_table_model_->SetObserver(this); const SessionStartupPref startup_pref = SessionStartupPref::GetStartupPref(profile->GetPrefs()); startup_custom_pages_table_model_->SetURLs(startup_pref.urls); } void BrowserOptionsHandler::OnModelChanged() { // TODO(stuartmorgan): Add support for showing favicons. ListValue startup_pages; int page_count = startup_custom_pages_table_model_->RowCount(); for (int i = 0; i < page_count; ++i) { DictionaryValue* entry = new DictionaryValue(); entry->SetString("title", WideToUTF16Hack( startup_custom_pages_table_model_->GetText(i, 0))); entry->SetString("tooltip", WideToUTF16Hack( startup_custom_pages_table_model_->GetTooltip(i))); startup_pages.Append(entry); } dom_ui_->CallJavascriptFunction(L"BrowserOptions.updateStartupPages", startup_pages); } void BrowserOptionsHandler::OnItemsChanged(int start, int length) { OnModelChanged(); } void BrowserOptionsHandler::OnItemsAdded(int start, int length) { OnModelChanged(); } void BrowserOptionsHandler::OnItemsRemoved(int start, int length) { OnModelChanged(); } void BrowserOptionsHandler::SetStartupPagesToCurrentPages(const Value* value) { startup_custom_pages_table_model_->SetToCurrentlyOpenPages(); SaveStartupPagesPref(); } void BrowserOptionsHandler::RemoveStartupPages(const Value* value) { if (!value || !value->IsType(Value::TYPE_LIST)) { NOTREACHED(); return; } const ListValue* param_values = static_cast<const ListValue*>(value); for (int i = param_values->GetSize() - 1; i >= 0; --i) { std::string string_value; if (!param_values->GetString(i, &string_value)) { NOTREACHED(); return; } int selected_index; base::StringToInt(string_value, &selected_index); if (selected_index < 0 || selected_index >= startup_custom_pages_table_model_->RowCount()) { NOTREACHED(); return; } startup_custom_pages_table_model_->Remove(selected_index); } SaveStartupPagesPref(); } void BrowserOptionsHandler::SaveStartupPagesPref() { PrefService* prefs = dom_ui_->GetProfile()->GetPrefs(); SessionStartupPref pref = SessionStartupPref::GetStartupPref(prefs); pref.urls = startup_custom_pages_table_model_->GetURLs(); SessionStartupPref::SetStartupPref(prefs, pref); } <|endoftext|>
<commit_before>// Copyright (c) 2009 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/extensions/convert_user_script.h" #include <string> #include <vector> #include "base/base64.h" #include "base/file_path.h" #include "base/file_util.h" #include "base/scoped_temp_dir.h" #include "base/sha2.h" #include "base/string_util.h" #include "chrome/browser/extensions/user_script_master.h" #include "chrome/common/extensions/extension.h" #include "chrome/common/extensions/extension_constants.h" #include "chrome/common/extensions/user_script.h" #include "chrome/common/json_value_serializer.h" #include "googleurl/src/gurl.h" namespace keys = extension_manifest_keys; Extension* ConvertUserScriptToExtension(const FilePath& user_script_path, const GURL& original_url, std::string* error) { std::string content; if (!file_util::ReadFileToString(user_script_path, &content)) { *error = "Could not read source file: " + WideToASCII(user_script_path.ToWStringHack()); return NULL; } UserScript script; if (!UserScriptMaster::ScriptReloader::ParseMetadataHeader(content, &script)) { *error = "Invalid script header."; return NULL; } ScopedTempDir temp_dir; if (!temp_dir.CreateUniqueTempDir()) { *error = "Could not create temporary directory."; return NULL; } // Create the manifest scoped_ptr<DictionaryValue> root(new DictionaryValue); std::string script_name; if (!script.name().empty() && !script.name_space().empty()) script_name = script.name_space() + "/" + script.name(); else script_name = original_url.spec(); // Create the public key. // User scripts are not signed, but the public key for an extension doubles as // its unique identity, and we need one of those. A user script's unique // identity is its namespace+name, so we hash that to create a public key. // There will be no corresponding private key, which means user scripts cannot // be auto-updated, or claimed in the gallery. char raw[base::SHA256_LENGTH] = {0}; std::string key; base::SHA256HashString(script_name, raw, base::SHA256_LENGTH); base::Base64Encode(std::string(raw, base::SHA256_LENGTH), &key); // The script may not have a name field, but we need one for an extension. If // it is missing, use the filename of the original URL. if (!script.name().empty()) root->SetString(keys::kName, script.name()); else root->SetString(keys::kName, original_url.ExtractFileName()); // Not all scripts have a version, but we need one. Default to 1.0 if it is // missing. if (!script.version().empty()) root->SetString(keys::kVersion, script.version()); else root->SetString(keys::kVersion, "1.0"); root->SetString(keys::kDescription, script.description()); root->SetString(keys::kPublicKey, key); root->SetBoolean(keys::kConvertedFromUserScript, true); ListValue* js_files = new ListValue(); js_files->Append(Value::CreateStringValue("script.js")); // If the script provides its own match patterns, we use those. Otherwise, we // generate some using the include globs. ListValue* matches = new ListValue(); if (!script.url_patterns().empty()) { for (size_t i = 0; i < script.url_patterns().size(); ++i) { matches->Append(Value::CreateStringValue( script.url_patterns()[i].GetAsString())); } } else { // TODO(aa): Derive tighter matches where possible. matches->Append(Value::CreateStringValue("http://*/*")); matches->Append(Value::CreateStringValue("https://*/*")); } ListValue* includes = new ListValue(); for (size_t i = 0; i < script.globs().size(); ++i) includes->Append(Value::CreateStringValue(script.globs().at(i))); ListValue* excludes = new ListValue(); for (size_t i = 0; i < script.exclude_globs().size(); ++i) excludes->Append(Value::CreateStringValue(script.exclude_globs().at(i))); DictionaryValue* content_script = new DictionaryValue(); content_script->Set(keys::kMatches, matches); content_script->Set(keys::kIncludeGlobs, includes); content_script->Set(keys::kExcludeGlobs, excludes); content_script->Set(keys::kJs, js_files); ListValue* content_scripts = new ListValue(); content_scripts->Append(content_script); root->Set(keys::kContentScripts, content_scripts); FilePath manifest_path = temp_dir.path().Append( Extension::kManifestFilename); JSONFileValueSerializer serializer(manifest_path); if (!serializer.Serialize(*root)) { *error = "Could not write JSON."; return NULL; } // Write the script file. if (!file_util::CopyFile(user_script_path, temp_dir.path().AppendASCII("script.js"))) { *error = "Could not copy script file."; return NULL; } scoped_ptr<Extension> extension(new Extension(temp_dir.path())); if (!extension->InitFromValue(*root, false, error)) { NOTREACHED() << "Could not init extension " << *error; return NULL; } temp_dir.Take(); // The caller takes ownership of the directory. return extension.release(); } <commit_msg>Pack content scripts in a temp directory in the profile dir.<commit_after>// Copyright (c) 2009 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/extensions/convert_user_script.h" #include <string> #include <vector> #include "base/base64.h" #include "base/file_path.h" #include "base/file_util.h" #include "base/path_service.h" #include "base/scoped_temp_dir.h" #include "base/sha2.h" #include "base/string_util.h" #include "chrome/browser/extensions/user_script_master.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/extensions/extension.h" #include "chrome/common/extensions/extension_constants.h" #include "chrome/common/extensions/user_script.h" #include "chrome/common/json_value_serializer.h" #include "googleurl/src/gurl.h" namespace keys = extension_manifest_keys; Extension* ConvertUserScriptToExtension(const FilePath& user_script_path, const GURL& original_url, std::string* error) { std::string content; if (!file_util::ReadFileToString(user_script_path, &content)) { *error = "Could not read source file: " + WideToASCII(user_script_path.ToWStringHack()); return NULL; } UserScript script; if (!UserScriptMaster::ScriptReloader::ParseMetadataHeader(content, &script)) { *error = "Invalid script header."; return NULL; } FilePath user_data_temp_dir; CHECK(PathService::Get(chrome::DIR_USER_DATA_TEMP, &user_data_temp_dir)); ScopedTempDir temp_dir; if (!temp_dir.CreateUniqueTempDirUnderPath(user_data_temp_dir, false)) { *error = "Could not create temporary directory."; return NULL; } // Create the manifest scoped_ptr<DictionaryValue> root(new DictionaryValue); std::string script_name; if (!script.name().empty() && !script.name_space().empty()) script_name = script.name_space() + "/" + script.name(); else script_name = original_url.spec(); // Create the public key. // User scripts are not signed, but the public key for an extension doubles as // its unique identity, and we need one of those. A user script's unique // identity is its namespace+name, so we hash that to create a public key. // There will be no corresponding private key, which means user scripts cannot // be auto-updated, or claimed in the gallery. char raw[base::SHA256_LENGTH] = {0}; std::string key; base::SHA256HashString(script_name, raw, base::SHA256_LENGTH); base::Base64Encode(std::string(raw, base::SHA256_LENGTH), &key); // The script may not have a name field, but we need one for an extension. If // it is missing, use the filename of the original URL. if (!script.name().empty()) root->SetString(keys::kName, script.name()); else root->SetString(keys::kName, original_url.ExtractFileName()); // Not all scripts have a version, but we need one. Default to 1.0 if it is // missing. if (!script.version().empty()) root->SetString(keys::kVersion, script.version()); else root->SetString(keys::kVersion, "1.0"); root->SetString(keys::kDescription, script.description()); root->SetString(keys::kPublicKey, key); root->SetBoolean(keys::kConvertedFromUserScript, true); ListValue* js_files = new ListValue(); js_files->Append(Value::CreateStringValue("script.js")); // If the script provides its own match patterns, we use those. Otherwise, we // generate some using the include globs. ListValue* matches = new ListValue(); if (!script.url_patterns().empty()) { for (size_t i = 0; i < script.url_patterns().size(); ++i) { matches->Append(Value::CreateStringValue( script.url_patterns()[i].GetAsString())); } } else { // TODO(aa): Derive tighter matches where possible. matches->Append(Value::CreateStringValue("http://*/*")); matches->Append(Value::CreateStringValue("https://*/*")); } ListValue* includes = new ListValue(); for (size_t i = 0; i < script.globs().size(); ++i) includes->Append(Value::CreateStringValue(script.globs().at(i))); ListValue* excludes = new ListValue(); for (size_t i = 0; i < script.exclude_globs().size(); ++i) excludes->Append(Value::CreateStringValue(script.exclude_globs().at(i))); DictionaryValue* content_script = new DictionaryValue(); content_script->Set(keys::kMatches, matches); content_script->Set(keys::kIncludeGlobs, includes); content_script->Set(keys::kExcludeGlobs, excludes); content_script->Set(keys::kJs, js_files); ListValue* content_scripts = new ListValue(); content_scripts->Append(content_script); root->Set(keys::kContentScripts, content_scripts); FilePath manifest_path = temp_dir.path().Append( Extension::kManifestFilename); JSONFileValueSerializer serializer(manifest_path); if (!serializer.Serialize(*root)) { *error = "Could not write JSON."; return NULL; } // Write the script file. if (!file_util::CopyFile(user_script_path, temp_dir.path().AppendASCII("script.js"))) { *error = "Could not copy script file."; return NULL; } scoped_ptr<Extension> extension(new Extension(temp_dir.path())); if (!extension->InitFromValue(*root, false, error)) { NOTREACHED() << "Could not init extension " << *error; return NULL; } temp_dir.Take(); // The caller takes ownership of the directory. return extension.release(); } <|endoftext|>
<commit_before><commit_msg>Fix the problem that file URL is not converted to file path in drag-and-drop on Linux.<commit_after><|endoftext|>
<commit_before><commit_msg>Coverity: Fix an invalidated iterator case and refactor to use the STLDeleteValues helper function.<commit_after><|endoftext|>
<commit_before>//===- llvm/CodeGen/GlobalISel/InstructionSelect.cpp - InstructionSelect ---==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// \file /// This file implements the InstructionSelect class. //===----------------------------------------------------------------------===// #include "llvm/CodeGen/GlobalISel/InstructionSelect.h" #include "llvm/ADT/PostOrderIterator.h" #include "llvm/ADT/Twine.h" #include "llvm/CodeGen/GlobalISel/InstructionSelector.h" #include "llvm/CodeGen/GlobalISel/LegalizerInfo.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/CodeGen/TargetPassConfig.h" #include "llvm/IR/Function.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Debug.h" #include "llvm/Target/TargetSubtargetInfo.h" #define DEBUG_TYPE "instruction-select" using namespace llvm; char InstructionSelect::ID = 0; INITIALIZE_PASS_BEGIN(InstructionSelect, DEBUG_TYPE, "Select target instructions out of generic instructions", false, false) INITIALIZE_PASS_DEPENDENCY(TargetPassConfig) INITIALIZE_PASS_END(InstructionSelect, DEBUG_TYPE, "Select target instructions out of generic instructions", false, false) InstructionSelect::InstructionSelect() : MachineFunctionPass(ID) { initializeInstructionSelectPass(*PassRegistry::getPassRegistry()); } void InstructionSelect::getAnalysisUsage(AnalysisUsage &AU) const { AU.addRequired<TargetPassConfig>(); MachineFunctionPass::getAnalysisUsage(AU); } static void reportSelectionError(const MachineFunction &MF, const MachineInstr *MI, const Twine &Message) { std::string ErrStorage; raw_string_ostream Err(ErrStorage); Err << Message << ":\nIn function: " << MF.getName() << '\n'; if (MI) Err << *MI << '\n'; report_fatal_error(Err.str()); } bool InstructionSelect::runOnMachineFunction(MachineFunction &MF) { // If the ISel pipeline failed, do not bother running that pass. if (MF.getProperties().hasProperty( MachineFunctionProperties::Property::FailedISel)) return false; DEBUG(dbgs() << "Selecting function: " << MF.getName() << '\n'); const TargetPassConfig &TPC = getAnalysis<TargetPassConfig>(); const InstructionSelector *ISel = MF.getSubtarget().getInstructionSelector(); assert(ISel && "Cannot work without InstructionSelector"); // FIXME: freezeReservedRegs is now done in IRTranslator, but there are many // other MF/MFI fields we need to initialize. const MachineRegisterInfo &MRI = MF.getRegInfo(); #ifndef NDEBUG // Check that our input is fully legal: we require the function to have the // Legalized property, so it should be. // FIXME: This should be in the MachineVerifier, but it can't use the // LegalizerInfo as it's currently in the separate GlobalISel library. // The RegBankSelected property is already checked in the verifier. Note // that it has the same layering problem, but we only use inline methods so // end up not needing to link against the GlobalISel library. if (const LegalizerInfo *MLI = MF.getSubtarget().getLegalizerInfo()) for (const MachineBasicBlock &MBB : MF) for (const MachineInstr &MI : MBB) if (isPreISelGenericOpcode(MI.getOpcode()) && !MLI->isLegal(MI, MRI)) reportSelectionError(MF, &MI, "Instruction is not legal"); #endif // FIXME: We could introduce new blocks and will need to fix the outer loop. // Until then, keep track of the number of blocks to assert that we don't. const size_t NumBlocks = MF.size(); bool Failed = false; for (MachineBasicBlock *MBB : post_order(&MF)) { if (MBB->empty()) continue; // Select instructions in reverse block order. We permit erasing so have // to resort to manually iterating and recognizing the begin (rend) case. bool ReachedBegin = false; for (auto MII = std::prev(MBB->end()), Begin = MBB->begin(); !ReachedBegin;) { #ifndef NDEBUG // Keep track of the insertion range for debug printing. const auto AfterIt = std::next(MII); #endif // Select this instruction. MachineInstr &MI = *MII; // And have our iterator point to the next instruction, if there is one. if (MII == Begin) ReachedBegin = true; else --MII; DEBUG(dbgs() << "Selecting: \n " << MI); if (!ISel->select(MI)) { if (TPC.isGlobalISelAbortEnabled()) // FIXME: It would be nice to dump all inserted instructions. It's // not obvious how, esp. considering select() can insert after MI. reportSelectionError(MF, &MI, "Cannot select"); Failed = true; break; } // Dump the range of instructions that MI expanded into. DEBUG({ auto InsertedBegin = ReachedBegin ? MBB->begin() : std::next(MII); dbgs() << "Into:\n"; for (auto &InsertedMI : make_range(InsertedBegin, AfterIt)) dbgs() << " " << InsertedMI; dbgs() << '\n'; }); } } // Now that selection is complete, there are no more generic vregs. Verify // that the size of the now-constrained vreg is unchanged and that it has a // register class. for (auto &VRegToType : MRI.getVRegToType()) { unsigned VReg = VRegToType.first; auto *RC = MRI.getRegClassOrNull(VReg); auto *MI = MRI.def_instr_begin(VReg) == MRI.def_instr_end() ? nullptr : &*MRI.def_instr_begin(VReg); if (!RC) { if (TPC.isGlobalISelAbortEnabled()) reportSelectionError(MF, MI, "VReg as no regclass after selection"); Failed = true; break; } if (VRegToType.second.isValid() && VRegToType.second.getSizeInBits() > (RC->getSize() * 8)) { if (TPC.isGlobalISelAbortEnabled()) reportSelectionError( MF, MI, "VReg has explicit size different from class size"); Failed = true; break; } } MRI.getVRegToType().clear(); if (!TPC.isGlobalISelAbortEnabled() && (Failed || MF.size() != NumBlocks)) { MF.getProperties().set(MachineFunctionProperties::Property::FailedISel); return false; } assert(MF.size() == NumBlocks && "Inserting blocks is not supported yet"); // FIXME: Should we accurately track changes? return true; } <commit_msg>GlobalISel: Fix typo in error message<commit_after>//===- llvm/CodeGen/GlobalISel/InstructionSelect.cpp - InstructionSelect ---==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// \file /// This file implements the InstructionSelect class. //===----------------------------------------------------------------------===// #include "llvm/CodeGen/GlobalISel/InstructionSelect.h" #include "llvm/ADT/PostOrderIterator.h" #include "llvm/ADT/Twine.h" #include "llvm/CodeGen/GlobalISel/InstructionSelector.h" #include "llvm/CodeGen/GlobalISel/LegalizerInfo.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/CodeGen/TargetPassConfig.h" #include "llvm/IR/Function.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Debug.h" #include "llvm/Target/TargetSubtargetInfo.h" #define DEBUG_TYPE "instruction-select" using namespace llvm; char InstructionSelect::ID = 0; INITIALIZE_PASS_BEGIN(InstructionSelect, DEBUG_TYPE, "Select target instructions out of generic instructions", false, false) INITIALIZE_PASS_DEPENDENCY(TargetPassConfig) INITIALIZE_PASS_END(InstructionSelect, DEBUG_TYPE, "Select target instructions out of generic instructions", false, false) InstructionSelect::InstructionSelect() : MachineFunctionPass(ID) { initializeInstructionSelectPass(*PassRegistry::getPassRegistry()); } void InstructionSelect::getAnalysisUsage(AnalysisUsage &AU) const { AU.addRequired<TargetPassConfig>(); MachineFunctionPass::getAnalysisUsage(AU); } static void reportSelectionError(const MachineFunction &MF, const MachineInstr *MI, const Twine &Message) { std::string ErrStorage; raw_string_ostream Err(ErrStorage); Err << Message << ":\nIn function: " << MF.getName() << '\n'; if (MI) Err << *MI << '\n'; report_fatal_error(Err.str()); } bool InstructionSelect::runOnMachineFunction(MachineFunction &MF) { // If the ISel pipeline failed, do not bother running that pass. if (MF.getProperties().hasProperty( MachineFunctionProperties::Property::FailedISel)) return false; DEBUG(dbgs() << "Selecting function: " << MF.getName() << '\n'); const TargetPassConfig &TPC = getAnalysis<TargetPassConfig>(); const InstructionSelector *ISel = MF.getSubtarget().getInstructionSelector(); assert(ISel && "Cannot work without InstructionSelector"); // FIXME: freezeReservedRegs is now done in IRTranslator, but there are many // other MF/MFI fields we need to initialize. const MachineRegisterInfo &MRI = MF.getRegInfo(); #ifndef NDEBUG // Check that our input is fully legal: we require the function to have the // Legalized property, so it should be. // FIXME: This should be in the MachineVerifier, but it can't use the // LegalizerInfo as it's currently in the separate GlobalISel library. // The RegBankSelected property is already checked in the verifier. Note // that it has the same layering problem, but we only use inline methods so // end up not needing to link against the GlobalISel library. if (const LegalizerInfo *MLI = MF.getSubtarget().getLegalizerInfo()) for (const MachineBasicBlock &MBB : MF) for (const MachineInstr &MI : MBB) if (isPreISelGenericOpcode(MI.getOpcode()) && !MLI->isLegal(MI, MRI)) reportSelectionError(MF, &MI, "Instruction is not legal"); #endif // FIXME: We could introduce new blocks and will need to fix the outer loop. // Until then, keep track of the number of blocks to assert that we don't. const size_t NumBlocks = MF.size(); bool Failed = false; for (MachineBasicBlock *MBB : post_order(&MF)) { if (MBB->empty()) continue; // Select instructions in reverse block order. We permit erasing so have // to resort to manually iterating and recognizing the begin (rend) case. bool ReachedBegin = false; for (auto MII = std::prev(MBB->end()), Begin = MBB->begin(); !ReachedBegin;) { #ifndef NDEBUG // Keep track of the insertion range for debug printing. const auto AfterIt = std::next(MII); #endif // Select this instruction. MachineInstr &MI = *MII; // And have our iterator point to the next instruction, if there is one. if (MII == Begin) ReachedBegin = true; else --MII; DEBUG(dbgs() << "Selecting: \n " << MI); if (!ISel->select(MI)) { if (TPC.isGlobalISelAbortEnabled()) // FIXME: It would be nice to dump all inserted instructions. It's // not obvious how, esp. considering select() can insert after MI. reportSelectionError(MF, &MI, "Cannot select"); Failed = true; break; } // Dump the range of instructions that MI expanded into. DEBUG({ auto InsertedBegin = ReachedBegin ? MBB->begin() : std::next(MII); dbgs() << "Into:\n"; for (auto &InsertedMI : make_range(InsertedBegin, AfterIt)) dbgs() << " " << InsertedMI; dbgs() << '\n'; }); } } // Now that selection is complete, there are no more generic vregs. Verify // that the size of the now-constrained vreg is unchanged and that it has a // register class. for (auto &VRegToType : MRI.getVRegToType()) { unsigned VReg = VRegToType.first; auto *RC = MRI.getRegClassOrNull(VReg); auto *MI = MRI.def_instr_begin(VReg) == MRI.def_instr_end() ? nullptr : &*MRI.def_instr_begin(VReg); if (!RC) { if (TPC.isGlobalISelAbortEnabled()) reportSelectionError(MF, MI, "VReg has no regclass after selection"); Failed = true; break; } if (VRegToType.second.isValid() && VRegToType.second.getSizeInBits() > (RC->getSize() * 8)) { if (TPC.isGlobalISelAbortEnabled()) reportSelectionError( MF, MI, "VReg has explicit size different from class size"); Failed = true; break; } } MRI.getVRegToType().clear(); if (!TPC.isGlobalISelAbortEnabled() && (Failed || MF.size() != NumBlocks)) { MF.getProperties().set(MachineFunctionProperties::Property::FailedISel); return false; } assert(MF.size() == NumBlocks && "Inserting blocks is not supported yet"); // FIXME: Should we accurately track changes? return true; } <|endoftext|>
<commit_before>//===- BlackfinISelDAGToDAG.cpp - A dag to dag inst selector for Blackfin -===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines an instruction selector for the Blackfin target. // //===----------------------------------------------------------------------===// #include "Blackfin.h" #include "BlackfinISelLowering.h" #include "BlackfinTargetMachine.h" #include "BlackfinRegisterInfo.h" #include "llvm/Intrinsics.h" #include "llvm/CodeGen/SelectionDAGISel.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/Debug.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; //===----------------------------------------------------------------------===// // Instruction Selector Implementation //===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===// /// BlackfinDAGToDAGISel - Blackfin specific code to select blackfin machine /// instructions for SelectionDAG operations. namespace { class BlackfinDAGToDAGISel : public SelectionDAGISel { /// Subtarget - Keep a pointer to the Blackfin Subtarget around so that we /// can make the right decision when generating code for different targets. //const BlackfinSubtarget &Subtarget; public: BlackfinDAGToDAGISel(BlackfinTargetMachine &TM, CodeGenOpt::Level OptLevel) : SelectionDAGISel(TM, OptLevel) {} virtual void InstructionSelect(); virtual const char *getPassName() const { return "Blackfin DAG->DAG Pattern Instruction Selection"; } // Include the pieces autogenerated from the target description. #include "BlackfinGenDAGISel.inc" private: SDNode *Select(SDValue Op); bool SelectADDRspii(SDValue Op, SDValue Addr, SDValue &Base, SDValue &Offset); // Walk the DAG after instruction selection, fixing register class issues. void FixRegisterClasses(SelectionDAG &DAG); const BlackfinInstrInfo &getInstrInfo() { return *static_cast<const BlackfinTargetMachine&>(TM).getInstrInfo(); } const BlackfinRegisterInfo *getRegisterInfo() { return static_cast<const BlackfinTargetMachine&>(TM).getRegisterInfo(); } }; } // end anonymous namespace FunctionPass *llvm::createBlackfinISelDag(BlackfinTargetMachine &TM, CodeGenOpt::Level OptLevel) { return new BlackfinDAGToDAGISel(TM, OptLevel); } /// InstructionSelect - This callback is invoked by /// SelectionDAGISel when it has created a SelectionDAG for us to codegen. void BlackfinDAGToDAGISel::InstructionSelect() { // Select target instructions for the DAG. SelectRoot(*CurDAG); DEBUG(errs() << "Selected selection DAG before regclass fixup:\n"); DEBUG(CurDAG->dump()); FixRegisterClasses(*CurDAG); } SDNode *BlackfinDAGToDAGISel::Select(SDValue Op) { SDNode *N = Op.getNode(); DebugLoc dl = N->getDebugLoc(); if (N->isMachineOpcode()) return NULL; // Already selected. switch (N->getOpcode()) { default: break; case ISD::FrameIndex: { // Selects to ADDpp FI, 0 which in turn will become ADDimm7 SP, imm or ADDpp // SP, Px int FI = cast<FrameIndexSDNode>(N)->getIndex(); SDValue TFI = CurDAG->getTargetFrameIndex(FI, MVT::i32); return CurDAG->SelectNodeTo(N, BF::ADDpp, MVT::i32, TFI, CurDAG->getTargetConstant(0, MVT::i32)); } } return SelectCode(Op); } bool BlackfinDAGToDAGISel::SelectADDRspii(SDValue Op, SDValue Addr, SDValue &Base, SDValue &Offset) { FrameIndexSDNode *FIN = 0; if ((FIN = dyn_cast<FrameIndexSDNode>(Addr))) { Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), MVT::i32); Offset = CurDAG->getTargetConstant(0, MVT::i32); return true; } if (Addr.getOpcode() == ISD::ADD) { ConstantSDNode *CN = 0; if ((FIN = dyn_cast<FrameIndexSDNode>(Addr.getOperand(0))) && (CN = dyn_cast<ConstantSDNode>(Addr.getOperand(1))) && (CN->getSExtValue() % 4 == 0 && CN->getSExtValue() >= 0)) { // Constant positive word offset from frame index Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), MVT::i32); Offset = CurDAG->getTargetConstant(CN->getSExtValue(), MVT::i32); return true; } } return false; } static inline bool isCC(const TargetRegisterClass *RC) { return RC == &BF::AnyCCRegClass || BF::AnyCCRegClass.hasSubClass(RC); } static inline bool isDCC(const TargetRegisterClass *RC) { return RC == &BF::DRegClass || BF::DRegClass.hasSubClass(RC) || isCC(RC); } static void UpdateNodeOperand(SelectionDAG &DAG, SDNode *N, unsigned Num, SDValue Val) { SmallVector<SDValue, 8> ops(N->op_begin(), N->op_end()); ops[Num] = Val; SDValue New = DAG.UpdateNodeOperands(SDValue(N, 0), ops.data(), ops.size()); DAG.ReplaceAllUsesWith(N, New.getNode()); } // After instruction selection, insert COPY_TO_REGCLASS nodes to help in // choosing the proper register classes. void BlackfinDAGToDAGISel::FixRegisterClasses(SelectionDAG &DAG) { const BlackfinInstrInfo &TII = getInstrInfo(); const BlackfinRegisterInfo *TRI = getRegisterInfo(); DAG.AssignTopologicalOrder(); HandleSDNode Dummy(DAG.getRoot()); for (SelectionDAG::allnodes_iterator NI = DAG.allnodes_begin(); NI != DAG.allnodes_end(); ++NI) { if (NI->use_empty() || !NI->isMachineOpcode()) continue; const TargetInstrDesc &DefTID = TII.get(NI->getMachineOpcode()); for (SDNode::use_iterator UI = NI->use_begin(); !UI.atEnd(); ++UI) { if (!UI->isMachineOpcode()) continue; if (UI.getUse().getResNo() >= DefTID.getNumDefs()) continue; const TargetRegisterClass *DefRC = DefTID.OpInfo[UI.getUse().getResNo()].getRegClass(TRI); const TargetInstrDesc &UseTID = TII.get(UI->getMachineOpcode()); if (UseTID.getNumDefs()+UI.getOperandNo() >= UseTID.getNumOperands()) continue; const TargetRegisterClass *UseRC = UseTID.OpInfo[UseTID.getNumDefs()+UI.getOperandNo()].getRegClass(TRI); if (!DefRC || !UseRC) continue; // We cannot copy CC <-> !(CC/D) if ((isCC(DefRC) && !isDCC(UseRC)) || (isCC(UseRC) && !isDCC(DefRC))) { SDNode *Copy = DAG.getMachineNode(TargetInstrInfo::COPY_TO_REGCLASS, NI->getDebugLoc(), MVT::i32, UI.getUse().get(), DAG.getTargetConstant(BF::DRegClassID, MVT::i32)); UpdateNodeOperand(DAG, *UI, UI.getOperandNo(), SDValue(Copy, 0)); } } } DAG.setRoot(Dummy.getValue()); } <commit_msg>Remove dead variable.<commit_after>//===- BlackfinISelDAGToDAG.cpp - A dag to dag inst selector for Blackfin -===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines an instruction selector for the Blackfin target. // //===----------------------------------------------------------------------===// #include "Blackfin.h" #include "BlackfinISelLowering.h" #include "BlackfinTargetMachine.h" #include "BlackfinRegisterInfo.h" #include "llvm/Intrinsics.h" #include "llvm/CodeGen/SelectionDAGISel.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/Debug.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; //===----------------------------------------------------------------------===// // Instruction Selector Implementation //===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===// /// BlackfinDAGToDAGISel - Blackfin specific code to select blackfin machine /// instructions for SelectionDAG operations. namespace { class BlackfinDAGToDAGISel : public SelectionDAGISel { /// Subtarget - Keep a pointer to the Blackfin Subtarget around so that we /// can make the right decision when generating code for different targets. //const BlackfinSubtarget &Subtarget; public: BlackfinDAGToDAGISel(BlackfinTargetMachine &TM, CodeGenOpt::Level OptLevel) : SelectionDAGISel(TM, OptLevel) {} virtual void InstructionSelect(); virtual const char *getPassName() const { return "Blackfin DAG->DAG Pattern Instruction Selection"; } // Include the pieces autogenerated from the target description. #include "BlackfinGenDAGISel.inc" private: SDNode *Select(SDValue Op); bool SelectADDRspii(SDValue Op, SDValue Addr, SDValue &Base, SDValue &Offset); // Walk the DAG after instruction selection, fixing register class issues. void FixRegisterClasses(SelectionDAG &DAG); const BlackfinInstrInfo &getInstrInfo() { return *static_cast<const BlackfinTargetMachine&>(TM).getInstrInfo(); } const BlackfinRegisterInfo *getRegisterInfo() { return static_cast<const BlackfinTargetMachine&>(TM).getRegisterInfo(); } }; } // end anonymous namespace FunctionPass *llvm::createBlackfinISelDag(BlackfinTargetMachine &TM, CodeGenOpt::Level OptLevel) { return new BlackfinDAGToDAGISel(TM, OptLevel); } /// InstructionSelect - This callback is invoked by /// SelectionDAGISel when it has created a SelectionDAG for us to codegen. void BlackfinDAGToDAGISel::InstructionSelect() { // Select target instructions for the DAG. SelectRoot(*CurDAG); DEBUG(errs() << "Selected selection DAG before regclass fixup:\n"); DEBUG(CurDAG->dump()); FixRegisterClasses(*CurDAG); } SDNode *BlackfinDAGToDAGISel::Select(SDValue Op) { SDNode *N = Op.getNode(); if (N->isMachineOpcode()) return NULL; // Already selected. switch (N->getOpcode()) { default: break; case ISD::FrameIndex: { // Selects to ADDpp FI, 0 which in turn will become ADDimm7 SP, imm or ADDpp // SP, Px int FI = cast<FrameIndexSDNode>(N)->getIndex(); SDValue TFI = CurDAG->getTargetFrameIndex(FI, MVT::i32); return CurDAG->SelectNodeTo(N, BF::ADDpp, MVT::i32, TFI, CurDAG->getTargetConstant(0, MVT::i32)); } } return SelectCode(Op); } bool BlackfinDAGToDAGISel::SelectADDRspii(SDValue Op, SDValue Addr, SDValue &Base, SDValue &Offset) { FrameIndexSDNode *FIN = 0; if ((FIN = dyn_cast<FrameIndexSDNode>(Addr))) { Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), MVT::i32); Offset = CurDAG->getTargetConstant(0, MVT::i32); return true; } if (Addr.getOpcode() == ISD::ADD) { ConstantSDNode *CN = 0; if ((FIN = dyn_cast<FrameIndexSDNode>(Addr.getOperand(0))) && (CN = dyn_cast<ConstantSDNode>(Addr.getOperand(1))) && (CN->getSExtValue() % 4 == 0 && CN->getSExtValue() >= 0)) { // Constant positive word offset from frame index Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), MVT::i32); Offset = CurDAG->getTargetConstant(CN->getSExtValue(), MVT::i32); return true; } } return false; } static inline bool isCC(const TargetRegisterClass *RC) { return RC == &BF::AnyCCRegClass || BF::AnyCCRegClass.hasSubClass(RC); } static inline bool isDCC(const TargetRegisterClass *RC) { return RC == &BF::DRegClass || BF::DRegClass.hasSubClass(RC) || isCC(RC); } static void UpdateNodeOperand(SelectionDAG &DAG, SDNode *N, unsigned Num, SDValue Val) { SmallVector<SDValue, 8> ops(N->op_begin(), N->op_end()); ops[Num] = Val; SDValue New = DAG.UpdateNodeOperands(SDValue(N, 0), ops.data(), ops.size()); DAG.ReplaceAllUsesWith(N, New.getNode()); } // After instruction selection, insert COPY_TO_REGCLASS nodes to help in // choosing the proper register classes. void BlackfinDAGToDAGISel::FixRegisterClasses(SelectionDAG &DAG) { const BlackfinInstrInfo &TII = getInstrInfo(); const BlackfinRegisterInfo *TRI = getRegisterInfo(); DAG.AssignTopologicalOrder(); HandleSDNode Dummy(DAG.getRoot()); for (SelectionDAG::allnodes_iterator NI = DAG.allnodes_begin(); NI != DAG.allnodes_end(); ++NI) { if (NI->use_empty() || !NI->isMachineOpcode()) continue; const TargetInstrDesc &DefTID = TII.get(NI->getMachineOpcode()); for (SDNode::use_iterator UI = NI->use_begin(); !UI.atEnd(); ++UI) { if (!UI->isMachineOpcode()) continue; if (UI.getUse().getResNo() >= DefTID.getNumDefs()) continue; const TargetRegisterClass *DefRC = DefTID.OpInfo[UI.getUse().getResNo()].getRegClass(TRI); const TargetInstrDesc &UseTID = TII.get(UI->getMachineOpcode()); if (UseTID.getNumDefs()+UI.getOperandNo() >= UseTID.getNumOperands()) continue; const TargetRegisterClass *UseRC = UseTID.OpInfo[UseTID.getNumDefs()+UI.getOperandNo()].getRegClass(TRI); if (!DefRC || !UseRC) continue; // We cannot copy CC <-> !(CC/D) if ((isCC(DefRC) && !isDCC(UseRC)) || (isCC(UseRC) && !isDCC(DefRC))) { SDNode *Copy = DAG.getMachineNode(TargetInstrInfo::COPY_TO_REGCLASS, NI->getDebugLoc(), MVT::i32, UI.getUse().get(), DAG.getTargetConstant(BF::DRegClassID, MVT::i32)); UpdateNodeOperand(DAG, *UI, UI.getOperandNo(), SDValue(Copy, 0)); } } } DAG.setRoot(Dummy.getValue()); } <|endoftext|>
<commit_before>/* This file is part of KDE Kontact. Copyright (C) 2003 Cornelius Schumacher <schumacher@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program 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 this program; see the file COPYING. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <qptrlist.h> #include <qwidgetstack.h> #include <qsignal.h> #include <qobjectlist.h> #include <qlabel.h> #include <qpainter.h> #include <qbitmap.h> #include <qfontmetrics.h> #include <qstyle.h> #include <qframe.h> #include <qdrawutil.h> #include <kapplication.h> #include <kconfig.h> #include <klocale.h> #include <kiconloader.h> #include <sidebarextension.h> #include <kdebug.h> #include "mainwindow.h" #include "plugin.h" #include "iconsidepane.h" using namespace Kontact; EntryItem::EntryItem( QListBox *parent, Kontact::Plugin *plugin ) : QListBoxItem( parent ), mPlugin( plugin ) { mPixmap = KGlobal::iconLoader()->loadIcon( plugin->icon(), KIcon::Desktop, 48 ); setCustomHighlighting( true ); setText( plugin->title() ); } EntryItem::~EntryItem() { } int EntryItem::width( const QListBox *listbox) const { int w; if ( text().isEmpty() ) w = mPixmap.width(); else w = QMAX( mPixmap.width(), listbox->fontMetrics().width( text() ) ); return w + 18; } int EntryItem::height( const QListBox *listbox) const { int h; if ( text().isEmpty() ) h = mPixmap.height(); else h = mPixmap.height() + listbox->fontMetrics().lineSpacing(); return h + 4; } void EntryItem::paint( QPainter *p ) { QListBox *box = listBox(); int w = box->viewport()->width(); int y = 2; if ( !mPixmap.isNull() ) { int x = ( w - mPixmap.width() ) / 2; p->drawPixmap( x, y, mPixmap ); } QColor save; if ( isCurrent() || isSelected() ) { save = p->pen().color(); p->setPen(listBox()->colorGroup().brightText()); } if ( !text().isEmpty() ) { QFontMetrics fm = p->fontMetrics(); y += mPixmap.height() + fm.height() - fm.descent(); int x = ( w - fm.width( text() ) ) / 2; p->drawText( x, y, text() ); } // draw sunken if ( isCurrent() || isSelected() ) { p->setPen(save); QColorGroup group = box->colorGroup(); group.setColor( QColorGroup::Dark, Qt::black ); qDrawShadePanel( p, 1, 0, w - 2, height( box ), group, true, 1, 0 ); } } Navigator::Navigator( SidePaneBase *parent, const char *name) : KListBox( parent, name ), mSidePane( parent ) { setSelectionMode( KListBox::Single ); viewport()->setBackgroundMode( PaletteMid ); setHScrollBarMode( QScrollView::AlwaysOff ); setAcceptDrops( true ); connect( this, SIGNAL( currentChanged( QListBoxItem * ) ), SLOT( slotExecuted( QListBoxItem * ) ) ); } QSize Navigator::sizeHint() const { return QSize( 100, 100 ); } void Navigator::setSelected( QListBoxItem *i, bool sel ) { // Reimplmemented to avoid the immediate activation of // the item. might turn out it doesn't work, we check that // an confirm from MainWindow::selectPlugin() if (sel) { EntryItem *entry = static_cast<EntryItem *>( i ); emit pluginActivated( entry->plugin() ); } } void Navigator::updatePlugins( QValueList<Kontact::Plugin*> plugins ) { clear(); int minWidth = 0; QValueList<Kontact::Plugin*>::ConstIterator end = plugins.end(); QValueList<Kontact::Plugin*>::ConstIterator it = plugins.begin(); for ( ; it != end; ++it ) { Kontact::Plugin *plugin = *it; if ( !plugin->showInSideBar() ) continue; EntryItem *item = new EntryItem( this, plugin ); if ( item->width( this ) > minWidth ) minWidth = item->width( this ); } parentWidget()->setFixedWidth( minWidth ); } void Navigator::slotExecuted( QListBoxItem *item ) { if ( !item ) return; EntryItem *entry = static_cast<EntryItem *>( item ); emit pluginActivated( entry->plugin() ); } void Navigator::dragEnterEvent( QDragEnterEvent *event ) { kdDebug() << "Navigator::dragEnterEvent()" << endl; dragMoveEvent( event ); } void Navigator::dragMoveEvent( QDragMoveEvent *event ) { kdDebug() << "Navigator::dragEnterEvent()" << endl; kdDebug() << " Format: " << event->format() << endl; QListBoxItem *item = itemAt( event->pos() ); if ( !item ) { event->accept( false ); return; } EntryItem *entry = static_cast<EntryItem *>( item ); kdDebug() << " PLUGIN: " << entry->plugin()->identifier() << endl; event->accept( entry->plugin()->canDecodeDrag( event ) ); } void Navigator::dropEvent( QDropEvent *event ) { kdDebug() << "Navigator::dropEvent()" << endl; QListBoxItem *item = itemAt( event->pos() ); if ( !item ) { return; } EntryItem *entry = static_cast<EntryItem *>( item ); kdDebug() << " PLUGIN: " << entry->plugin()->identifier() << endl; // Make sure the part is loaded before calling processDropEvent. // Maybe it's better, if that would be done by the plugin. // Hmm, this doesn't work anyway. mSidePane->selectPlugin( entry->plugin() ); entry->plugin()->processDropEvent( event ); } IconSidePane::IconSidePane( Core *core, QWidget *parent, const char *name ) : SidePaneBase( core, parent, name ) { mNavigator = new Navigator( this ); connect( mNavigator, SIGNAL( pluginActivated( Kontact::Plugin * ) ), SIGNAL( pluginSelected( Kontact::Plugin * ) ) ); setAcceptDrops( true ); } IconSidePane::~IconSidePane() { } void IconSidePane::updatePlugins() { mNavigator->updatePlugins( core()->pluginList() ); } void IconSidePane::selectPlugin( Kontact::Plugin *plugin ) { bool blocked = signalsBlocked(); blockSignals( true ); uint i; for ( i = 0; i < mNavigator->count(); ++i ) { EntryItem *item = static_cast<EntryItem *>( mNavigator->item( i ) ); if ( item->plugin() == plugin ) { mNavigator->setCurrentItem( i ); break; } } blockSignals( blocked ); } void IconSidePane::selectPlugin( const QString &name ) { bool blocked = signalsBlocked(); blockSignals( true ); uint i; for ( i = 0; i < mNavigator->count(); ++i ) { EntryItem *item = static_cast<EntryItem *>( mNavigator->item( i ) ); if ( item->plugin()->identifier() == name ) { mNavigator->setCurrentItem( i ); break; } } blockSignals( blocked ); } #include "iconsidepane.moc" // vim: sw=2 sts=2 et tw=80 <commit_msg>Don't try to activate part on drop.<commit_after>/* This file is part of KDE Kontact. Copyright (C) 2003 Cornelius Schumacher <schumacher@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program 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 this program; see the file COPYING. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <qptrlist.h> #include <qwidgetstack.h> #include <qsignal.h> #include <qobjectlist.h> #include <qlabel.h> #include <qpainter.h> #include <qbitmap.h> #include <qfontmetrics.h> #include <qstyle.h> #include <qframe.h> #include <qdrawutil.h> #include <kapplication.h> #include <kconfig.h> #include <klocale.h> #include <kiconloader.h> #include <sidebarextension.h> #include <kdebug.h> #include "mainwindow.h" #include "plugin.h" #include "iconsidepane.h" using namespace Kontact; EntryItem::EntryItem( QListBox *parent, Kontact::Plugin *plugin ) : QListBoxItem( parent ), mPlugin( plugin ) { mPixmap = KGlobal::iconLoader()->loadIcon( plugin->icon(), KIcon::Desktop, 48 ); setCustomHighlighting( true ); setText( plugin->title() ); } EntryItem::~EntryItem() { } int EntryItem::width( const QListBox *listbox) const { int w; if ( text().isEmpty() ) w = mPixmap.width(); else w = QMAX( mPixmap.width(), listbox->fontMetrics().width( text() ) ); return w + 18; } int EntryItem::height( const QListBox *listbox) const { int h; if ( text().isEmpty() ) h = mPixmap.height(); else h = mPixmap.height() + listbox->fontMetrics().lineSpacing(); return h + 4; } void EntryItem::paint( QPainter *p ) { QListBox *box = listBox(); int w = box->viewport()->width(); int y = 2; if ( !mPixmap.isNull() ) { int x = ( w - mPixmap.width() ) / 2; p->drawPixmap( x, y, mPixmap ); } QColor save; if ( isCurrent() || isSelected() ) { save = p->pen().color(); p->setPen(listBox()->colorGroup().brightText()); } if ( !text().isEmpty() ) { QFontMetrics fm = p->fontMetrics(); y += mPixmap.height() + fm.height() - fm.descent(); int x = ( w - fm.width( text() ) ) / 2; p->drawText( x, y, text() ); } // draw sunken if ( isCurrent() || isSelected() ) { p->setPen(save); QColorGroup group = box->colorGroup(); group.setColor( QColorGroup::Dark, Qt::black ); qDrawShadePanel( p, 1, 0, w - 2, height( box ), group, true, 1, 0 ); } } Navigator::Navigator( SidePaneBase *parent, const char *name) : KListBox( parent, name ), mSidePane( parent ) { setSelectionMode( KListBox::Single ); viewport()->setBackgroundMode( PaletteMid ); setHScrollBarMode( QScrollView::AlwaysOff ); setAcceptDrops( true ); connect( this, SIGNAL( currentChanged( QListBoxItem * ) ), SLOT( slotExecuted( QListBoxItem * ) ) ); } QSize Navigator::sizeHint() const { return QSize( 100, 100 ); } void Navigator::setSelected( QListBoxItem *i, bool sel ) { // Reimplmemented to avoid the immediate activation of // the item. might turn out it doesn't work, we check that // an confirm from MainWindow::selectPlugin() if (sel) { EntryItem *entry = static_cast<EntryItem *>( i ); emit pluginActivated( entry->plugin() ); } } void Navigator::updatePlugins( QValueList<Kontact::Plugin*> plugins ) { clear(); int minWidth = 0; QValueList<Kontact::Plugin*>::ConstIterator end = plugins.end(); QValueList<Kontact::Plugin*>::ConstIterator it = plugins.begin(); for ( ; it != end; ++it ) { Kontact::Plugin *plugin = *it; if ( !plugin->showInSideBar() ) continue; EntryItem *item = new EntryItem( this, plugin ); if ( item->width( this ) > minWidth ) minWidth = item->width( this ); } parentWidget()->setFixedWidth( minWidth ); } void Navigator::slotExecuted( QListBoxItem *item ) { if ( !item ) return; EntryItem *entry = static_cast<EntryItem *>( item ); emit pluginActivated( entry->plugin() ); } void Navigator::dragEnterEvent( QDragEnterEvent *event ) { kdDebug() << "Navigator::dragEnterEvent()" << endl; dragMoveEvent( event ); } void Navigator::dragMoveEvent( QDragMoveEvent *event ) { kdDebug() << "Navigator::dragEnterEvent()" << endl; kdDebug() << " Format: " << event->format() << endl; QListBoxItem *item = itemAt( event->pos() ); if ( !item ) { event->accept( false ); return; } EntryItem *entry = static_cast<EntryItem *>( item ); kdDebug() << " PLUGIN: " << entry->plugin()->identifier() << endl; event->accept( entry->plugin()->canDecodeDrag( event ) ); } void Navigator::dropEvent( QDropEvent *event ) { kdDebug() << "Navigator::dropEvent()" << endl; QListBoxItem *item = itemAt( event->pos() ); if ( !item ) { return; } EntryItem *entry = static_cast<EntryItem *>( item ); kdDebug() << " PLUGIN: " << entry->plugin()->identifier() << endl; entry->plugin()->processDropEvent( event ); } IconSidePane::IconSidePane( Core *core, QWidget *parent, const char *name ) : SidePaneBase( core, parent, name ) { mNavigator = new Navigator( this ); connect( mNavigator, SIGNAL( pluginActivated( Kontact::Plugin * ) ), SIGNAL( pluginSelected( Kontact::Plugin * ) ) ); setAcceptDrops( true ); } IconSidePane::~IconSidePane() { } void IconSidePane::updatePlugins() { mNavigator->updatePlugins( core()->pluginList() ); } void IconSidePane::selectPlugin( Kontact::Plugin *plugin ) { bool blocked = signalsBlocked(); blockSignals( true ); uint i; for ( i = 0; i < mNavigator->count(); ++i ) { EntryItem *item = static_cast<EntryItem *>( mNavigator->item( i ) ); if ( item->plugin() == plugin ) { mNavigator->setCurrentItem( i ); break; } } blockSignals( blocked ); } void IconSidePane::selectPlugin( const QString &name ) { bool blocked = signalsBlocked(); blockSignals( true ); uint i; for ( i = 0; i < mNavigator->count(); ++i ) { EntryItem *item = static_cast<EntryItem *>( mNavigator->item( i ) ); if ( item->plugin()->identifier() == name ) { mNavigator->setCurrentItem( i ); break; } } blockSignals( blocked ); } #include "iconsidepane.moc" // vim: sw=2 sts=2 et tw=80 <|endoftext|>
<commit_before>/* This file is part of KDE Kontact. Copyright (C) 2003 Cornelius Schumacher <schumacher@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program 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 this program; see the file COPYING. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <qptrlist.h> #include <qwidgetstack.h> #include <qsignal.h> #include <qobjectlist.h> #include <qlabel.h> #include <qimage.h> #include <qpainter.h> #include <qbitmap.h> #include <qfontmetrics.h> #include <qsignalmapper.h> #include <qstyle.h> #include <qframe.h> #include <qdrawutil.h> #include <kpopupmenu.h> #include <kapplication.h> #include <kdialog.h> #include <klocale.h> #include <kiconloader.h> #include <sidebarextension.h> #include <kdebug.h> #include "mainwindow.h" #include "plugin.h" #include "prefs.h" #include "iconsidepane.h" namespace Kontact { //ugly wrapper class for adding an operator< to the Plugin class class PluginProxy { public: PluginProxy() : mPlugin( 0 ) { } PluginProxy( Plugin *plugin ) : mPlugin( plugin ) { } PluginProxy & operator=( Plugin *plugin ) { mPlugin = plugin; return *this; } bool operator<( PluginProxy &rhs ) const { return mPlugin->weight() < rhs.mPlugin->weight(); } Plugin *plugin() const { return mPlugin; } private: Plugin *mPlugin; }; } //namespace using namespace Kontact; EntryItem::EntryItem( Navigator *parent, Kontact::Plugin *plugin ) : QListBoxItem( parent ), mPlugin( plugin ) { reloadPixmap(); setCustomHighlighting( true ); setText( plugin->title() ); } EntryItem::~EntryItem() { } void EntryItem::reloadPixmap() { int size = (int)navigator()->viewMode(); if ( size != 0 ) mPixmap = KGlobal::iconLoader()->loadIcon( mPlugin->icon(), KIcon::Desktop, size ); else mPixmap = QPixmap(); } Navigator* EntryItem::navigator() const { return static_cast<Navigator*>( listBox() ); } int EntryItem::width( const QListBox *listbox ) const { int w; if ( text().isEmpty() ) w = mPixmap.width(); else if (navigator()->viewMode() > SmallIcons) w = QMAX( (int)navigator()->viewMode(), listbox->fontMetrics().width( text() ) ); else w = (int)navigator()->viewMode() + 4 + listbox->fontMetrics().width( text() ); return w + ( KDialog::marginHint() * 2 ); } int EntryItem::height( const QListBox *listbox ) const { int h; if ( text().isEmpty() ) h = mPixmap.height(); else if (navigator()->viewMode() > SmallIcons) h = (int)navigator()->viewMode() + listbox->fontMetrics().lineSpacing(); else h = QMAX( (int)navigator()->viewMode(), listbox->fontMetrics().lineSpacing() ); return h + 4; } void EntryItem::paint( QPainter *p ) { reloadPixmap(); QListBox *box = listBox(); bool iconAboveText = navigator()->viewMode() > SmallIcons; int w = box->viewport()->width(); int y = 2; // draw selected if ( isCurrent() || isSelected() ) { int h = height( box ); QBrush brush = box->colorGroup().brush( QColorGroup::Highlight ); brush.setColor( brush.color().light( 115 ) ); p->fillRect( 1, 0, w - 2, h - 1, brush ); QPen pen = p->pen(); QPen oldPen = pen; pen.setColor( box->colorGroup().mid() ); p->setPen( pen ); p->drawPoint( 1, 0 ); p->drawPoint( 1, h - 2 ); p->drawPoint( w - 2, 0 ); p->drawPoint( w - 2, h - 2 ); p->setPen( oldPen ); } if ( !mPixmap.isNull() ) { int x = iconAboveText ? ( ( w - mPixmap.width() ) / 2 ) : KDialog::marginHint(); p->drawPixmap( x, y, mPixmap ); } QColor shadowColor = listBox()->colorGroup().background().dark(115); if ( isCurrent() || isSelected() ) { p->setPen( box->colorGroup().highlightedText() ); } if ( !text().isEmpty() ) { QFontMetrics fm = p->fontMetrics(); int x = 0; if (iconAboveText) { x = ( w - fm.width( text() ) ) / 2; y += fm.height() - fm.descent() + mPixmap.height(); } else { x = KDialog::marginHint() + mPixmap.width() + 4; if ( mPixmap.height() < fm.height() ) y += fm.ascent() + fm.leading()/2; else y += mPixmap.height()/2 - fm.height()/2 + fm.ascent(); } if ( isCurrent() || isSelected() ) { p->setPen( box->colorGroup().highlight().dark(115) ); p->drawText( x + ( QApplication::reverseLayout() ? -1 : 1), y + 1, text() ); p->setPen( box->colorGroup().highlightedText() ); } else p->setPen( box->colorGroup().text() ); p->drawText( x, y, text() ); } } Navigator::Navigator( SidePaneBase *parent, const char *name ) : KListBox( parent, name ), mSidePane( parent ) { mViewMode = sizeIntToEnum( Prefs::self()->sidePaneIconSize() ); setSelectionMode( KListBox::Single ); viewport()->setBackgroundMode( PaletteBackground ); setHScrollBarMode( QScrollView::AlwaysOff ); setAcceptDrops( true ); setFocusPolicy( NoFocus ); connect( this, SIGNAL( selectionChanged( QListBoxItem* ) ), SLOT( slotExecuted( QListBoxItem* ) ) ); connect( this, SIGNAL( rightButtonPressed( QListBoxItem*, const QPoint& ) ), SLOT( slotShowRMBMenu( QListBoxItem*, const QPoint& ) ) ); mMapper = new QSignalMapper( this ); connect( mMapper, SIGNAL( mapped( int ) ), SLOT( shortCutSelected( int ) ) ); } QSize Navigator::sizeHint() const { return QSize( 100, 100 ); } void Navigator::setSelected( QListBoxItem *item, bool selected ) { // Reimplemented to avoid the immediate activation of // the item. might turn out it doesn't work, we check that // an confirm from MainWindow::selectPlugin() if ( selected ) { EntryItem *entry = static_cast<EntryItem*>( item ); emit pluginActivated( entry->plugin() ); } } void Navigator::updatePlugins( QValueList<Kontact::Plugin*> plugins_ ) { QValueList<Kontact::PluginProxy> plugins; QValueList<Kontact::Plugin*>::ConstIterator end_ = plugins_.end(); QValueList<Kontact::Plugin*>::ConstIterator it_ = plugins_.begin(); for ( ; it_ != end_; ++it_ ) plugins += PluginProxy( *it_ ); clear(); mActions.setAutoDelete( true ); mActions.clear(); mActions.setAutoDelete( false ); int counter = 0; int minWidth = 0; qBubbleSort( plugins ); QValueList<Kontact::PluginProxy>::ConstIterator end = plugins.end(); QValueList<Kontact::PluginProxy>::ConstIterator it = plugins.begin(); for ( ; it != end; ++it ) { Kontact::Plugin *plugin = ( *it ).plugin(); if ( !plugin->showInSideBar() ) continue; EntryItem *item = new EntryItem( this, plugin ); if ( item->width( this ) > minWidth ) minWidth = item->width( this ); QString name = QString( "CTRL+%1" ).arg( counter + 1 ); KAction *action = new KAction( plugin->title(), KShortcut( name ), mMapper, SLOT( map() ), mSidePane->actionCollection(), name.latin1() ); mMapper->setMapping( action, counter ); counter++; } parentWidget()->setFixedWidth( minWidth ); } void Navigator::dragEnterEvent( QDragEnterEvent *event ) { kdDebug(5600) << "Navigator::dragEnterEvent()" << endl; dragMoveEvent( event ); } void Navigator::dragMoveEvent( QDragMoveEvent *event ) { kdDebug(5600) << "Navigator::dragEnterEvent()" << endl; kdDebug(5600) << " Format: " << event->format() << endl; QListBoxItem *item = itemAt( event->pos() ); if ( !item ) { event->accept( false ); return; } EntryItem *entry = static_cast<EntryItem*>( item ); kdDebug(5600) << " PLUGIN: " << entry->plugin()->identifier() << endl; event->accept( entry->plugin()->canDecodeDrag( event ) ); } void Navigator::dropEvent( QDropEvent *event ) { kdDebug(5600) << "Navigator::dropEvent()" << endl; QListBoxItem *item = itemAt( event->pos() ); if ( !item ) { return; } EntryItem *entry = static_cast<EntryItem*>( item ); kdDebug(5600) << " PLUGIN: " << entry->plugin()->identifier() << endl; entry->plugin()->processDropEvent( event ); } void Navigator::resizeEvent( QResizeEvent *event ) { QListBox::resizeEvent( event ); triggerUpdate( true ); } void Navigator::slotExecuted( QListBoxItem *item ) { if ( !item ) return; EntryItem *entry = static_cast<EntryItem*>( item ); emit pluginActivated( entry->plugin() ); } IconViewMode Navigator::sizeIntToEnum(int size) const { switch ( size ) { case int(LargeIcons): return LargeIcons; break; case int(NormalIcons): return NormalIcons; break; case int(SmallIcons): return SmallIcons; break; case int(TextOnly): return TextOnly; break; default: // Stick with sane values return NormalIcons; kdDebug() << "View mode not implemented!" << endl; break; } } void Navigator::slotShowRMBMenu( QListBoxItem *, const QPoint &pos ) { KPopupMenu menu; menu.insertTitle( i18n( "Icon Size" ) ); menu.insertItem( i18n( "Large" ), (int)LargeIcons ); menu.insertItem( i18n( "Normal" ), (int)NormalIcons ); menu.insertItem( i18n( "Small" ), (int)SmallIcons ); menu.insertItem( i18n( "Text Only" ), (int)TextOnly ); int choice = menu.exec( pos ); if ( choice == -1 ) return; mViewMode = sizeIntToEnum( choice ); Prefs::self()->setSidePaneIconSize( choice ); int maxWidth = 0; QListBoxItem* it = 0; for (int i = 0; (it = item(i)) != 0; ++i) { int width = it->width(this); if (width > maxWidth) maxWidth = width; } parentWidget()->setFixedWidth( maxWidth ); triggerUpdate( true ); } void Navigator::shortCutSelected( int pos ) { setCurrentItem( pos ); } IconSidePane::IconSidePane( Core *core, QWidget *parent, const char *name ) : SidePaneBase( core, parent, name ) { mNavigator = new Navigator( this ); connect( mNavigator, SIGNAL( pluginActivated( Kontact::Plugin* ) ), SIGNAL( pluginSelected( Kontact::Plugin* ) ) ); setAcceptDrops( true ); } IconSidePane::~IconSidePane() { } void IconSidePane::updatePlugins() { mNavigator->updatePlugins( core()->pluginList() ); } void IconSidePane::selectPlugin( Kontact::Plugin *plugin ) { bool blocked = signalsBlocked(); blockSignals( true ); uint i; for ( i = 0; i < mNavigator->count(); ++i ) { EntryItem *item = static_cast<EntryItem*>( mNavigator->item( i ) ); if ( item->plugin() == plugin ) { mNavigator->setCurrentItem( i ); break; } } blockSignals( blocked ); } void IconSidePane::selectPlugin( const QString &name ) { bool blocked = signalsBlocked(); blockSignals( true ); uint i; for ( i = 0; i < mNavigator->count(); ++i ) { EntryItem *item = static_cast<EntryItem*>( mNavigator->item( i ) ); if ( item->plugin()->identifier() == name ) { mNavigator->setCurrentItem( i ); break; } } blockSignals( blocked ); } #include "iconsidepane.moc" // vim: sw=2 sts=2 et tw=80 <commit_msg>spacingHint() for small icons. gives it a nice ballanced look and uses more of the available widget space, too.<commit_after>/* This file is part of KDE Kontact. Copyright (C) 2003 Cornelius Schumacher <schumacher@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program 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 this program; see the file COPYING. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <qptrlist.h> #include <qwidgetstack.h> #include <qsignal.h> #include <qobjectlist.h> #include <qlabel.h> #include <qimage.h> #include <qpainter.h> #include <qbitmap.h> #include <qfontmetrics.h> #include <qsignalmapper.h> #include <qstyle.h> #include <qframe.h> #include <qdrawutil.h> #include <kpopupmenu.h> #include <kapplication.h> #include <kdialog.h> #include <klocale.h> #include <kiconloader.h> #include <sidebarextension.h> #include <kdebug.h> #include "mainwindow.h" #include "plugin.h" #include "prefs.h" #include "iconsidepane.h" namespace Kontact { //ugly wrapper class for adding an operator< to the Plugin class class PluginProxy { public: PluginProxy() : mPlugin( 0 ) { } PluginProxy( Plugin *plugin ) : mPlugin( plugin ) { } PluginProxy & operator=( Plugin *plugin ) { mPlugin = plugin; return *this; } bool operator<( PluginProxy &rhs ) const { return mPlugin->weight() < rhs.mPlugin->weight(); } Plugin *plugin() const { return mPlugin; } private: Plugin *mPlugin; }; } //namespace using namespace Kontact; EntryItem::EntryItem( Navigator *parent, Kontact::Plugin *plugin ) : QListBoxItem( parent ), mPlugin( plugin ) { reloadPixmap(); setCustomHighlighting( true ); setText( plugin->title() ); } EntryItem::~EntryItem() { } void EntryItem::reloadPixmap() { int size = (int)navigator()->viewMode(); if ( size != 0 ) mPixmap = KGlobal::iconLoader()->loadIcon( mPlugin->icon(), KIcon::Desktop, size ); else mPixmap = QPixmap(); } Navigator* EntryItem::navigator() const { return static_cast<Navigator*>( listBox() ); } int EntryItem::width( const QListBox *listbox ) const { int w; if ( text().isEmpty() ) w = mPixmap.width(); else if (navigator()->viewMode() > SmallIcons) w = QMAX( (int)navigator()->viewMode(), listbox->fontMetrics().width( text() ) ); else w = (int)navigator()->viewMode() + 4 + listbox->fontMetrics().width( text() ); return w + ( KDialog::marginHint() * 2 ); } int EntryItem::height( const QListBox *listbox ) const { int h; if ( text().isEmpty() ) h = mPixmap.height() + 4; else if (navigator()->viewMode() > SmallIcons) h = (int)navigator()->viewMode() + listbox->fontMetrics().lineSpacing() + 4; else h = QMAX( (int)navigator()->viewMode(), listbox->fontMetrics().lineSpacing() ) + KDialog::spacingHint() * 2; return h; } void EntryItem::paint( QPainter *p ) { reloadPixmap(); QListBox *box = listBox(); bool iconAboveText = navigator()->viewMode() > SmallIcons; int w = box->viewport()->width(); int y = iconAboveText ? 2 : KDialog::spacingHint(); // draw selected if ( isCurrent() || isSelected() ) { int h = height( box ); QBrush brush = box->colorGroup().brush( QColorGroup::Highlight ); brush.setColor( brush.color().light( 115 ) ); p->fillRect( 1, 0, w - 2, h - 1, brush ); QPen pen = p->pen(); QPen oldPen = pen; pen.setColor( box->colorGroup().mid() ); p->setPen( pen ); p->drawPoint( 1, 0 ); p->drawPoint( 1, h - 2 ); p->drawPoint( w - 2, 0 ); p->drawPoint( w - 2, h - 2 ); p->setPen( oldPen ); } if ( !mPixmap.isNull() ) { int x = iconAboveText ? ( ( w - mPixmap.width() ) / 2 ) : KDialog::marginHint(); p->drawPixmap( x, y, mPixmap ); } QColor shadowColor = listBox()->colorGroup().background().dark(115); if ( isCurrent() || isSelected() ) { p->setPen( box->colorGroup().highlightedText() ); } if ( !text().isEmpty() ) { QFontMetrics fm = p->fontMetrics(); int x = 0; if (iconAboveText) { x = ( w - fm.width( text() ) ) / 2; y += fm.height() - fm.descent() + mPixmap.height(); } else { x = KDialog::marginHint() + mPixmap.width() + 4; if ( mPixmap.height() < fm.height() ) y += fm.ascent() + fm.leading()/2; else y += mPixmap.height()/2 - fm.height()/2 + fm.ascent(); } if ( isCurrent() || isSelected() ) { p->setPen( box->colorGroup().highlight().dark(115) ); p->drawText( x + ( QApplication::reverseLayout() ? -1 : 1), y + 1, text() ); p->setPen( box->colorGroup().highlightedText() ); } else p->setPen( box->colorGroup().text() ); p->drawText( x, y, text() ); } } Navigator::Navigator( SidePaneBase *parent, const char *name ) : KListBox( parent, name ), mSidePane( parent ) { mViewMode = sizeIntToEnum( Prefs::self()->sidePaneIconSize() ); setSelectionMode( KListBox::Single ); viewport()->setBackgroundMode( PaletteBackground ); setHScrollBarMode( QScrollView::AlwaysOff ); setAcceptDrops( true ); setFocusPolicy( NoFocus ); connect( this, SIGNAL( selectionChanged( QListBoxItem* ) ), SLOT( slotExecuted( QListBoxItem* ) ) ); connect( this, SIGNAL( rightButtonPressed( QListBoxItem*, const QPoint& ) ), SLOT( slotShowRMBMenu( QListBoxItem*, const QPoint& ) ) ); mMapper = new QSignalMapper( this ); connect( mMapper, SIGNAL( mapped( int ) ), SLOT( shortCutSelected( int ) ) ); } QSize Navigator::sizeHint() const { return QSize( 100, 100 ); } void Navigator::setSelected( QListBoxItem *item, bool selected ) { // Reimplemented to avoid the immediate activation of // the item. might turn out it doesn't work, we check that // an confirm from MainWindow::selectPlugin() if ( selected ) { EntryItem *entry = static_cast<EntryItem*>( item ); emit pluginActivated( entry->plugin() ); } } void Navigator::updatePlugins( QValueList<Kontact::Plugin*> plugins_ ) { QValueList<Kontact::PluginProxy> plugins; QValueList<Kontact::Plugin*>::ConstIterator end_ = plugins_.end(); QValueList<Kontact::Plugin*>::ConstIterator it_ = plugins_.begin(); for ( ; it_ != end_; ++it_ ) plugins += PluginProxy( *it_ ); clear(); mActions.setAutoDelete( true ); mActions.clear(); mActions.setAutoDelete( false ); int counter = 0; int minWidth = 0; qBubbleSort( plugins ); QValueList<Kontact::PluginProxy>::ConstIterator end = plugins.end(); QValueList<Kontact::PluginProxy>::ConstIterator it = plugins.begin(); for ( ; it != end; ++it ) { Kontact::Plugin *plugin = ( *it ).plugin(); if ( !plugin->showInSideBar() ) continue; EntryItem *item = new EntryItem( this, plugin ); if ( item->width( this ) > minWidth ) minWidth = item->width( this ); QString name = QString( "CTRL+%1" ).arg( counter + 1 ); KAction *action = new KAction( plugin->title(), KShortcut( name ), mMapper, SLOT( map() ), mSidePane->actionCollection(), name.latin1() ); mMapper->setMapping( action, counter ); counter++; } parentWidget()->setFixedWidth( minWidth ); } void Navigator::dragEnterEvent( QDragEnterEvent *event ) { kdDebug(5600) << "Navigator::dragEnterEvent()" << endl; dragMoveEvent( event ); } void Navigator::dragMoveEvent( QDragMoveEvent *event ) { kdDebug(5600) << "Navigator::dragEnterEvent()" << endl; kdDebug(5600) << " Format: " << event->format() << endl; QListBoxItem *item = itemAt( event->pos() ); if ( !item ) { event->accept( false ); return; } EntryItem *entry = static_cast<EntryItem*>( item ); kdDebug(5600) << " PLUGIN: " << entry->plugin()->identifier() << endl; event->accept( entry->plugin()->canDecodeDrag( event ) ); } void Navigator::dropEvent( QDropEvent *event ) { kdDebug(5600) << "Navigator::dropEvent()" << endl; QListBoxItem *item = itemAt( event->pos() ); if ( !item ) { return; } EntryItem *entry = static_cast<EntryItem*>( item ); kdDebug(5600) << " PLUGIN: " << entry->plugin()->identifier() << endl; entry->plugin()->processDropEvent( event ); } void Navigator::resizeEvent( QResizeEvent *event ) { QListBox::resizeEvent( event ); triggerUpdate( true ); } void Navigator::slotExecuted( QListBoxItem *item ) { if ( !item ) return; EntryItem *entry = static_cast<EntryItem*>( item ); emit pluginActivated( entry->plugin() ); } IconViewMode Navigator::sizeIntToEnum(int size) const { switch ( size ) { case int(LargeIcons): return LargeIcons; break; case int(NormalIcons): return NormalIcons; break; case int(SmallIcons): return SmallIcons; break; case int(TextOnly): return TextOnly; break; default: // Stick with sane values return NormalIcons; kdDebug() << "View mode not implemented!" << endl; break; } } void Navigator::slotShowRMBMenu( QListBoxItem *, const QPoint &pos ) { KPopupMenu menu; menu.insertTitle( i18n( "Icon Size" ) ); menu.insertItem( i18n( "Large" ), (int)LargeIcons ); menu.insertItem( i18n( "Normal" ), (int)NormalIcons ); menu.insertItem( i18n( "Small" ), (int)SmallIcons ); menu.insertItem( i18n( "Text Only" ), (int)TextOnly ); int choice = menu.exec( pos ); if ( choice == -1 ) return; mViewMode = sizeIntToEnum( choice ); Prefs::self()->setSidePaneIconSize( choice ); int maxWidth = 0; QListBoxItem* it = 0; for (int i = 0; (it = item(i)) != 0; ++i) { int width = it->width(this); if (width > maxWidth) maxWidth = width; } parentWidget()->setFixedWidth( maxWidth ); triggerUpdate( true ); } void Navigator::shortCutSelected( int pos ) { setCurrentItem( pos ); } IconSidePane::IconSidePane( Core *core, QWidget *parent, const char *name ) : SidePaneBase( core, parent, name ) { mNavigator = new Navigator( this ); connect( mNavigator, SIGNAL( pluginActivated( Kontact::Plugin* ) ), SIGNAL( pluginSelected( Kontact::Plugin* ) ) ); setAcceptDrops( true ); } IconSidePane::~IconSidePane() { } void IconSidePane::updatePlugins() { mNavigator->updatePlugins( core()->pluginList() ); } void IconSidePane::selectPlugin( Kontact::Plugin *plugin ) { bool blocked = signalsBlocked(); blockSignals( true ); uint i; for ( i = 0; i < mNavigator->count(); ++i ) { EntryItem *item = static_cast<EntryItem*>( mNavigator->item( i ) ); if ( item->plugin() == plugin ) { mNavigator->setCurrentItem( i ); break; } } blockSignals( blocked ); } void IconSidePane::selectPlugin( const QString &name ) { bool blocked = signalsBlocked(); blockSignals( true ); uint i; for ( i = 0; i < mNavigator->count(); ++i ) { EntryItem *item = static_cast<EntryItem*>( mNavigator->item( i ) ); if ( item->plugin()->identifier() == name ) { mNavigator->setCurrentItem( i ); break; } } blockSignals( blocked ); } #include "iconsidepane.moc" // vim: sw=2 sts=2 et tw=80 <|endoftext|>
<commit_before>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* Revision 0.02 2005/07/28 A. De Caro: Update format TOF raw data (temporary solution) Correction of few wrong corrispondences between 'software' and 'hardware' numberings Revision 0.01 2005/07/22 A. De Caro Implement methods Next() GetSector(), GetPlate(), GetStrip(), GetPadZ(), GetPadX() */ /////////////////////////////////////////////////////////////////////////////// // // This class provides access to TOF raw data in DDL files. // // It loops over all TOF raw data given by the AliRawReader. // /////////////////////////////////////////////////////////////////////////////// #include "AliLog.h" #include "AliRawReader.h" #include "AliTOFGeometry.h" #include "AliTOFRawStream.h" ClassImp(AliTOFRawStream) //_____________________________________________________________________________ AliTOFRawStream::AliTOFRawStream(AliRawReader* rawReader) { // // create an object to read TOF raw digits // fRawReader = rawReader; fDDL = -1; fTRM = -1; fTDC = -1; fTDCChannel = -1; fTof = -1; fADC = -1; fErrorFlag = -1; //fCounter = -1; // v0.01 fTOFGeometry = new AliTOFGeometry(); fRawReader->Select(5); } //_____________________________________________________________________________ AliTOFRawStream::AliTOFRawStream(const AliTOFRawStream& stream) : TObject(stream) { // // copy constructor // fRawReader = NULL; fDDL = -1; fTRM = -1; fTDC = -1; fTDCChannel = -1; fTof = -1; fADC = -1; fErrorFlag = -1; //fCounter = -1; // v0.01 fTOFGeometry = new AliTOFGeometry(); } //_____________________________________________________________________________ AliTOFRawStream& AliTOFRawStream::operator = (const AliTOFRawStream& stream) { // // assignment operator // fRawReader = stream.fRawReader; fDDL = stream.fDDL; fTRM = stream.fTRM; fTDC = stream.fTDC; fTDCChannel = stream.fTDCChannel; fTof = stream.fTof; fADC = stream.fADC; fErrorFlag = stream.fErrorFlag; //fCounter = stream.fCounter; // v0.01 fTOFGeometry = stream.fTOFGeometry; return *this; } //_____________________________________________________________________________ AliTOFRawStream::~AliTOFRawStream() { // destructor fTOFGeometry = 0; } //_____________________________________________________________________________ Bool_t AliTOFRawStream::Next() { // read the next raw digit // returns kFALSE if there is no digit left //fCounter++; // v0.01 UInt_t data; /* // v0.01 if (fCounter==0) { if (!fRawReader->ReadNextInt(data)) return kFALSE; Int_t dummy = data & 0x007F; // first 7 bits AliInfo(Form("This is the number of the current DDL file %2i",dummy)); } */ if (!fRawReader->ReadNextInt(data)) return kFALSE; fTRM = data & 0x000F; // first 4 bits fTDC = (data >> 4) & 0x001F; // next 5 bits fTDCChannel = (data >> 9) & 0x0007; // next 3 bits fADC = (data >> 12) & 0x000FFFFF; // last 20 bits // v0.01 //fADC = (data >> 12) & 0x00FF; // next 8 bits // v0.02 if (!fRawReader->ReadNextInt(data)) return kFALSE; fErrorFlag = data & 0x00FF; // first 8 bits fTof = (data >> 8) & 0x00FFFFFF; // last 24 bits // v0.01 //fTof = (data >> 8) & 0x0FFF; // next 12 bits // v0.02 fDDL = fRawReader->GetDDLID(); //AliInfo(Form("fDDL %2i,fTRM %2i, fTDC %2i, fTDCChannel %1i",fDDL,fTRM,fTDC,fTDCChannel)); return kTRUE; } //_____________________________________________________________________________ Int_t AliTOFRawStream::GetSector() const { // // Transform the Hardware coordinate to Software coordinate // and also write it in the digit form // Int_t iSector = -1; iSector = (Int_t)((Float_t)fDDL/AliTOFGeometry::NDDL()); return iSector; } //_____________________________________________________________________________ Int_t AliTOFRawStream::GetPlate() const { // // Transform the Hardware coordinate to Software coordinate // and also write it in the digit form // Int_t iPlate = -1; Int_t localDDL = fDDL%AliTOFGeometry::NDDL(); Int_t iPadPerSector = fTDCChannel + AliTOFGeometry::NCh()*(fTDC + AliTOFGeometry::NTdc()*(fTRM + AliTOFGeometry::NTRM()*localDDL)); Int_t iStripPerSector = (Int_t)(iPadPerSector/(Float_t)AliTOFGeometry::NpadX()/(Float_t)AliTOFGeometry::NpadZ()); if (iStripPerSector < fTOFGeometry->NStripC()) iPlate = 0; else if (iStripPerSector>=fTOFGeometry->NStripC() && iStripPerSector< fTOFGeometry->NStripC()+AliTOFGeometry::NStripB()) iPlate = 1; else if (iStripPerSector>=fTOFGeometry->NStripC()+AliTOFGeometry::NStripB() && iStripPerSector< fTOFGeometry->NStripC()+AliTOFGeometry::NStripB()+AliTOFGeometry::NStripA()) iPlate = 2; else if (iStripPerSector>=fTOFGeometry->NStripC()+AliTOFGeometry::NStripB()+AliTOFGeometry::NStripA() && iStripPerSector< fTOFGeometry->NStripC()+AliTOFGeometry::NStripB()+AliTOFGeometry::NStripA()+AliTOFGeometry::NStripB()) iPlate = 3; else if (iStripPerSector>=fTOFGeometry->NStripC()+AliTOFGeometry::NStripB()+AliTOFGeometry::NStripA()+AliTOFGeometry::NStripB() && iStripPerSector< fTOFGeometry->NStripC()+AliTOFGeometry::NStripB()+AliTOFGeometry::NStripA()+AliTOFGeometry::NStripB()+fTOFGeometry->NStripC()) iPlate = 4; else iPlate = -1; return iPlate; } //_____________________________________________________________________________ Int_t AliTOFRawStream::GetStrip() const { // // Transform the Hardware coordinate to Software coordinate // and also write it in the digit form // Int_t iStrip = -1; Int_t localDDL = fDDL%AliTOFGeometry::NDDL(); Int_t iPadPerSector = fTDCChannel + AliTOFGeometry::NCh()*(fTDC + AliTOFGeometry::NTdc()*(fTRM + AliTOFGeometry::NTRM()*localDDL)); Int_t iStripPerSector = (Int_t)(iPadPerSector/(Float_t)AliTOFGeometry::NpadX()/(Float_t)AliTOFGeometry::NpadZ()); if (iStripPerSector < fTOFGeometry->NStripC()) iStrip = iStripPerSector; else if (iStripPerSector >=fTOFGeometry->NStripC() && iStripPerSector < fTOFGeometry->NStripC()+AliTOFGeometry::NStripB()) iStrip = iStripPerSector-fTOFGeometry->NStripC(); else if (iStripPerSector >=fTOFGeometry->NStripC()+AliTOFGeometry::NStripB() && iStripPerSector < fTOFGeometry->NStripC()+AliTOFGeometry::NStripB()+AliTOFGeometry::NStripA()) iStrip = iStripPerSector-fTOFGeometry->NStripC()-AliTOFGeometry::NStripB(); else if (iStripPerSector >=fTOFGeometry->NStripC()+AliTOFGeometry::NStripB()+AliTOFGeometry::NStripA() && iStripPerSector < fTOFGeometry->NStripC()+AliTOFGeometry::NStripB()+AliTOFGeometry::NStripA()+AliTOFGeometry::NStripB()) iStrip = iStripPerSector-fTOFGeometry->NStripC()-AliTOFGeometry::NStripB()-AliTOFGeometry::NStripA(); else if (iStripPerSector >=fTOFGeometry->NStripC()+AliTOFGeometry::NStripB()+AliTOFGeometry::NStripA()+AliTOFGeometry::NStripB() && iStripPerSector < fTOFGeometry->NStripC()+AliTOFGeometry::NStripB()+AliTOFGeometry::NStripA()+AliTOFGeometry::NStripB()+fTOFGeometry->NStripC()) iStrip = iStripPerSector-fTOFGeometry->NStripC()-AliTOFGeometry::NStripB()-AliTOFGeometry::NStripA()-AliTOFGeometry::NStripB(); else iStrip = -1; return iStrip; } //_____________________________________________________________________________ Int_t AliTOFRawStream::GetPadZ() const { // // Transform the Hardware coordinate to Software coordinate // and also write it in the digit form // Int_t iPadZ = -1; Int_t localDDL = fDDL%AliTOFGeometry::NDDL(); Int_t iPadPerSector = fTDCChannel + AliTOFGeometry::NCh()*(fTDC + AliTOFGeometry::NTdc()*(fTRM + AliTOFGeometry::NTRM()*localDDL)); Int_t iStripPerSector = (Int_t)(iPadPerSector/(Float_t)AliTOFGeometry::NpadX()/(Float_t)AliTOFGeometry::NpadZ()); Int_t iPadPerStrip = iPadPerSector-AliTOFGeometry::NpadX()*AliTOFGeometry::NpadZ()*iStripPerSector; iPadZ = iPadPerStrip%AliTOFGeometry::NpadZ(); return iPadZ; } //_____________________________________________________________________________ Int_t AliTOFRawStream::GetPadX() const { // // Transform the Hardware coordinate to Software coordinate // and also write it in the digit form // Int_t iPadX = -1; Int_t localDDL = fDDL%AliTOFGeometry::NDDL(); Int_t iPadPerSector = fTDCChannel + AliTOFGeometry::NCh()*(fTDC + AliTOFGeometry::NTdc()*(fTRM + AliTOFGeometry::NTRM()*localDDL)); Int_t iStripPerSector = (Int_t)(iPadPerSector/(Float_t)AliTOFGeometry::NpadX()/(Float_t)AliTOFGeometry::NpadZ()); Int_t iPadPerStrip = iPadPerSector-AliTOFGeometry::NpadX()*AliTOFGeometry::NpadZ()*iStripPerSector; iPadX = (Int_t)(iPadPerStrip/(Float_t)AliTOFGeometry::NpadZ()); return iPadX; } //_____________________________________________________________________________ <commit_msg>Geometry pointer correction in AliTOFRawStream class<commit_after>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* Revision 0.02 2005/07/28 A. De Caro: Update format TOF raw data (temporary solution) Correction of few wrong corrispondences between 'software' and 'hardware' numberings Revision 0.01 2005/07/22 A. De Caro Implement methods Next() GetSector(), GetPlate(), GetStrip(), GetPadZ(), GetPadX() */ /////////////////////////////////////////////////////////////////////////////// // // This class provides access to TOF raw data in DDL files. // // It loops over all TOF raw data given by the AliRawReader. // /////////////////////////////////////////////////////////////////////////////// #include "AliLog.h" #include "AliRawReader.h" #include "AliTOFGeometry.h" #include "AliTOFGeometryV5.h" #include "AliTOFRawStream.h" ClassImp(AliTOFRawStream) //_____________________________________________________________________________ AliTOFRawStream::AliTOFRawStream(AliRawReader* rawReader) { // // create an object to read TOF raw digits // fRawReader = rawReader; fDDL = -1; fTRM = -1; fTDC = -1; fTDCChannel = -1; fTof = -1; fADC = -1; fErrorFlag = -1; //fCounter = -1; // v0.01 fTOFGeometry = new AliTOFGeometryV5(); fRawReader->Select(5); } //_____________________________________________________________________________ AliTOFRawStream::AliTOFRawStream(const AliTOFRawStream& stream) : TObject(stream) { // // copy constructor // fRawReader = NULL; fDDL = -1; fTRM = -1; fTDC = -1; fTDCChannel = -1; fTof = -1; fADC = -1; fErrorFlag = -1; //fCounter = -1; // v0.01 fTOFGeometry = new AliTOFGeometryV5(); } //_____________________________________________________________________________ AliTOFRawStream& AliTOFRawStream::operator = (const AliTOFRawStream& stream) { // // assignment operator // fRawReader = stream.fRawReader; fDDL = stream.fDDL; fTRM = stream.fTRM; fTDC = stream.fTDC; fTDCChannel = stream.fTDCChannel; fTof = stream.fTof; fADC = stream.fADC; fErrorFlag = stream.fErrorFlag; //fCounter = stream.fCounter; // v0.01 fTOFGeometry = stream.fTOFGeometry; return *this; } //_____________________________________________________________________________ AliTOFRawStream::~AliTOFRawStream() { // destructor fTOFGeometry = 0; } //_____________________________________________________________________________ Bool_t AliTOFRawStream::Next() { // read the next raw digit // returns kFALSE if there is no digit left //fCounter++; // v0.01 UInt_t data; /* // v0.01 if (fCounter==0) { if (!fRawReader->ReadNextInt(data)) return kFALSE; Int_t dummy = data & 0x007F; // first 7 bits AliInfo(Form("This is the number of the current DDL file %2i",dummy)); } */ if (!fRawReader->ReadNextInt(data)) return kFALSE; fTRM = data & 0x000F; // first 4 bits fTDC = (data >> 4) & 0x001F; // next 5 bits fTDCChannel = (data >> 9) & 0x0007; // next 3 bits fADC = (data >> 12) & 0x000FFFFF; // last 20 bits // v0.01 //fADC = (data >> 12) & 0x00FF; // next 8 bits // v0.02 if (!fRawReader->ReadNextInt(data)) return kFALSE; fErrorFlag = data & 0x00FF; // first 8 bits fTof = (data >> 8) & 0x00FFFFFF; // last 24 bits // v0.01 //fTof = (data >> 8) & 0x0FFF; // next 12 bits // v0.02 fDDL = fRawReader->GetDDLID(); //AliInfo(Form("fDDL %2i,fTRM %2i, fTDC %2i, fTDCChannel %1i",fDDL,fTRM,fTDC,fTDCChannel)); return kTRUE; } //_____________________________________________________________________________ Int_t AliTOFRawStream::GetSector() const { // // Transform the Hardware coordinate to Software coordinate // and also write it in the digit form // Int_t iSector = -1; iSector = (Int_t)((Float_t)fDDL/AliTOFGeometry::NDDL()); return iSector; } //_____________________________________________________________________________ Int_t AliTOFRawStream::GetPlate() const { // // Transform the Hardware coordinate to Software coordinate // and also write it in the digit form // Int_t iPlate = -1; Int_t localDDL = fDDL%AliTOFGeometry::NDDL(); Int_t iPadPerSector = fTDCChannel + AliTOFGeometry::NCh()*(fTDC + AliTOFGeometry::NTdc()*(fTRM + AliTOFGeometry::NTRM()*localDDL)); Int_t iStripPerSector = (Int_t)(iPadPerSector/(Float_t)AliTOFGeometry::NpadX()/(Float_t)AliTOFGeometry::NpadZ()); if (iStripPerSector < fTOFGeometry->NStripC()) iPlate = 0; else if (iStripPerSector>=fTOFGeometry->NStripC() && iStripPerSector< fTOFGeometry->NStripC()+AliTOFGeometry::NStripB()) iPlate = 1; else if (iStripPerSector>=fTOFGeometry->NStripC()+AliTOFGeometry::NStripB() && iStripPerSector< fTOFGeometry->NStripC()+AliTOFGeometry::NStripB()+AliTOFGeometry::NStripA()) iPlate = 2; else if (iStripPerSector>=fTOFGeometry->NStripC()+AliTOFGeometry::NStripB()+AliTOFGeometry::NStripA() && iStripPerSector< fTOFGeometry->NStripC()+AliTOFGeometry::NStripB()+AliTOFGeometry::NStripA()+AliTOFGeometry::NStripB()) iPlate = 3; else if (iStripPerSector>=fTOFGeometry->NStripC()+AliTOFGeometry::NStripB()+AliTOFGeometry::NStripA()+AliTOFGeometry::NStripB() && iStripPerSector< fTOFGeometry->NStripC()+AliTOFGeometry::NStripB()+AliTOFGeometry::NStripA()+AliTOFGeometry::NStripB()+fTOFGeometry->NStripC()) iPlate = 4; else iPlate = -1; return iPlate; } //_____________________________________________________________________________ Int_t AliTOFRawStream::GetStrip() const { // // Transform the Hardware coordinate to Software coordinate // and also write it in the digit form // Int_t iStrip = -1; Int_t localDDL = fDDL%AliTOFGeometry::NDDL(); Int_t iPadPerSector = fTDCChannel + AliTOFGeometry::NCh()*(fTDC + AliTOFGeometry::NTdc()*(fTRM + AliTOFGeometry::NTRM()*localDDL)); Int_t iStripPerSector = (Int_t)(iPadPerSector/(Float_t)AliTOFGeometry::NpadX()/(Float_t)AliTOFGeometry::NpadZ()); if (iStripPerSector < fTOFGeometry->NStripC()) iStrip = iStripPerSector; else if (iStripPerSector >=fTOFGeometry->NStripC() && iStripPerSector < fTOFGeometry->NStripC()+AliTOFGeometry::NStripB()) iStrip = iStripPerSector-fTOFGeometry->NStripC(); else if (iStripPerSector >=fTOFGeometry->NStripC()+AliTOFGeometry::NStripB() && iStripPerSector < fTOFGeometry->NStripC()+AliTOFGeometry::NStripB()+AliTOFGeometry::NStripA()) iStrip = iStripPerSector-fTOFGeometry->NStripC()-AliTOFGeometry::NStripB(); else if (iStripPerSector >=fTOFGeometry->NStripC()+AliTOFGeometry::NStripB()+AliTOFGeometry::NStripA() && iStripPerSector < fTOFGeometry->NStripC()+AliTOFGeometry::NStripB()+AliTOFGeometry::NStripA()+AliTOFGeometry::NStripB()) iStrip = iStripPerSector-fTOFGeometry->NStripC()-AliTOFGeometry::NStripB()-AliTOFGeometry::NStripA(); else if (iStripPerSector >=fTOFGeometry->NStripC()+AliTOFGeometry::NStripB()+AliTOFGeometry::NStripA()+AliTOFGeometry::NStripB() && iStripPerSector < fTOFGeometry->NStripC()+AliTOFGeometry::NStripB()+AliTOFGeometry::NStripA()+AliTOFGeometry::NStripB()+fTOFGeometry->NStripC()) iStrip = iStripPerSector-fTOFGeometry->NStripC()-AliTOFGeometry::NStripB()-AliTOFGeometry::NStripA()-AliTOFGeometry::NStripB(); else iStrip = -1; return iStrip; } //_____________________________________________________________________________ Int_t AliTOFRawStream::GetPadZ() const { // // Transform the Hardware coordinate to Software coordinate // and also write it in the digit form // Int_t iPadZ = -1; Int_t localDDL = fDDL%AliTOFGeometry::NDDL(); Int_t iPadPerSector = fTDCChannel + AliTOFGeometry::NCh()*(fTDC + AliTOFGeometry::NTdc()*(fTRM + AliTOFGeometry::NTRM()*localDDL)); Int_t iStripPerSector = (Int_t)(iPadPerSector/(Float_t)AliTOFGeometry::NpadX()/(Float_t)AliTOFGeometry::NpadZ()); Int_t iPadPerStrip = iPadPerSector-AliTOFGeometry::NpadX()*AliTOFGeometry::NpadZ()*iStripPerSector; iPadZ = iPadPerStrip%AliTOFGeometry::NpadZ(); return iPadZ; } //_____________________________________________________________________________ Int_t AliTOFRawStream::GetPadX() const { // // Transform the Hardware coordinate to Software coordinate // and also write it in the digit form // Int_t iPadX = -1; Int_t localDDL = fDDL%AliTOFGeometry::NDDL(); Int_t iPadPerSector = fTDCChannel + AliTOFGeometry::NCh()*(fTDC + AliTOFGeometry::NTdc()*(fTRM + AliTOFGeometry::NTRM()*localDDL)); Int_t iStripPerSector = (Int_t)(iPadPerSector/(Float_t)AliTOFGeometry::NpadX()/(Float_t)AliTOFGeometry::NpadZ()); Int_t iPadPerStrip = iPadPerSector-AliTOFGeometry::NpadX()*AliTOFGeometry::NpadZ()*iStripPerSector; iPadX = (Int_t)(iPadPerStrip/(Float_t)AliTOFGeometry::NpadZ()); return iPadX; } //_____________________________________________________________________________ <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: XMLTextPContext.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: sab $ $Date: 2001-10-18 08:52:34 $ * * 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): _______________________________________ * * ************************************************************************/ #ifdef PCH #include "filt_pch.hxx" #endif #pragma hdrstop // INCLUDE --------------------------------------------------------------- #ifndef _SC_XMLTEXTPCONTEXT_HXX #include "XMLTextPContext.hxx" #endif #ifndef SC_XMLIMPRT_HXX #include "xmlimprt.hxx" #endif #ifndef SC_XMLCELLI_HXX #include "xmlcelli.hxx" #endif #ifndef _XMLOFF_XMLNMSPE_HXX #include <xmloff/xmlnmspe.hxx> #endif #ifndef _XMLOFF_XMLTOKEN_HXX #include <xmloff/xmltoken.hxx> #endif #ifndef _XMLOFF_NMSPMAP_HXX #include <xmloff/nmspmap.hxx> #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef _COM_SUN_STAR_TEXT_XTEXTCURSOR_HPP_ #include <com/sun/star/text/XTextCursor.hpp> #endif using namespace com::sun::star; using namespace xmloff::token; class ScXMLTextTContext : public SvXMLImportContext { const ScXMLImport& GetScImport() const { return (const ScXMLImport&)GetImport(); } ScXMLImport& GetScImport() { return (ScXMLImport&)GetImport(); } public: ScXMLTextTContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList, ScXMLTextPContext* pTextPContext); virtual ~ScXMLTextTContext(); }; ScXMLTextTContext::ScXMLTextTContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList, ScXMLTextPContext* pTextPContext) : SvXMLImportContext( rImport, nPrfx, rLName ) { if (pTextPContext) { sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; rtl::OUString aLocalName; rtl::OUString sValue; for( sal_Int16 i=0; i < nAttrCount; i++ ) { sal_uInt16 nPrefix = GetScImport().GetNamespaceMap().GetKeyByAttrName( xAttrList->getNameByIndex( i ), &aLocalName ); sValue = xAttrList->getValueByIndex( i ); if ((nPrefix == XML_NAMESPACE_TEXT) && IsXMLToken(aLocalName, XML_C)) pTextPContext->AddSpaces(sValue.toInt32()); } } } ScXMLTextTContext::~ScXMLTextTContext() { } //------------------------------------------------------------------ ScXMLTextPContext::ScXMLTextPContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xTempAttrList, ScXMLTableRowCellContext* pTempCellContext) : SvXMLImportContext( rImport, nPrfx, rLName ), pTextPContext(NULL), pCellContext(pTempCellContext), sOUText(), sLName(rLName), xAttrList(xTempAttrList), nPrefix(nPrfx), bIsOwn(sal_True) { // here are no attributes } ScXMLTextPContext::~ScXMLTextPContext() { if (pTextPContext) delete pTextPContext; } void ScXMLTextPContext::AddSpaces(sal_Int32 nSpaceCount) { sal_Char* pChars = new sal_Char[nSpaceCount]; memset(pChars, ' ', nSpaceCount); sOUText.appendAscii(pChars, nSpaceCount); } SvXMLImportContext *ScXMLTextPContext::CreateChildContext( USHORT nTempPrefix, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xTempAttrList ) { SvXMLImportContext *pContext = NULL; if (!pTextPContext && (nTempPrefix == XML_NAMESPACE_TEXT) && IsXMLToken(rLName, XML_S)) pContext = new ScXMLTextTContext( GetScImport(), nTempPrefix, rLName, xTempAttrList, this); else { if (!pTextPContext) { pCellContext->SetCursorOnTextImport(sOUText.makeStringAndClear()); pTextPContext = GetScImport().GetTextImport()->CreateTextChildContext( GetScImport(), nPrefix, sLName, xAttrList); } if (pTextPContext) pContext = pTextPContext->CreateChildContext(nTempPrefix, rLName, xTempAttrList); } if( !pContext ) pContext = new SvXMLImportContext( GetScImport(), nTempPrefix, rLName ); return pContext; } void ScXMLTextPContext::Characters( const ::rtl::OUString& rChars ) { if (!pTextPContext) sOUText.append(rChars); else pTextPContext->Characters(rChars); } void ScXMLTextPContext::EndElement() { if (!pTextPContext) pCellContext->SetString(sOUText.makeStringAndClear()); // GetScImport().GetTextImport()->GetCursor()->setString(sOUText.makeStringAndClear()); else { pTextPContext->EndElement(); GetScImport().SetRemoveLastChar(sal_True); } } <commit_msg>#92553#; if no text:s attribute is given the space count is 1<commit_after>/************************************************************************* * * $RCSfile: XMLTextPContext.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: sab $ $Date: 2001-10-24 10:15:02 $ * * 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): _______________________________________ * * ************************************************************************/ #ifdef PCH #include "filt_pch.hxx" #endif #pragma hdrstop // INCLUDE --------------------------------------------------------------- #ifndef _SC_XMLTEXTPCONTEXT_HXX #include "XMLTextPContext.hxx" #endif #ifndef SC_XMLIMPRT_HXX #include "xmlimprt.hxx" #endif #ifndef SC_XMLCELLI_HXX #include "xmlcelli.hxx" #endif #ifndef _XMLOFF_XMLNMSPE_HXX #include <xmloff/xmlnmspe.hxx> #endif #ifndef _XMLOFF_XMLTOKEN_HXX #include <xmloff/xmltoken.hxx> #endif #ifndef _XMLOFF_NMSPMAP_HXX #include <xmloff/nmspmap.hxx> #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef _COM_SUN_STAR_TEXT_XTEXTCURSOR_HPP_ #include <com/sun/star/text/XTextCursor.hpp> #endif using namespace com::sun::star; using namespace xmloff::token; class ScXMLTextTContext : public SvXMLImportContext { const ScXMLImport& GetScImport() const { return (const ScXMLImport&)GetImport(); } ScXMLImport& GetScImport() { return (ScXMLImport&)GetImport(); } public: ScXMLTextTContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList, ScXMLTextPContext* pTextPContext); virtual ~ScXMLTextTContext(); }; ScXMLTextTContext::ScXMLTextTContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList, ScXMLTextPContext* pTextPContext) : SvXMLImportContext( rImport, nPrfx, rLName ) { if (pTextPContext) { sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; rtl::OUString aLocalName; rtl::OUString sValue; sal_Int32 nCount(1); for( sal_Int16 i=0; i < nAttrCount; i++ ) { sal_uInt16 nPrefix = GetScImport().GetNamespaceMap().GetKeyByAttrName( xAttrList->getNameByIndex( i ), &aLocalName ); sValue = xAttrList->getValueByIndex( i ); if ((nPrefix == XML_NAMESPACE_TEXT) && IsXMLToken(aLocalName, XML_C)) nCount = sValue.toInt32(); } pTextPContext->AddSpaces(nCount); } } ScXMLTextTContext::~ScXMLTextTContext() { } //------------------------------------------------------------------ ScXMLTextPContext::ScXMLTextPContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xTempAttrList, ScXMLTableRowCellContext* pTempCellContext) : SvXMLImportContext( rImport, nPrfx, rLName ), pTextPContext(NULL), pCellContext(pTempCellContext), sOUText(), sLName(rLName), xAttrList(xTempAttrList), nPrefix(nPrfx), bIsOwn(sal_True) { // here are no attributes } ScXMLTextPContext::~ScXMLTextPContext() { if (pTextPContext) delete pTextPContext; } void ScXMLTextPContext::AddSpaces(sal_Int32 nSpaceCount) { sal_Char* pChars = new sal_Char[nSpaceCount]; memset(pChars, ' ', nSpaceCount); sOUText.appendAscii(pChars, nSpaceCount); } SvXMLImportContext *ScXMLTextPContext::CreateChildContext( USHORT nTempPrefix, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xTempAttrList ) { SvXMLImportContext *pContext = NULL; if (!pTextPContext && (nTempPrefix == XML_NAMESPACE_TEXT) && IsXMLToken(rLName, XML_S)) pContext = new ScXMLTextTContext( GetScImport(), nTempPrefix, rLName, xTempAttrList, this); else { if (!pTextPContext) { pCellContext->SetCursorOnTextImport(sOUText.makeStringAndClear()); pTextPContext = GetScImport().GetTextImport()->CreateTextChildContext( GetScImport(), nPrefix, sLName, xAttrList); } if (pTextPContext) pContext = pTextPContext->CreateChildContext(nTempPrefix, rLName, xTempAttrList); } if( !pContext ) pContext = new SvXMLImportContext( GetScImport(), nTempPrefix, rLName ); return pContext; } void ScXMLTextPContext::Characters( const ::rtl::OUString& rChars ) { if (!pTextPContext) sOUText.append(rChars); else pTextPContext->Characters(rChars); } void ScXMLTextPContext::EndElement() { if (!pTextPContext) pCellContext->SetString(sOUText.makeStringAndClear()); // GetScImport().GetTextImport()->GetCursor()->setString(sOUText.makeStringAndClear()); else { pTextPContext->EndElement(); GetScImport().SetRemoveLastChar(sal_True); } } <|endoftext|>
<commit_before>/* * Copyright (C) 2012 Apple Inc. 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. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. 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 "config.h" #include "modules/webdatabase/DatabaseManager.h" #include "bindings/v8/ExceptionMessages.h" #include "bindings/v8/ExceptionState.h" #include "core/dom/ExceptionCode.h" #include "core/dom/ExecutionContext.h" #include "core/dom/ExecutionContextTask.h" #include "platform/Logging.h" #include "modules/webdatabase/AbstractDatabaseServer.h" #include "modules/webdatabase/Database.h" #include "modules/webdatabase/DatabaseBackend.h" #include "modules/webdatabase/DatabaseBackendBase.h" #include "modules/webdatabase/DatabaseBackendSync.h" #include "modules/webdatabase/DatabaseCallback.h" #include "modules/webdatabase/DatabaseClient.h" #include "modules/webdatabase/DatabaseContext.h" #include "modules/webdatabase/DatabaseServer.h" #include "modules/webdatabase/DatabaseSync.h" #include "modules/webdatabase/DatabaseTask.h" #include "platform/weborigin/SecurityOrigin.h" namespace WebCore { DatabaseManager& DatabaseManager::manager() { static DatabaseManager* dbManager = 0; // FIXME: The following is vulnerable to a race between threads. Need to // implement a thread safe on-first-use static initializer. if (!dbManager) dbManager = new DatabaseManager(); return *dbManager; } DatabaseManager::DatabaseManager() #if !ASSERT_DISABLED : m_databaseContextRegisteredCount(0) , m_databaseContextInstanceCount(0) #endif { m_server = new DatabaseServer; ASSERT(m_server); // We should always have a server to work with. } DatabaseManager::~DatabaseManager() { } class DatabaseCreationCallbackTask FINAL : public ExecutionContextTask { public: static PassOwnPtr<DatabaseCreationCallbackTask> create(PassRefPtrWillBeRawPtr<Database> database, PassOwnPtr<DatabaseCallback> creationCallback) { return adoptPtr(new DatabaseCreationCallbackTask(database, creationCallback)); } virtual void performTask(ExecutionContext*) OVERRIDE { m_creationCallback->handleEvent(m_database.get()); } private: DatabaseCreationCallbackTask(PassRefPtrWillBeRawPtr<Database> database, PassOwnPtr<DatabaseCallback> callback) : m_database(database) , m_creationCallback(callback) { } RefPtrWillBePersistent<Database> m_database; OwnPtr<DatabaseCallback> m_creationCallback; }; DatabaseContext* DatabaseManager::existingDatabaseContextFor(ExecutionContext* context) { MutexLocker locker(m_contextMapLock); ASSERT(m_databaseContextRegisteredCount >= 0); ASSERT(m_databaseContextInstanceCount >= 0); ASSERT(m_databaseContextRegisteredCount <= m_databaseContextInstanceCount); #if ENABLE(OILPAN) const Persistent<DatabaseContext>* databaseContext = m_contextMap.get(context); return databaseContext ? databaseContext->get() : 0; #else return m_contextMap.get(context); #endif } DatabaseContext* DatabaseManager::databaseContextFor(ExecutionContext* context) { if (DatabaseContext* databaseContext = existingDatabaseContextFor(context)) return databaseContext; // We don't need to hold a reference returned by DatabaseContext::create // because DatabaseContext::create calls registerDatabaseContext, and the // DatabaseManager holds a reference. return DatabaseContext::create(context).get(); } void DatabaseManager::registerDatabaseContext(DatabaseContext* databaseContext) { MutexLocker locker(m_contextMapLock); ExecutionContext* context = databaseContext->executionContext(); #if ENABLE(OILPAN) m_contextMap.set(context, adoptPtr(new Persistent<DatabaseContext>(databaseContext))); #else m_contextMap.set(context, databaseContext); #endif #if !ASSERT_DISABLED m_databaseContextRegisteredCount++; #endif } void DatabaseManager::unregisterDatabaseContext(DatabaseContext* databaseContext) { MutexLocker locker(m_contextMapLock); ExecutionContext* context = databaseContext->executionContext(); ASSERT(m_contextMap.get(context)); #if !ASSERT_DISABLED m_databaseContextRegisteredCount--; #endif m_contextMap.remove(context); } #if !ASSERT_DISABLED void DatabaseManager::didConstructDatabaseContext() { MutexLocker lock(m_contextMapLock); m_databaseContextInstanceCount++; } void DatabaseManager::didDestructDatabaseContext() { MutexLocker lock(m_contextMapLock); m_databaseContextInstanceCount--; ASSERT(m_databaseContextRegisteredCount <= m_databaseContextInstanceCount); } #endif void DatabaseManager::throwExceptionForDatabaseError(DatabaseError error, const String& errorMessage, ExceptionState& exceptionState) { switch (error) { case DatabaseError::None: return; case DatabaseError::GenericSecurityError: exceptionState.throwSecurityError(errorMessage); return; case DatabaseError::InvalidDatabaseState: exceptionState.throwDOMException(InvalidStateError, errorMessage); return; default: ASSERT_NOT_REACHED(); } } static void logOpenDatabaseError(ExecutionContext* context, const String& name) { WTF_LOG(StorageAPI, "Database %s for origin %s not allowed to be established", name.ascii().data(), context->securityOrigin()->toString().ascii().data()); } PassRefPtrWillBeRawPtr<DatabaseBackendBase> DatabaseManager::openDatabaseBackend(ExecutionContext* context, DatabaseType type, const String& name, const String& expectedVersion, const String& displayName, unsigned long estimatedSize, bool setVersionInNewDatabase, DatabaseError& error, String& errorMessage) { ASSERT(error == DatabaseError::None); RefPtrWillBeRawPtr<DatabaseBackendBase> backend = m_server->openDatabase( databaseContextFor(context)->backend(), type, name, expectedVersion, displayName, estimatedSize, setVersionInNewDatabase, error, errorMessage); if (!backend) { ASSERT(error != DatabaseError::None); switch (error) { case DatabaseError::GenericSecurityError: logOpenDatabaseError(context, name); return nullptr; case DatabaseError::InvalidDatabaseState: logErrorMessage(context, errorMessage); return nullptr; default: ASSERT_NOT_REACHED(); } } return backend.release(); } PassRefPtrWillBeRawPtr<Database> DatabaseManager::openDatabase(ExecutionContext* context, const String& name, const String& expectedVersion, const String& displayName, unsigned long estimatedSize, PassOwnPtr<DatabaseCallback> creationCallback, DatabaseError& error, String& errorMessage) { ASSERT(error == DatabaseError::None); bool setVersionInNewDatabase = !creationCallback; RefPtrWillBeRawPtr<DatabaseBackendBase> backend = openDatabaseBackend(context, DatabaseType::Async, name, expectedVersion, displayName, estimatedSize, setVersionInNewDatabase, error, errorMessage); if (!backend) return nullptr; RefPtrWillBeRawPtr<Database> database = Database::create(context, backend); databaseContextFor(context)->setHasOpenDatabases(); DatabaseClient::from(context)->didOpenDatabase(database, context->securityOrigin()->host(), name, expectedVersion); if (backend->isNew() && creationCallback.get()) { WTF_LOG(StorageAPI, "Scheduling DatabaseCreationCallbackTask for database %p\n", database.get()); database->executionContext()->postTask(DatabaseCreationCallbackTask::create(database, creationCallback)); } ASSERT(database); return database.release(); } PassRefPtrWillBeRawPtr<DatabaseSync> DatabaseManager::openDatabaseSync(ExecutionContext* context, const String& name, const String& expectedVersion, const String& displayName, unsigned long estimatedSize, PassOwnPtr<DatabaseCallback> creationCallback, DatabaseError& error, String& errorMessage) { ASSERT(context->isContextThread()); ASSERT(error == DatabaseError::None); bool setVersionInNewDatabase = !creationCallback; RefPtrWillBeRawPtr<DatabaseBackendBase> backend = openDatabaseBackend(context, DatabaseType::Sync, name, expectedVersion, displayName, estimatedSize, setVersionInNewDatabase, error, errorMessage); if (!backend) return nullptr; RefPtrWillBeRawPtr<DatabaseSync> database = DatabaseSync::create(context, backend); if (backend->isNew() && creationCallback.get()) { WTF_LOG(StorageAPI, "Invoking the creation callback for database %p\n", database.get()); creationCallback->handleEvent(database.get()); } ASSERT(database); return database.release(); } String DatabaseManager::fullPathForDatabase(SecurityOrigin* origin, const String& name, bool createIfDoesNotExist) { return m_server->fullPathForDatabase(origin, name, createIfDoesNotExist); } void DatabaseManager::closeDatabasesImmediately(const String& originIdentifier, const String& name) { m_server->closeDatabasesImmediately(originIdentifier, name); } void DatabaseManager::interruptAllDatabasesForContext(DatabaseContext* databaseContext) { m_server->interruptAllDatabasesForContext(databaseContext->backend()); } void DatabaseManager::logErrorMessage(ExecutionContext* context, const String& message) { context->addConsoleMessage(StorageMessageSource, ErrorMessageLevel, message); } } // namespace WebCore <commit_msg>Fix a race in DatabaseManager::manager.<commit_after>/* * Copyright (C) 2012 Apple Inc. 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. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. 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 "config.h" #include "modules/webdatabase/DatabaseManager.h" #include "bindings/v8/ExceptionMessages.h" #include "bindings/v8/ExceptionState.h" #include "core/dom/ExceptionCode.h" #include "core/dom/ExecutionContext.h" #include "core/dom/ExecutionContextTask.h" #include "platform/Logging.h" #include "modules/webdatabase/AbstractDatabaseServer.h" #include "modules/webdatabase/Database.h" #include "modules/webdatabase/DatabaseBackend.h" #include "modules/webdatabase/DatabaseBackendBase.h" #include "modules/webdatabase/DatabaseBackendSync.h" #include "modules/webdatabase/DatabaseCallback.h" #include "modules/webdatabase/DatabaseClient.h" #include "modules/webdatabase/DatabaseContext.h" #include "modules/webdatabase/DatabaseServer.h" #include "modules/webdatabase/DatabaseSync.h" #include "modules/webdatabase/DatabaseTask.h" #include "platform/weborigin/SecurityOrigin.h" namespace WebCore { DatabaseManager& DatabaseManager::manager() { AtomicallyInitializedStatic(DatabaseManager*, dbManager = new DatabaseManager); return *dbManager; } DatabaseManager::DatabaseManager() #if !ASSERT_DISABLED : m_databaseContextRegisteredCount(0) , m_databaseContextInstanceCount(0) #endif { m_server = new DatabaseServer; ASSERT(m_server); // We should always have a server to work with. } DatabaseManager::~DatabaseManager() { } class DatabaseCreationCallbackTask FINAL : public ExecutionContextTask { public: static PassOwnPtr<DatabaseCreationCallbackTask> create(PassRefPtrWillBeRawPtr<Database> database, PassOwnPtr<DatabaseCallback> creationCallback) { return adoptPtr(new DatabaseCreationCallbackTask(database, creationCallback)); } virtual void performTask(ExecutionContext*) OVERRIDE { m_creationCallback->handleEvent(m_database.get()); } private: DatabaseCreationCallbackTask(PassRefPtrWillBeRawPtr<Database> database, PassOwnPtr<DatabaseCallback> callback) : m_database(database) , m_creationCallback(callback) { } RefPtrWillBePersistent<Database> m_database; OwnPtr<DatabaseCallback> m_creationCallback; }; DatabaseContext* DatabaseManager::existingDatabaseContextFor(ExecutionContext* context) { MutexLocker locker(m_contextMapLock); ASSERT(m_databaseContextRegisteredCount >= 0); ASSERT(m_databaseContextInstanceCount >= 0); ASSERT(m_databaseContextRegisteredCount <= m_databaseContextInstanceCount); #if ENABLE(OILPAN) const Persistent<DatabaseContext>* databaseContext = m_contextMap.get(context); return databaseContext ? databaseContext->get() : 0; #else return m_contextMap.get(context); #endif } DatabaseContext* DatabaseManager::databaseContextFor(ExecutionContext* context) { if (DatabaseContext* databaseContext = existingDatabaseContextFor(context)) return databaseContext; // We don't need to hold a reference returned by DatabaseContext::create // because DatabaseContext::create calls registerDatabaseContext, and the // DatabaseManager holds a reference. return DatabaseContext::create(context).get(); } void DatabaseManager::registerDatabaseContext(DatabaseContext* databaseContext) { MutexLocker locker(m_contextMapLock); ExecutionContext* context = databaseContext->executionContext(); #if ENABLE(OILPAN) m_contextMap.set(context, adoptPtr(new Persistent<DatabaseContext>(databaseContext))); #else m_contextMap.set(context, databaseContext); #endif #if !ASSERT_DISABLED m_databaseContextRegisteredCount++; #endif } void DatabaseManager::unregisterDatabaseContext(DatabaseContext* databaseContext) { MutexLocker locker(m_contextMapLock); ExecutionContext* context = databaseContext->executionContext(); ASSERT(m_contextMap.get(context)); #if !ASSERT_DISABLED m_databaseContextRegisteredCount--; #endif m_contextMap.remove(context); } #if !ASSERT_DISABLED void DatabaseManager::didConstructDatabaseContext() { MutexLocker lock(m_contextMapLock); m_databaseContextInstanceCount++; } void DatabaseManager::didDestructDatabaseContext() { MutexLocker lock(m_contextMapLock); m_databaseContextInstanceCount--; ASSERT(m_databaseContextRegisteredCount <= m_databaseContextInstanceCount); } #endif void DatabaseManager::throwExceptionForDatabaseError(DatabaseError error, const String& errorMessage, ExceptionState& exceptionState) { switch (error) { case DatabaseError::None: return; case DatabaseError::GenericSecurityError: exceptionState.throwSecurityError(errorMessage); return; case DatabaseError::InvalidDatabaseState: exceptionState.throwDOMException(InvalidStateError, errorMessage); return; default: ASSERT_NOT_REACHED(); } } static void logOpenDatabaseError(ExecutionContext* context, const String& name) { WTF_LOG(StorageAPI, "Database %s for origin %s not allowed to be established", name.ascii().data(), context->securityOrigin()->toString().ascii().data()); } PassRefPtrWillBeRawPtr<DatabaseBackendBase> DatabaseManager::openDatabaseBackend(ExecutionContext* context, DatabaseType type, const String& name, const String& expectedVersion, const String& displayName, unsigned long estimatedSize, bool setVersionInNewDatabase, DatabaseError& error, String& errorMessage) { ASSERT(error == DatabaseError::None); RefPtrWillBeRawPtr<DatabaseBackendBase> backend = m_server->openDatabase( databaseContextFor(context)->backend(), type, name, expectedVersion, displayName, estimatedSize, setVersionInNewDatabase, error, errorMessage); if (!backend) { ASSERT(error != DatabaseError::None); switch (error) { case DatabaseError::GenericSecurityError: logOpenDatabaseError(context, name); return nullptr; case DatabaseError::InvalidDatabaseState: logErrorMessage(context, errorMessage); return nullptr; default: ASSERT_NOT_REACHED(); } } return backend.release(); } PassRefPtrWillBeRawPtr<Database> DatabaseManager::openDatabase(ExecutionContext* context, const String& name, const String& expectedVersion, const String& displayName, unsigned long estimatedSize, PassOwnPtr<DatabaseCallback> creationCallback, DatabaseError& error, String& errorMessage) { ASSERT(error == DatabaseError::None); bool setVersionInNewDatabase = !creationCallback; RefPtrWillBeRawPtr<DatabaseBackendBase> backend = openDatabaseBackend(context, DatabaseType::Async, name, expectedVersion, displayName, estimatedSize, setVersionInNewDatabase, error, errorMessage); if (!backend) return nullptr; RefPtrWillBeRawPtr<Database> database = Database::create(context, backend); databaseContextFor(context)->setHasOpenDatabases(); DatabaseClient::from(context)->didOpenDatabase(database, context->securityOrigin()->host(), name, expectedVersion); if (backend->isNew() && creationCallback.get()) { WTF_LOG(StorageAPI, "Scheduling DatabaseCreationCallbackTask for database %p\n", database.get()); database->executionContext()->postTask(DatabaseCreationCallbackTask::create(database, creationCallback)); } ASSERT(database); return database.release(); } PassRefPtrWillBeRawPtr<DatabaseSync> DatabaseManager::openDatabaseSync(ExecutionContext* context, const String& name, const String& expectedVersion, const String& displayName, unsigned long estimatedSize, PassOwnPtr<DatabaseCallback> creationCallback, DatabaseError& error, String& errorMessage) { ASSERT(context->isContextThread()); ASSERT(error == DatabaseError::None); bool setVersionInNewDatabase = !creationCallback; RefPtrWillBeRawPtr<DatabaseBackendBase> backend = openDatabaseBackend(context, DatabaseType::Sync, name, expectedVersion, displayName, estimatedSize, setVersionInNewDatabase, error, errorMessage); if (!backend) return nullptr; RefPtrWillBeRawPtr<DatabaseSync> database = DatabaseSync::create(context, backend); if (backend->isNew() && creationCallback.get()) { WTF_LOG(StorageAPI, "Invoking the creation callback for database %p\n", database.get()); creationCallback->handleEvent(database.get()); } ASSERT(database); return database.release(); } String DatabaseManager::fullPathForDatabase(SecurityOrigin* origin, const String& name, bool createIfDoesNotExist) { return m_server->fullPathForDatabase(origin, name, createIfDoesNotExist); } void DatabaseManager::closeDatabasesImmediately(const String& originIdentifier, const String& name) { m_server->closeDatabasesImmediately(originIdentifier, name); } void DatabaseManager::interruptAllDatabasesForContext(DatabaseContext* databaseContext) { m_server->interruptAllDatabasesForContext(databaseContext->backend()); } void DatabaseManager::logErrorMessage(ExecutionContext* context, const String& message) { context->addConsoleMessage(StorageMessageSource, ErrorMessageLevel, message); } } // namespace WebCore <|endoftext|>
<commit_before> #include "rtkTestConfiguration.h" #include "rtkThreeDCircularProjectionGeometryXMLFile.h" #include "rtkRayBoxIntersectionImageFilter.h" #include "rtkSheppLoganPhantomFilter.h" #include "rtkDrawSheppLoganFilter.h" #include "rtkConstantImageSource.h" #ifdef USE_CUDA # include "rtkCudaForwardProjectionImageFilter.h" #else # include "rtkJosephForwardProjectionImageFilter.h" #endif template<class TImage1, class TImage2> #if FAST_TESTS_NO_CHECKS void CheckImageQuality(typename TImage::Pointer itkNotUsed(recon), typename TImage::Pointer itkNotUsed(ref)) { } #else void CheckImageQuality(typename TImage1::Pointer recon, typename TImage2::Pointer ref) { typedef itk::ImageRegionConstIterator<TImage1> ImageIteratorType1; typedef itk::ImageRegionConstIterator<TImage2> ImageIteratorType2; ImageIteratorType1 itTest( recon, recon->GetBufferedRegion() ); ImageIteratorType2 itRef( ref, ref->GetBufferedRegion() ); typedef double ErrorType; ErrorType TestError = 0.; ErrorType EnerError = 0.; itTest.GoToBegin(); itRef.GoToBegin(); while( !itRef.IsAtEnd() ) { typename TImage1::PixelType TestVal = itTest.Get(); typename TImage2::PixelType RefVal = itRef.Get(); if( TestVal != RefVal ) { TestError += vcl_abs(RefVal - TestVal); EnerError += vcl_pow(ErrorType(RefVal - TestVal), 2.); } ++itTest; ++itRef; } // Error per Pixel ErrorType ErrorPerPixel = TestError/recon->GetBufferedRegion().GetNumberOfPixels(); std::cout << "\nError per Pixel = " << ErrorPerPixel << std::endl; // MSE ErrorType MSE = EnerError/ref->GetBufferedRegion().GetNumberOfPixels(); std::cout << "MSE = " << MSE << std::endl; // PSNR ErrorType PSNR = 20*log10(255.0) - 10*log10(MSE); std::cout << "PSNR = " << PSNR << "dB" << std::endl; // QI ErrorType QI = (255.0-ErrorPerPixel)/255.0; std::cout << "QI = " << QI << std::endl; // Checking results if (ErrorPerPixel > 1.28) { std::cerr << "Test Failed, Error per pixel not valid! " << ErrorPerPixel << " instead of 1.28" << std::endl; //exit( EXIT_FAILURE); } if (PSNR < 44.) { std::cerr << "Test Failed, PSNR not valid! " << PSNR << " instead of 44" << std::endl; //exit( EXIT_FAILURE); } } #endif int main(int , char** ) { const unsigned int Dimension = 3; typedef float OutputPixelType; #ifdef USE_CUDA typedef itk::CudaImage< OutputPixelType, Dimension > OutputImageType; #else typedef itk::Image< OutputPixelType, Dimension > OutputImageType; #endif typedef itk::Image< OutputPixelType, Dimension > OutputImageType2; typedef itk::Vector<double, 3> VectorType; #if FAST_TESTS_NO_CHECKS const unsigned int NumberOfProjectionImages = 3; #else const unsigned int NumberOfProjectionImages = 45; #endif // Constant image sources typedef rtk::ConstantImageSource< OutputImageType > ConstantImageSourceType; ConstantImageSourceType::PointType origin; ConstantImageSourceType::SizeType size; ConstantImageSourceType::SpacingType spacing; // The test projects a volume filled with ones. The forward projector should // then return the intersection of the ray with the box and it is compared // with the analytical intersection of a box with a ray. // Create Joseph Forward Projector volume input. const ConstantImageSourceType::Pointer volInput = ConstantImageSourceType::New(); origin[0] = -126; origin[1] = -126; origin[2] = -126; #if FAST_TESTS_NO_CHECKS size[0] = 2; size[1] = 2; size[2] = 2; spacing[0] = 252.; spacing[1] = 252.; spacing[2] = 252.; #else size[0] = 64; size[1] = 64; size[2] = 64; spacing[0] = 4.; spacing[1] = 4.; spacing[2] = 4.; #endif volInput->SetOrigin( origin ); volInput->SetSpacing( spacing ); volInput->SetSize( size ); volInput->SetConstant( 1. ); volInput->UpdateOutputInformation(); // Initialization Volume, it is used in the Joseph Forward Projector and in the // Ray Box Intersection Filter in order to initialize the stack of projections. const ConstantImageSourceType::Pointer projInput = ConstantImageSourceType::New(); size[2] = NumberOfProjectionImages; projInput->SetOrigin( origin ); projInput->SetSpacing( spacing ); projInput->SetSize( size ); projInput->SetConstant( 0. ); projInput->Update(); // Joseph Forward Projection filter #ifdef USE_CUDA typedef rtk::CudaForwardProjectionImageFilter JFPType; #else typedef rtk::JosephForwardProjectionImageFilter<OutputImageType, OutputImageType> JFPType; #endif JFPType::Pointer jfp = JFPType::New(); jfp->InPlaceOff(); jfp->SetInput( projInput->GetOutput() ); jfp->SetInput( 1, volInput->GetOutput() ); // Ray Box Intersection filter (reference) typedef rtk::RayBoxIntersectionImageFilter<OutputImageType2, OutputImageType2> RBIType; RBIType::Pointer rbi = RBIType::New(); rbi->InPlaceOff(); rbi->SetInput( projInput->GetOutput() ); VectorType boxMin, boxMax; boxMin[0] = -126.0; boxMin[1] = -126.0; boxMin[2] = -126.0; boxMax[0] = 126.0; boxMax[1] = 126.0; boxMax[2] = 47.6; rbi->SetBoxMin(boxMin); rbi->SetBoxMax(boxMax); std::cout << "\n\n****** Case 1: inner ray source ******" << std::endl; // The circle is divided in 4 quarters for(int q=0; q<4; q++) { // Geometry typedef rtk::ThreeDCircularProjectionGeometry GeometryType; GeometryType::Pointer geometry = GeometryType::New(); for(unsigned int i=0; i<NumberOfProjectionImages;i++) { const double angle = -45. + i*2.; geometry->AddProjection(47.6 / vcl_cos(angle*itk::Math::pi/180.), 1000., q*90+angle); } if(q==0) { rbi->SetGeometry( geometry ); rbi->Update(); } jfp->SetGeometry(geometry); jfp->Update(); CheckImageQuality<OutputImageType2, OutputImageType>(rbi->GetOutput(), jfp->GetOutput()); std::cout << "\n\nTest of quarter #" << q << " PASSED! " << std::endl; } std::cout << "\n\n****** Case 2: outer ray source ******" << std::endl; boxMax[2] = 126.0; rbi->SetBoxMax(boxMax); // Geometry typedef rtk::ThreeDCircularProjectionGeometry GeometryType; GeometryType::Pointer geometry = GeometryType::New(); for(unsigned int i=0; i<NumberOfProjectionImages; i++) geometry->AddProjection(500., 1000., i*8.); rbi->SetGeometry( geometry ); rbi->Update(); jfp->SetGeometry( geometry ); jfp->Update(); CheckImageQuality<OutputImageType2, OutputImageType>(rbi->GetOutput(), jfp->GetOutput()); std::cout << "\n\nTest PASSED! " << std::endl; std::cout << "\n\n****** Case 3: Shepp-Logan, outer ray source ******" << std::endl; // Create Shepp Logan reference projections typedef rtk::SheppLoganPhantomFilter<OutputImageType2, OutputImageType2> SLPType; SLPType::Pointer slp = SLPType::New(); slp->InPlaceOff(); slp->SetInput( projInput->GetOutput() ); slp->SetGeometry(geometry); slp->Update(); // Create a Shepp Logan reference volume (finer resolution) origin.Fill(-127); size.Fill(128); spacing.Fill(2.); volInput->SetOrigin( origin ); volInput->SetSpacing( spacing ); volInput->SetSize( size ); volInput->SetConstant( 0. ); typedef rtk::DrawSheppLoganFilter<OutputImageType2, OutputImageType> DSLType; DSLType::Pointer dsl = DSLType::New(); dsl->InPlaceOff(); dsl->SetInput( volInput->GetOutput() ); dsl->Update(); // Forward projection jfp->SetInput( 1, dsl->GetOutput() ); jfp->Update(); CheckImageQuality<OutputImageType2, OutputImageType>(slp->GetOutput(), jfp->GetOutput()); std::cout << "\n\nTest PASSED! " << std::endl; std::cout << "\n\n****** Case 4: Shepp-Logan, inner ray source ******" << std::endl; geometry = GeometryType::New(); for(unsigned int i=0; i<NumberOfProjectionImages; i++) geometry->AddProjection(120., 1000., i*8.); slp->SetGeometry(geometry); slp->Update(); jfp->SetGeometry( geometry ); jfp->Update(); CheckImageQuality<OutputImageType2, OutputImageType>(slp->GetOutput(), jfp->GetOutput()); std::cout << "\n\nTest PASSED! " << std::endl; return EXIT_SUCCESS; } <commit_msg>Fixed compilation error (wrong copy pasting)<commit_after> #include "rtkTestConfiguration.h" #include "rtkThreeDCircularProjectionGeometryXMLFile.h" #include "rtkRayBoxIntersectionImageFilter.h" #include "rtkSheppLoganPhantomFilter.h" #include "rtkDrawSheppLoganFilter.h" #include "rtkConstantImageSource.h" #ifdef USE_CUDA # include "rtkCudaForwardProjectionImageFilter.h" #else # include "rtkJosephForwardProjectionImageFilter.h" #endif template<class TImage1, class TImage2> #if FAST_TESTS_NO_CHECKS void CheckImageQuality(typename TImage1::Pointer itkNotUsed(recon), typename TImage2::Pointer itkNotUsed(ref)) { } #else void CheckImageQuality(typename TImage1::Pointer recon, typename TImage2::Pointer ref) { typedef itk::ImageRegionConstIterator<TImage1> ImageIteratorType1; typedef itk::ImageRegionConstIterator<TImage2> ImageIteratorType2; ImageIteratorType1 itTest( recon, recon->GetBufferedRegion() ); ImageIteratorType2 itRef( ref, ref->GetBufferedRegion() ); typedef double ErrorType; ErrorType TestError = 0.; ErrorType EnerError = 0.; itTest.GoToBegin(); itRef.GoToBegin(); while( !itRef.IsAtEnd() ) { typename TImage1::PixelType TestVal = itTest.Get(); typename TImage2::PixelType RefVal = itRef.Get(); if( TestVal != RefVal ) { TestError += vcl_abs(RefVal - TestVal); EnerError += vcl_pow(ErrorType(RefVal - TestVal), 2.); } ++itTest; ++itRef; } // Error per Pixel ErrorType ErrorPerPixel = TestError/recon->GetBufferedRegion().GetNumberOfPixels(); std::cout << "\nError per Pixel = " << ErrorPerPixel << std::endl; // MSE ErrorType MSE = EnerError/ref->GetBufferedRegion().GetNumberOfPixels(); std::cout << "MSE = " << MSE << std::endl; // PSNR ErrorType PSNR = 20*log10(255.0) - 10*log10(MSE); std::cout << "PSNR = " << PSNR << "dB" << std::endl; // QI ErrorType QI = (255.0-ErrorPerPixel)/255.0; std::cout << "QI = " << QI << std::endl; // Checking results if (ErrorPerPixel > 1.28) { std::cerr << "Test Failed, Error per pixel not valid! " << ErrorPerPixel << " instead of 1.28" << std::endl; //exit( EXIT_FAILURE); } if (PSNR < 44.) { std::cerr << "Test Failed, PSNR not valid! " << PSNR << " instead of 44" << std::endl; //exit( EXIT_FAILURE); } } #endif int main(int , char** ) { const unsigned int Dimension = 3; typedef float OutputPixelType; #ifdef USE_CUDA typedef itk::CudaImage< OutputPixelType, Dimension > OutputImageType; #else typedef itk::Image< OutputPixelType, Dimension > OutputImageType; #endif typedef itk::Image< OutputPixelType, Dimension > OutputImageType2; typedef itk::Vector<double, 3> VectorType; #if FAST_TESTS_NO_CHECKS const unsigned int NumberOfProjectionImages = 3; #else const unsigned int NumberOfProjectionImages = 45; #endif // Constant image sources typedef rtk::ConstantImageSource< OutputImageType > ConstantImageSourceType; ConstantImageSourceType::PointType origin; ConstantImageSourceType::SizeType size; ConstantImageSourceType::SpacingType spacing; // The test projects a volume filled with ones. The forward projector should // then return the intersection of the ray with the box and it is compared // with the analytical intersection of a box with a ray. // Create Joseph Forward Projector volume input. const ConstantImageSourceType::Pointer volInput = ConstantImageSourceType::New(); origin[0] = -126; origin[1] = -126; origin[2] = -126; #if FAST_TESTS_NO_CHECKS size[0] = 2; size[1] = 2; size[2] = 2; spacing[0] = 252.; spacing[1] = 252.; spacing[2] = 252.; #else size[0] = 64; size[1] = 64; size[2] = 64; spacing[0] = 4.; spacing[1] = 4.; spacing[2] = 4.; #endif volInput->SetOrigin( origin ); volInput->SetSpacing( spacing ); volInput->SetSize( size ); volInput->SetConstant( 1. ); volInput->UpdateOutputInformation(); // Initialization Volume, it is used in the Joseph Forward Projector and in the // Ray Box Intersection Filter in order to initialize the stack of projections. const ConstantImageSourceType::Pointer projInput = ConstantImageSourceType::New(); size[2] = NumberOfProjectionImages; projInput->SetOrigin( origin ); projInput->SetSpacing( spacing ); projInput->SetSize( size ); projInput->SetConstant( 0. ); projInput->Update(); // Joseph Forward Projection filter #ifdef USE_CUDA typedef rtk::CudaForwardProjectionImageFilter JFPType; #else typedef rtk::JosephForwardProjectionImageFilter<OutputImageType, OutputImageType> JFPType; #endif JFPType::Pointer jfp = JFPType::New(); jfp->InPlaceOff(); jfp->SetInput( projInput->GetOutput() ); jfp->SetInput( 1, volInput->GetOutput() ); // Ray Box Intersection filter (reference) typedef rtk::RayBoxIntersectionImageFilter<OutputImageType2, OutputImageType2> RBIType; RBIType::Pointer rbi = RBIType::New(); rbi->InPlaceOff(); rbi->SetInput( projInput->GetOutput() ); VectorType boxMin, boxMax; boxMin[0] = -126.0; boxMin[1] = -126.0; boxMin[2] = -126.0; boxMax[0] = 126.0; boxMax[1] = 126.0; boxMax[2] = 47.6; rbi->SetBoxMin(boxMin); rbi->SetBoxMax(boxMax); std::cout << "\n\n****** Case 1: inner ray source ******" << std::endl; // The circle is divided in 4 quarters for(int q=0; q<4; q++) { // Geometry typedef rtk::ThreeDCircularProjectionGeometry GeometryType; GeometryType::Pointer geometry = GeometryType::New(); for(unsigned int i=0; i<NumberOfProjectionImages;i++) { const double angle = -45. + i*2.; geometry->AddProjection(47.6 / vcl_cos(angle*itk::Math::pi/180.), 1000., q*90+angle); } if(q==0) { rbi->SetGeometry( geometry ); rbi->Update(); } jfp->SetGeometry(geometry); jfp->Update(); CheckImageQuality<OutputImageType2, OutputImageType>(rbi->GetOutput(), jfp->GetOutput()); std::cout << "\n\nTest of quarter #" << q << " PASSED! " << std::endl; } std::cout << "\n\n****** Case 2: outer ray source ******" << std::endl; boxMax[2] = 126.0; rbi->SetBoxMax(boxMax); // Geometry typedef rtk::ThreeDCircularProjectionGeometry GeometryType; GeometryType::Pointer geometry = GeometryType::New(); for(unsigned int i=0; i<NumberOfProjectionImages; i++) geometry->AddProjection(500., 1000., i*8.); rbi->SetGeometry( geometry ); rbi->Update(); jfp->SetGeometry( geometry ); jfp->Update(); CheckImageQuality<OutputImageType2, OutputImageType>(rbi->GetOutput(), jfp->GetOutput()); std::cout << "\n\nTest PASSED! " << std::endl; std::cout << "\n\n****** Case 3: Shepp-Logan, outer ray source ******" << std::endl; // Create Shepp Logan reference projections typedef rtk::SheppLoganPhantomFilter<OutputImageType2, OutputImageType2> SLPType; SLPType::Pointer slp = SLPType::New(); slp->InPlaceOff(); slp->SetInput( projInput->GetOutput() ); slp->SetGeometry(geometry); slp->Update(); // Create a Shepp Logan reference volume (finer resolution) origin.Fill(-127); size.Fill(128); spacing.Fill(2.); volInput->SetOrigin( origin ); volInput->SetSpacing( spacing ); volInput->SetSize( size ); volInput->SetConstant( 0. ); typedef rtk::DrawSheppLoganFilter<OutputImageType2, OutputImageType> DSLType; DSLType::Pointer dsl = DSLType::New(); dsl->InPlaceOff(); dsl->SetInput( volInput->GetOutput() ); dsl->Update(); // Forward projection jfp->SetInput( 1, dsl->GetOutput() ); jfp->Update(); CheckImageQuality<OutputImageType2, OutputImageType>(slp->GetOutput(), jfp->GetOutput()); std::cout << "\n\nTest PASSED! " << std::endl; std::cout << "\n\n****** Case 4: Shepp-Logan, inner ray source ******" << std::endl; geometry = GeometryType::New(); for(unsigned int i=0; i<NumberOfProjectionImages; i++) geometry->AddProjection(120., 1000., i*8.); slp->SetGeometry(geometry); slp->Update(); jfp->SetGeometry( geometry ); jfp->Update(); CheckImageQuality<OutputImageType2, OutputImageType>(slp->GetOutput(), jfp->GetOutput()); std::cout << "\n\nTest PASSED! " << std::endl; return EXIT_SUCCESS; } <|endoftext|>
<commit_before> #include "rtkTestConfiguration.h" #include "rtkThreeDCircularProjectionGeometryXMLFile.h" #include "rtkRayBoxIntersectionImageFilter.h" #include "rtkSheppLoganPhantomFilter.h" #include "rtkDrawSheppLoganFilter.h" #include "rtkConstantImageSource.h" #ifdef USE_CUDA # include "rtkCudaForwardProjectionImageFilter.h" #else # include "rtkJosephForwardProjectionImageFilter.h" #endif template<class TImage1, class TImage2> #if FAST_TESTS_NO_CHECKS void CheckImageQuality(typename TImage::Pointer itkNotUsed(recon), typename TImage::Pointer itkNotUsed(ref)) { } #else void CheckImageQuality(typename TImage1::Pointer recon, typename TImage2::Pointer ref) { typedef itk::ImageRegionConstIterator<TImage1> ImageIteratorType1; typedef itk::ImageRegionConstIterator<TImage2> ImageIteratorType2; ImageIteratorType1 itTest( recon, recon->GetBufferedRegion() ); ImageIteratorType2 itRef( ref, ref->GetBufferedRegion() ); typedef double ErrorType; ErrorType TestError = 0.; ErrorType EnerError = 0.; itTest.GoToBegin(); itRef.GoToBegin(); while( !itRef.IsAtEnd() ) { typename TImage1::PixelType TestVal = itTest.Get(); typename TImage2::PixelType RefVal = itRef.Get(); if( TestVal != RefVal ) { TestError += vcl_abs(RefVal - TestVal); EnerError += vcl_pow(ErrorType(RefVal - TestVal), 2.); } ++itTest; ++itRef; } // Error per Pixel ErrorType ErrorPerPixel = TestError/recon->GetBufferedRegion().GetNumberOfPixels(); std::cout << "\nError per Pixel = " << ErrorPerPixel << std::endl; // MSE ErrorType MSE = EnerError/ref->GetBufferedRegion().GetNumberOfPixels(); std::cout << "MSE = " << MSE << std::endl; // PSNR ErrorType PSNR = 20*log10(255.0) - 10*log10(MSE); std::cout << "PSNR = " << PSNR << "dB" << std::endl; // QI ErrorType QI = (255.0-ErrorPerPixel)/255.0; std::cout << "QI = " << QI << std::endl; // Checking results if (ErrorPerPixel > 1.28) { std::cerr << "Test Failed, Error per pixel not valid! " << ErrorPerPixel << " instead of 1.28" << std::endl; //exit( EXIT_FAILURE); } if (PSNR < 44.) { std::cerr << "Test Failed, PSNR not valid! " << PSNR << " instead of 44" << std::endl; //exit( EXIT_FAILURE); } } #endif int main(int , char** ) { const unsigned int Dimension = 3; typedef float OutputPixelType; #ifdef USE_CUDA typedef itk::CudaImage< OutputPixelType, Dimension > OutputImageType; #else typedef itk::Image< OutputPixelType, Dimension > OutputImageType; #endif typedef itk::Image< OutputPixelType, Dimension > OutputImageType2; typedef itk::Vector<double, 3> VectorType; #if FAST_TESTS_NO_CHECKS const unsigned int NumberOfProjectionImages = 3; #else const unsigned int NumberOfProjectionImages = 45; #endif // Constant image sources typedef rtk::ConstantImageSource< OutputImageType > ConstantImageSourceType; ConstantImageSourceType::PointType origin; ConstantImageSourceType::SizeType size; ConstantImageSourceType::SpacingType spacing; // The test projects a volume filled with ones. The forward projector should // then return the intersection of the ray with the box and it is compared // with the analytical intersection of a box with a ray. // Create Joseph Forward Projector volume input. const ConstantImageSourceType::Pointer volInput = ConstantImageSourceType::New(); origin[0] = -126; origin[1] = -126; origin[2] = -126; #if FAST_TESTS_NO_CHECKS size[0] = 2; size[1] = 2; size[2] = 2; spacing[0] = 252.; spacing[1] = 252.; spacing[2] = 252.; #else size[0] = 64; size[1] = 64; size[2] = 64; spacing[0] = 4.; spacing[1] = 4.; spacing[2] = 4.; #endif volInput->SetOrigin( origin ); volInput->SetSpacing( spacing ); volInput->SetSize( size ); volInput->SetConstant( 1. ); volInput->UpdateOutputInformation(); // Initialization Volume, it is used in the Joseph Forward Projector and in the // Ray Box Intersection Filter in order to initialize the stack of projections. const ConstantImageSourceType::Pointer projInput = ConstantImageSourceType::New(); size[2] = NumberOfProjectionImages; projInput->SetOrigin( origin ); projInput->SetSpacing( spacing ); projInput->SetSize( size ); projInput->SetConstant( 0. ); projInput->Update(); // Joseph Forward Projection filter #ifdef USE_CUDA typedef rtk::CudaForwardProjectionImageFilter JFPType; #else typedef rtk::JosephForwardProjectionImageFilter<OutputImageType, OutputImageType> JFPType; #endif JFPType::Pointer jfp = JFPType::New(); jfp->InPlaceOff(); jfp->SetInput( projInput->GetOutput() ); jfp->SetInput( 1, volInput->GetOutput() ); // Ray Box Intersection filter (reference) typedef rtk::RayBoxIntersectionImageFilter<OutputImageType2, OutputImageType2> RBIType; RBIType::Pointer rbi = RBIType::New(); rbi->InPlaceOff(); rbi->SetInput( projInput->GetOutput() ); VectorType boxMin, boxMax; boxMin[0] = -126.0; boxMin[1] = -126.0; boxMin[2] = -126.0; boxMax[0] = 126.0; boxMax[1] = 126.0; boxMax[2] = 47.6; rbi->SetBoxMin(boxMin); rbi->SetBoxMax(boxMax); std::cout << "\n\n****** Case 1: inner ray source ******" << std::endl; // The circle is divided in 4 quarters for(int q=0; q<4; q++) { // Geometry typedef rtk::ThreeDCircularProjectionGeometry GeometryType; GeometryType::Pointer geometry = GeometryType::New(); for(unsigned int i=0; i<NumberOfProjectionImages;i++) { const double angle = -45. + i*2.; geometry->AddProjection(47.6 / vcl_cos(angle*itk::Math::pi/180.), 1000., q*90+angle); } if(q==0) { rbi->SetGeometry( geometry ); rbi->Update(); } jfp->SetGeometry(geometry); jfp->Update(); CheckImageQuality<OutputImageType2, OutputImageType>(rbi->GetOutput(), jfp->GetOutput()); std::cout << "\n\nTest of quarter #" << q << " PASSED! " << std::endl; } std::cout << "\n\n****** Case 2: outer ray source ******" << std::endl; boxMax[2] = 126.0; rbi->SetBoxMax(boxMax); // Geometry typedef rtk::ThreeDCircularProjectionGeometry GeometryType; GeometryType::Pointer geometry = GeometryType::New(); for(unsigned int i=0; i<NumberOfProjectionImages; i++) geometry->AddProjection(500., 1000., i*8.); rbi->SetGeometry( geometry ); rbi->Update(); jfp->SetGeometry( geometry ); jfp->Update(); CheckImageQuality<OutputImageType2, OutputImageType>(rbi->GetOutput(), jfp->GetOutput()); std::cout << "\n\nTest PASSED! " << std::endl; std::cout << "\n\n****** Case 3: Shepp-Logan, outer ray source ******" << std::endl; // Create Shepp Logan reference projections typedef rtk::SheppLoganPhantomFilter<OutputImageType2, OutputImageType2> SLPType; SLPType::Pointer slp = SLPType::New(); slp->InPlaceOff(); slp->SetInput( projInput->GetOutput() ); slp->SetGeometry(geometry); slp->Update(); // Create a Shepp Logan reference volume (finer resolution) origin.Fill(-127); size.Fill(128); spacing.Fill(2.); volInput->SetOrigin( origin ); volInput->SetSpacing( spacing ); volInput->SetSize( size ); volInput->SetConstant( 0. ); typedef rtk::DrawSheppLoganFilter<OutputImageType2, OutputImageType> DSLType; DSLType::Pointer dsl = DSLType::New(); dsl->InPlaceOff(); dsl->SetInput( volInput->GetOutput() ); dsl->Update(); // Forward projection jfp->SetInput( 1, dsl->GetOutput() ); jfp->Update(); CheckImageQuality<OutputImageType2, OutputImageType>(slp->GetOutput(), jfp->GetOutput()); std::cout << "\n\nTest PASSED! " << std::endl; std::cout << "\n\n****** Case 4: Shepp-Logan, inner ray source ******" << std::endl; geometry = GeometryType::New(); for(unsigned int i=0; i<NumberOfProjectionImages; i++) geometry->AddProjection(120., 1000., i*8.); slp->SetGeometry(geometry); slp->Update(); jfp->SetGeometry( geometry ); jfp->Update(); CheckImageQuality<OutputImageType2, OutputImageType>(slp->GetOutput(), jfp->GetOutput()); std::cout << "\n\nTest PASSED! " << std::endl; return EXIT_SUCCESS; } <commit_msg>Fixed compilation error (wrong copy pasting)<commit_after> #include "rtkTestConfiguration.h" #include "rtkThreeDCircularProjectionGeometryXMLFile.h" #include "rtkRayBoxIntersectionImageFilter.h" #include "rtkSheppLoganPhantomFilter.h" #include "rtkDrawSheppLoganFilter.h" #include "rtkConstantImageSource.h" #ifdef USE_CUDA # include "rtkCudaForwardProjectionImageFilter.h" #else # include "rtkJosephForwardProjectionImageFilter.h" #endif template<class TImage1, class TImage2> #if FAST_TESTS_NO_CHECKS void CheckImageQuality(typename TImage1::Pointer itkNotUsed(recon), typename TImage2::Pointer itkNotUsed(ref)) { } #else void CheckImageQuality(typename TImage1::Pointer recon, typename TImage2::Pointer ref) { typedef itk::ImageRegionConstIterator<TImage1> ImageIteratorType1; typedef itk::ImageRegionConstIterator<TImage2> ImageIteratorType2; ImageIteratorType1 itTest( recon, recon->GetBufferedRegion() ); ImageIteratorType2 itRef( ref, ref->GetBufferedRegion() ); typedef double ErrorType; ErrorType TestError = 0.; ErrorType EnerError = 0.; itTest.GoToBegin(); itRef.GoToBegin(); while( !itRef.IsAtEnd() ) { typename TImage1::PixelType TestVal = itTest.Get(); typename TImage2::PixelType RefVal = itRef.Get(); if( TestVal != RefVal ) { TestError += vcl_abs(RefVal - TestVal); EnerError += vcl_pow(ErrorType(RefVal - TestVal), 2.); } ++itTest; ++itRef; } // Error per Pixel ErrorType ErrorPerPixel = TestError/recon->GetBufferedRegion().GetNumberOfPixels(); std::cout << "\nError per Pixel = " << ErrorPerPixel << std::endl; // MSE ErrorType MSE = EnerError/ref->GetBufferedRegion().GetNumberOfPixels(); std::cout << "MSE = " << MSE << std::endl; // PSNR ErrorType PSNR = 20*log10(255.0) - 10*log10(MSE); std::cout << "PSNR = " << PSNR << "dB" << std::endl; // QI ErrorType QI = (255.0-ErrorPerPixel)/255.0; std::cout << "QI = " << QI << std::endl; // Checking results if (ErrorPerPixel > 1.28) { std::cerr << "Test Failed, Error per pixel not valid! " << ErrorPerPixel << " instead of 1.28" << std::endl; //exit( EXIT_FAILURE); } if (PSNR < 44.) { std::cerr << "Test Failed, PSNR not valid! " << PSNR << " instead of 44" << std::endl; //exit( EXIT_FAILURE); } } #endif int main(int , char** ) { const unsigned int Dimension = 3; typedef float OutputPixelType; #ifdef USE_CUDA typedef itk::CudaImage< OutputPixelType, Dimension > OutputImageType; #else typedef itk::Image< OutputPixelType, Dimension > OutputImageType; #endif typedef itk::Image< OutputPixelType, Dimension > OutputImageType2; typedef itk::Vector<double, 3> VectorType; #if FAST_TESTS_NO_CHECKS const unsigned int NumberOfProjectionImages = 3; #else const unsigned int NumberOfProjectionImages = 45; #endif // Constant image sources typedef rtk::ConstantImageSource< OutputImageType > ConstantImageSourceType; ConstantImageSourceType::PointType origin; ConstantImageSourceType::SizeType size; ConstantImageSourceType::SpacingType spacing; // The test projects a volume filled with ones. The forward projector should // then return the intersection of the ray with the box and it is compared // with the analytical intersection of a box with a ray. // Create Joseph Forward Projector volume input. const ConstantImageSourceType::Pointer volInput = ConstantImageSourceType::New(); origin[0] = -126; origin[1] = -126; origin[2] = -126; #if FAST_TESTS_NO_CHECKS size[0] = 2; size[1] = 2; size[2] = 2; spacing[0] = 252.; spacing[1] = 252.; spacing[2] = 252.; #else size[0] = 64; size[1] = 64; size[2] = 64; spacing[0] = 4.; spacing[1] = 4.; spacing[2] = 4.; #endif volInput->SetOrigin( origin ); volInput->SetSpacing( spacing ); volInput->SetSize( size ); volInput->SetConstant( 1. ); volInput->UpdateOutputInformation(); // Initialization Volume, it is used in the Joseph Forward Projector and in the // Ray Box Intersection Filter in order to initialize the stack of projections. const ConstantImageSourceType::Pointer projInput = ConstantImageSourceType::New(); size[2] = NumberOfProjectionImages; projInput->SetOrigin( origin ); projInput->SetSpacing( spacing ); projInput->SetSize( size ); projInput->SetConstant( 0. ); projInput->Update(); // Joseph Forward Projection filter #ifdef USE_CUDA typedef rtk::CudaForwardProjectionImageFilter JFPType; #else typedef rtk::JosephForwardProjectionImageFilter<OutputImageType, OutputImageType> JFPType; #endif JFPType::Pointer jfp = JFPType::New(); jfp->InPlaceOff(); jfp->SetInput( projInput->GetOutput() ); jfp->SetInput( 1, volInput->GetOutput() ); // Ray Box Intersection filter (reference) typedef rtk::RayBoxIntersectionImageFilter<OutputImageType2, OutputImageType2> RBIType; RBIType::Pointer rbi = RBIType::New(); rbi->InPlaceOff(); rbi->SetInput( projInput->GetOutput() ); VectorType boxMin, boxMax; boxMin[0] = -126.0; boxMin[1] = -126.0; boxMin[2] = -126.0; boxMax[0] = 126.0; boxMax[1] = 126.0; boxMax[2] = 47.6; rbi->SetBoxMin(boxMin); rbi->SetBoxMax(boxMax); std::cout << "\n\n****** Case 1: inner ray source ******" << std::endl; // The circle is divided in 4 quarters for(int q=0; q<4; q++) { // Geometry typedef rtk::ThreeDCircularProjectionGeometry GeometryType; GeometryType::Pointer geometry = GeometryType::New(); for(unsigned int i=0; i<NumberOfProjectionImages;i++) { const double angle = -45. + i*2.; geometry->AddProjection(47.6 / vcl_cos(angle*itk::Math::pi/180.), 1000., q*90+angle); } if(q==0) { rbi->SetGeometry( geometry ); rbi->Update(); } jfp->SetGeometry(geometry); jfp->Update(); CheckImageQuality<OutputImageType2, OutputImageType>(rbi->GetOutput(), jfp->GetOutput()); std::cout << "\n\nTest of quarter #" << q << " PASSED! " << std::endl; } std::cout << "\n\n****** Case 2: outer ray source ******" << std::endl; boxMax[2] = 126.0; rbi->SetBoxMax(boxMax); // Geometry typedef rtk::ThreeDCircularProjectionGeometry GeometryType; GeometryType::Pointer geometry = GeometryType::New(); for(unsigned int i=0; i<NumberOfProjectionImages; i++) geometry->AddProjection(500., 1000., i*8.); rbi->SetGeometry( geometry ); rbi->Update(); jfp->SetGeometry( geometry ); jfp->Update(); CheckImageQuality<OutputImageType2, OutputImageType>(rbi->GetOutput(), jfp->GetOutput()); std::cout << "\n\nTest PASSED! " << std::endl; std::cout << "\n\n****** Case 3: Shepp-Logan, outer ray source ******" << std::endl; // Create Shepp Logan reference projections typedef rtk::SheppLoganPhantomFilter<OutputImageType2, OutputImageType2> SLPType; SLPType::Pointer slp = SLPType::New(); slp->InPlaceOff(); slp->SetInput( projInput->GetOutput() ); slp->SetGeometry(geometry); slp->Update(); // Create a Shepp Logan reference volume (finer resolution) origin.Fill(-127); size.Fill(128); spacing.Fill(2.); volInput->SetOrigin( origin ); volInput->SetSpacing( spacing ); volInput->SetSize( size ); volInput->SetConstant( 0. ); typedef rtk::DrawSheppLoganFilter<OutputImageType2, OutputImageType> DSLType; DSLType::Pointer dsl = DSLType::New(); dsl->InPlaceOff(); dsl->SetInput( volInput->GetOutput() ); dsl->Update(); // Forward projection jfp->SetInput( 1, dsl->GetOutput() ); jfp->Update(); CheckImageQuality<OutputImageType2, OutputImageType>(slp->GetOutput(), jfp->GetOutput()); std::cout << "\n\nTest PASSED! " << std::endl; std::cout << "\n\n****** Case 4: Shepp-Logan, inner ray source ******" << std::endl; geometry = GeometryType::New(); for(unsigned int i=0; i<NumberOfProjectionImages; i++) geometry->AddProjection(120., 1000., i*8.); slp->SetGeometry(geometry); slp->Update(); jfp->SetGeometry( geometry ); jfp->Update(); CheckImageQuality<OutputImageType2, OutputImageType>(slp->GetOutput(), jfp->GetOutput()); std::cout << "\n\nTest PASSED! " << std::endl; return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#ifndef NETWORK_NETWORK_HPP #define NETWORK_NETWORK_HPP #include <vector> #include <nanomsg/nn.h> namespace MDL { namespace net { const size_t MAX_ELEMENT_NR = 100; struct msg_header { size_t msg_ele_nr; size_t msg_ele_sze[0]; }; size_t header_size(const msg_header *hdr); size_t make_header(msg_header **hdr, const std::vector<size_t> &lens); size_t make_nn_header(struct nn_msghdr *hdr, const std::vector<void *> &data, const std::vector<size_t> &lens); size_t make_nn_header(struct nn_msghdr *hdr, const std::vector<size_t> &lens); void free_header(msg_header *hdr); void free_header(struct nn_msghdr *hdr, bool free_base); } // namespace net }; // namespace MDL #endif // NETWORK_NETWORK_HPP <commit_msg>network<commit_after>#ifndef NETWORK_NETWORK_HPP #define NETWORK_NETWORK_HPP #include <vector> #include <nanomsg/nn.h> namespace MDL { namespace net { const size_t MAX_ELEMENT_NR = 100; struct msg_header { size_t msg_ele_nr; size_t msg_ele_sze[0]; }; size_t header_size(const msg_header *hdr); size_t make_header(msg_header **hdr, const std::vector<size_t> &lens); size_t make_nn_header(struct nn_msghdr *hdr, const std::vector<void *> &data, const std::vector<size_t> &lens); size_t make_nn_header(struct nn_msghdr *hdr, const std::vector<size_t> &lens); void free_header(msg_header *hdr); void free_header(struct nn_msghdr *hdr, bool free_base); template<class T> long receive(T &obj, int sock); template<class T> long send(const T &obj, int sock); } // namespace net }; // namespace MDL #endif // NETWORK_NETWORK_HPP <|endoftext|>
<commit_before> #include <QtTest> #include <QtDebug> #include <Control.h> #include <Parser.h> #include <AST.h> CPLUSPLUS_USE_NAMESPACE class tst_AST: public QObject { Q_OBJECT Control control; public: TranslationUnit *parse(const QByteArray &source, TranslationUnit::ParseMode mode) { StringLiteral *fileId = control.findOrInsertFileName("<stdin>"); TranslationUnit *unit = new TranslationUnit(&control, fileId); unit->setSource(source.constData(), source.length()); unit->parse(mode); return unit; } TranslationUnit *parseStatement(const QByteArray &source) { return parse(source, TranslationUnit::ParseStatement); } private slots: void if_statement(); void if_else_statement(); void cpp_initializer_or_function_declaration(); }; void tst_AST::if_statement() { QSharedPointer<TranslationUnit> unit(parseStatement("if (a) b;")); AST *ast = unit->ast(); QVERIFY(ast != 0); IfStatementAST *stmt = ast->asIfStatement(); QVERIFY(stmt != 0); QCOMPARE(stmt->if_token, 1U); QCOMPARE(stmt->lparen_token, 2U); QVERIFY(stmt->condition != 0); QCOMPARE(stmt->rparen_token, 4U); QVERIFY(stmt->statement != 0); QCOMPARE(stmt->else_token, 0U); QVERIFY(stmt->else_statement == 0); // check the `then' statement ExpressionStatementAST *then_stmt = stmt->statement->asExpressionStatement(); QVERIFY(then_stmt != 0); QVERIFY(then_stmt->expression != 0); QCOMPARE(then_stmt->semicolon_token, 6U); SimpleNameAST *id_expr = then_stmt->expression->asSimpleName(); QVERIFY(id_expr != 0); QCOMPARE(id_expr->identifier_token, 5U); } void tst_AST::if_else_statement() { QSharedPointer<TranslationUnit> unit(parseStatement("if (a) b; else c;")); AST *ast = unit->ast(); QVERIFY(ast != 0); IfStatementAST *stmt = ast->asIfStatement(); QVERIFY(stmt != 0); QCOMPARE(stmt->if_token, 1U); QCOMPARE(stmt->lparen_token, 2U); QVERIFY(stmt->condition != 0); QCOMPARE(stmt->rparen_token, 4U); QVERIFY(stmt->statement != 0); QCOMPARE(stmt->else_token, 7U); QVERIFY(stmt->else_statement != 0); // check the `then' statement ExpressionStatementAST *then_stmt = stmt->statement->asExpressionStatement(); QVERIFY(then_stmt != 0); QVERIFY(then_stmt->expression != 0); QCOMPARE(then_stmt->semicolon_token, 6U); SimpleNameAST *a_id_expr = then_stmt->expression->asSimpleName(); QVERIFY(a_id_expr != 0); QCOMPARE(a_id_expr->identifier_token, 5U); // check the `then' statement ExpressionStatementAST *else_stmt = stmt->else_statement->asExpressionStatement(); QVERIFY(else_stmt != 0); QVERIFY(else_stmt->expression != 0); QCOMPARE(else_stmt->semicolon_token, 9U); SimpleNameAST *b_id_expr = else_stmt->expression->asSimpleName(); QVERIFY(b_id_expr != 0); QCOMPARE(b_id_expr->identifier_token, 8U); } void tst_AST::cpp_initializer_or_function_declaration() { QSharedPointer<TranslationUnit> unit(parseStatement("QFileInfo fileInfo(foo);")); AST *ast = unit->ast(); QVERIFY(ast != 0); DeclarationStatementAST *stmt = ast->asDeclarationStatement(); QVERIFY(stmt != 0); QVERIFY(stmt->declaration != 0); SimpleDeclarationAST *simple_decl = stmt->declaration->asSimpleDeclaration(); QVERIFY(simple_decl != 0); QVERIFY(simple_decl->decl_specifier_seq != 0); QVERIFY(simple_decl->decl_specifier_seq->next == 0); QVERIFY(simple_decl->declarators != 0); QVERIFY(simple_decl->declarators->next == 0); QCOMPARE(simple_decl->semicolon_token, 6U); NamedTypeSpecifierAST *named_ty = simple_decl->decl_specifier_seq->asNamedTypeSpecifier(); QVERIFY(named_ty != 0); QVERIFY(named_ty->name != 0); SimpleNameAST *simple_named_ty = named_ty->name->asSimpleName(); QVERIFY(simple_named_ty != 0); QCOMPARE(simple_named_ty->identifier_token, 1U); DeclaratorAST *declarator = simple_decl->declarators->declarator; QVERIFY(declarator != 0); QVERIFY(declarator->core_declarator != 0); QVERIFY(declarator->postfix_declarators != 0); QVERIFY(declarator->postfix_declarators->next == 0); QVERIFY(declarator->initializer == 0); DeclaratorIdAST *decl_id = declarator->core_declarator->asDeclaratorId(); QVERIFY(decl_id != 0); QVERIFY(decl_id->name != 0); QVERIFY(decl_id->name->asSimpleName() != 0); QCOMPARE(decl_id->name->asSimpleName()->identifier_token, 2U); FunctionDeclaratorAST *fun_declarator = declarator->postfix_declarators->asFunctionDeclarator(); QVERIFY(fun_declarator != 0); QCOMPARE(fun_declarator->lparen_token, 3U); QVERIFY(fun_declarator->parameters != 0); QCOMPARE(fun_declarator->rparen_token, 5U); // check the formal arguments ParameterDeclarationClauseAST *param_clause = fun_declarator->parameters; QVERIFY(param_clause->parameter_declarations != 0); QVERIFY(param_clause->parameter_declarations->next == 0); QCOMPARE(param_clause->dot_dot_dot_token, 0U); // check the parameter ParameterDeclarationAST *param = param_clause->parameter_declarations->asParameterDeclaration(); QVERIFY(param->type_specifier != 0); QVERIFY(param->type_specifier->next == 0); QVERIFY(param->type_specifier->asNamedTypeSpecifier() != 0); QVERIFY(param->type_specifier->asNamedTypeSpecifier()->name != 0); QVERIFY(param->type_specifier->asNamedTypeSpecifier()->name->asSimpleName() != 0); QCOMPARE(param->type_specifier->asNamedTypeSpecifier()->name->asSimpleName()->identifier_token, 4U); } QTEST_APPLESS_MAIN(tst_AST) #include "tst_ast.moc" <commit_msg>Testing `while' statement.<commit_after> #include <QtTest> #include <QtDebug> #include <Control.h> #include <Parser.h> #include <AST.h> CPLUSPLUS_USE_NAMESPACE class tst_AST: public QObject { Q_OBJECT Control control; public: TranslationUnit *parse(const QByteArray &source, TranslationUnit::ParseMode mode) { StringLiteral *fileId = control.findOrInsertFileName("<stdin>"); TranslationUnit *unit = new TranslationUnit(&control, fileId); unit->setSource(source.constData(), source.length()); unit->parse(mode); return unit; } TranslationUnit *parseStatement(const QByteArray &source) { return parse(source, TranslationUnit::ParseStatement); } private slots: void if_statement(); void if_else_statement(); void while_statement(); void while_condition_statement(); void cpp_initializer_or_function_declaration(); }; void tst_AST::if_statement() { QSharedPointer<TranslationUnit> unit(parseStatement("if (a) b;")); AST *ast = unit->ast(); QVERIFY(ast != 0); IfStatementAST *stmt = ast->asIfStatement(); QVERIFY(stmt != 0); QCOMPARE(stmt->if_token, 1U); QCOMPARE(stmt->lparen_token, 2U); QVERIFY(stmt->condition != 0); QCOMPARE(stmt->rparen_token, 4U); QVERIFY(stmt->statement != 0); QCOMPARE(stmt->else_token, 0U); QVERIFY(stmt->else_statement == 0); // check the `then' statement ExpressionStatementAST *then_stmt = stmt->statement->asExpressionStatement(); QVERIFY(then_stmt != 0); QVERIFY(then_stmt->expression != 0); QCOMPARE(then_stmt->semicolon_token, 6U); SimpleNameAST *id_expr = then_stmt->expression->asSimpleName(); QVERIFY(id_expr != 0); QCOMPARE(id_expr->identifier_token, 5U); } void tst_AST::if_else_statement() { QSharedPointer<TranslationUnit> unit(parseStatement("if (a) b; else c;")); AST *ast = unit->ast(); QVERIFY(ast != 0); IfStatementAST *stmt = ast->asIfStatement(); QVERIFY(stmt != 0); QCOMPARE(stmt->if_token, 1U); QCOMPARE(stmt->lparen_token, 2U); QVERIFY(stmt->condition != 0); QCOMPARE(stmt->rparen_token, 4U); QVERIFY(stmt->statement != 0); QCOMPARE(stmt->else_token, 7U); QVERIFY(stmt->else_statement != 0); // check the `then' statement ExpressionStatementAST *then_stmt = stmt->statement->asExpressionStatement(); QVERIFY(then_stmt != 0); QVERIFY(then_stmt->expression != 0); QCOMPARE(then_stmt->semicolon_token, 6U); SimpleNameAST *a_id_expr = then_stmt->expression->asSimpleName(); QVERIFY(a_id_expr != 0); QCOMPARE(a_id_expr->identifier_token, 5U); // check the `then' statement ExpressionStatementAST *else_stmt = stmt->else_statement->asExpressionStatement(); QVERIFY(else_stmt != 0); QVERIFY(else_stmt->expression != 0); QCOMPARE(else_stmt->semicolon_token, 9U); SimpleNameAST *b_id_expr = else_stmt->expression->asSimpleName(); QVERIFY(b_id_expr != 0); QCOMPARE(b_id_expr->identifier_token, 8U); } void tst_AST::while_statement() { QSharedPointer<TranslationUnit> unit(parseStatement("while (a) { }")); AST *ast = unit->ast(); QVERIFY(ast != 0); WhileStatementAST *stmt = ast->asWhileStatement(); QVERIFY(stmt != 0); QCOMPARE(stmt->while_token, 1U); QCOMPARE(stmt->lparen_token, 2U); QVERIFY(stmt->condition != 0); QCOMPARE(stmt->rparen_token, 4U); QVERIFY(stmt->statement != 0); // check condition QVERIFY(stmt->condition->asSimpleName() != 0); QCOMPARE(stmt->condition->asSimpleName()->identifier_token, 3U); // check the `body' statement CompoundStatementAST *body_stmt = stmt->statement->asCompoundStatement(); QVERIFY(body_stmt != 0); QCOMPARE(body_stmt->lbrace_token, 5U); QVERIFY(body_stmt->statements == 0); QCOMPARE(body_stmt->rbrace_token, 6U); } void tst_AST::while_condition_statement() { QSharedPointer<TranslationUnit> unit(parseStatement("while (int a = foo) { }")); AST *ast = unit->ast(); QVERIFY(ast != 0); WhileStatementAST *stmt = ast->asWhileStatement(); QVERIFY(stmt != 0); QCOMPARE(stmt->while_token, 1U); QCOMPARE(stmt->lparen_token, 2U); QVERIFY(stmt->condition != 0); QCOMPARE(stmt->rparen_token, 7U); QVERIFY(stmt->statement != 0); // check condition ConditionAST *condition = stmt->condition->asCondition(); QVERIFY(condition != 0); QVERIFY(condition->type_specifier != 0); QVERIFY(condition->type_specifier->asSimpleSpecifier() != 0); QCOMPARE(condition->type_specifier->asSimpleSpecifier()->specifier_token, 3U); QVERIFY(condition->type_specifier->next == 0); QVERIFY(condition->declarator != 0); QVERIFY(condition->declarator->initializer != 0); // check the `body' statement CompoundStatementAST *body_stmt = stmt->statement->asCompoundStatement(); QVERIFY(body_stmt != 0); QCOMPARE(body_stmt->lbrace_token, 8U); QVERIFY(body_stmt->statements == 0); QCOMPARE(body_stmt->rbrace_token, 9U); } void tst_AST::cpp_initializer_or_function_declaration() { QSharedPointer<TranslationUnit> unit(parseStatement("QFileInfo fileInfo(foo);")); AST *ast = unit->ast(); QVERIFY(ast != 0); DeclarationStatementAST *stmt = ast->asDeclarationStatement(); QVERIFY(stmt != 0); QVERIFY(stmt->declaration != 0); SimpleDeclarationAST *simple_decl = stmt->declaration->asSimpleDeclaration(); QVERIFY(simple_decl != 0); QVERIFY(simple_decl->decl_specifier_seq != 0); QVERIFY(simple_decl->decl_specifier_seq->next == 0); QVERIFY(simple_decl->declarators != 0); QVERIFY(simple_decl->declarators->next == 0); QCOMPARE(simple_decl->semicolon_token, 6U); NamedTypeSpecifierAST *named_ty = simple_decl->decl_specifier_seq->asNamedTypeSpecifier(); QVERIFY(named_ty != 0); QVERIFY(named_ty->name != 0); SimpleNameAST *simple_named_ty = named_ty->name->asSimpleName(); QVERIFY(simple_named_ty != 0); QCOMPARE(simple_named_ty->identifier_token, 1U); DeclaratorAST *declarator = simple_decl->declarators->declarator; QVERIFY(declarator != 0); QVERIFY(declarator->core_declarator != 0); QVERIFY(declarator->postfix_declarators != 0); QVERIFY(declarator->postfix_declarators->next == 0); QVERIFY(declarator->initializer == 0); DeclaratorIdAST *decl_id = declarator->core_declarator->asDeclaratorId(); QVERIFY(decl_id != 0); QVERIFY(decl_id->name != 0); QVERIFY(decl_id->name->asSimpleName() != 0); QCOMPARE(decl_id->name->asSimpleName()->identifier_token, 2U); FunctionDeclaratorAST *fun_declarator = declarator->postfix_declarators->asFunctionDeclarator(); QVERIFY(fun_declarator != 0); QCOMPARE(fun_declarator->lparen_token, 3U); QVERIFY(fun_declarator->parameters != 0); QCOMPARE(fun_declarator->rparen_token, 5U); // check the formal arguments ParameterDeclarationClauseAST *param_clause = fun_declarator->parameters; QVERIFY(param_clause->parameter_declarations != 0); QVERIFY(param_clause->parameter_declarations->next == 0); QCOMPARE(param_clause->dot_dot_dot_token, 0U); // check the parameter ParameterDeclarationAST *param = param_clause->parameter_declarations->asParameterDeclaration(); QVERIFY(param->type_specifier != 0); QVERIFY(param->type_specifier->next == 0); QVERIFY(param->type_specifier->asNamedTypeSpecifier() != 0); QVERIFY(param->type_specifier->asNamedTypeSpecifier()->name != 0); QVERIFY(param->type_specifier->asNamedTypeSpecifier()->name->asSimpleName() != 0); QCOMPARE(param->type_specifier->asNamedTypeSpecifier()->name->asSimpleName()->identifier_token, 4U); } QTEST_APPLESS_MAIN(tst_AST) #include "tst_ast.moc" <|endoftext|>
<commit_before>// QtPromise #include <QtPromise> // Qt #include <QtTest> using namespace QtPromise; using namespace QtPromisePrivate; class tst_qpromise: public QObject { Q_OBJECT private Q_SLOTS: void finallyReturns(); void finallyThrows(); void finallyDelayedFulfilled(); void finallyDelayedRejected(); }; // class tst_qpromise QTEST_MAIN(tst_qpromise) #include "tst_qpromise.moc" void tst_qpromise::finallyReturns() { { // fulfilled QVector<int> values; auto next = QPromise<int>::resolve(42).finally([&]() { values << 8; return 16; // ignored! }); next.then([&](int r) { values << r; }).wait(); QVERIFY(next.isFulfilled()); QCOMPARE(values, QVector<int>({8, 42})); } { // rejected QString error; int value = -1; auto next = QPromise<int>([](const QPromiseResolve<int>) { throw QString("foo"); }).finally([&]() { value = 8; return 16; // ignored! }); next.fail([&](const QString& err) { error = err; return 42; }).wait(); QVERIFY(next.isRejected()); QCOMPARE(error, QString("foo")); QCOMPARE(value, 8); } } void tst_qpromise::finallyThrows() { { // fulfilled QString error; auto next = QPromise<int>::resolve(42).finally([&]() { throw QString("bar"); }); next.fail([&](const QString& err) { error = err; return 0; }).wait(); QVERIFY(next.isRejected()); QCOMPARE(error, QString("bar")); } { // rejected QString error; auto next = QPromise<int>::reject(QString("foo")).finally([&]() { throw QString("bar"); }); next.fail([&](const QString& err) { error = err; return 0; }).wait(); QVERIFY(next.isRejected()); QCOMPARE(error, QString("bar")); } } void tst_qpromise::finallyDelayedFulfilled() { { // fulfilled QVector<int> values; auto next = QPromise<int>::resolve(42).finally([&]() { QPromise<int> p([&](const QPromiseResolve<int>& resolve) { qtpromise_defer([=, &values]() { values << 64; resolve(16); // ignored! }); }); values << 8; return p; }); next.then([&](int r) { values << r; }).wait(); QVERIFY(next.isFulfilled()); QCOMPARE(values, QVector<int>({8, 64, 42})); } { // rejected QString error; QVector<int> values; auto next = QPromise<int>::reject(QString("foo")).finally([&]() { QPromise<int> p([&](const QPromiseResolve<int>& resolve) { qtpromise_defer([=, &values]() { values << 64; resolve(16); // ignored! }); }); values << 8; return p; }); next.then([&](int r) { values << r; }, [&](const QString& err) { error = err; }).wait(); QVERIFY(next.isRejected()); QCOMPARE(error, QString("foo")); QCOMPARE(values, QVector<int>({8, 64})); } } void tst_qpromise::finallyDelayedRejected() { { // fulfilled QString error; auto next = QPromise<int>::resolve(42).finally([]() { return QPromise<int>([](const QPromiseResolve<int>&, const QPromiseReject<int>& reject) { qtpromise_defer([=]() { reject(QString("bar")); }); }); }); next.fail([&](const QString& err) { error = err; return 0; }).wait(); QVERIFY(next.isRejected()); QCOMPARE(error, QString("bar")); } { // rejected QString error; auto next = QPromise<int>::reject(QString("foo")).finally([]() { return QPromise<int>([](const QPromiseResolve<int>&, const QPromiseReject<int>& reject) { qtpromise_defer([=]() { reject(QString("bar")); }); }); }); next.fail([&](const QString& err) { error = err; return 0; }).wait(); QVERIFY(next.isRejected()); QCOMPARE(error, QString("bar")); } } <commit_msg>More QPromise<T/void> unit tests<commit_after>// QtPromise #include <QtPromise> // Qt #include <QtTest> using namespace QtPromise; using namespace QtPromisePrivate; class tst_qpromise: public QObject { Q_OBJECT private Q_SLOTS: void resolveSync(); void resolveSync_void(); void resolveDelayed(); void rejectSync(); void rejectDelayed(); void rejectThrows(); void thenReturns(); void thenThrows(); void thenNullPtr(); void thenSkipResult(); void thenDelayedResolved(); void thenDelayedRejected(); void failSameType(); void failBaseClass(); void failCatchAll(); void finallyReturns(); void finallyReturns_void(); void finallyThrows(); void finallyThrows_void(); void finallyDelayedResolved(); void finallyDelayedRejected(); }; // class tst_qpromise QTEST_MAIN(tst_qpromise) #include "tst_qpromise.moc" template <typename T> T waitForValue(const QPromise<T>& promise, const T& initial) { T value(initial); promise.then([&](const T& res) { value = res; }).wait(); return value; } template <typename T> T waitForValue(const QPromise<void>& promise, const T& initial, const T& expected) { T value(initial); promise.then([&]() { value = expected; }).wait(); return value; } template <typename T, typename E> E waitForError(const QPromise<T>& promise, const E& initial) { E error(initial); promise.fail([&](const E& err) { error = err; return T(); }).wait(); return error; } template <typename E> E waitForError(const QPromise<void>& promise, const E& initial) { E error(initial); promise.fail([&](const E& err) { error = err; }).wait(); return error; } void tst_qpromise::resolveSync() { { // resolver(resolve) QPromise<int> p([](const QPromiseResolve<int>& resolve) { resolve(42); }); QCOMPARE(p.isFulfilled(), true); QCOMPARE(waitForError(p, QString()), QString()); QCOMPARE(waitForValue(p, -1), 42); } { // resolver(resolve, reject) QPromise<int> p([](const QPromiseResolve<int>& resolve, const QPromiseReject<int>&) { resolve(42); }); QCOMPARE(p.isFulfilled(), true); QCOMPARE(waitForError(p, QString()), QString()); QCOMPARE(waitForValue(p, -1), 42); } } void tst_qpromise::resolveSync_void() { { // resolver(resolve) QPromise<void> p([](const QPromiseResolve<void>& resolve) { resolve(); }); QCOMPARE(p.isFulfilled(), true); QCOMPARE(waitForError(p, QString()), QString()); QCOMPARE(waitForValue(p, -1, 42), 42); } { // resolver(resolve, reject) QPromise<void> p([](const QPromiseResolve<void>& resolve, const QPromiseReject<void>&) { resolve(); }); QCOMPARE(p.isFulfilled(), true); QCOMPARE(waitForError(p, QString()), QString()); QCOMPARE(waitForValue(p, -1, 42), 42); } } void tst_qpromise::resolveDelayed() { { // resolver(resolve) QPromise<int> p([](const QPromiseResolve<int>& resolve) { QtPromisePrivate::qtpromise_defer([=]() { resolve(42); }); }); QCOMPARE(p.isPending(), true); QCOMPARE(waitForError(p, QString()), QString()); QCOMPARE(waitForValue(p, -1), 42); QCOMPARE(p.isFulfilled(), true); } { // resolver(resolve, reject) QPromise<int> p([](const QPromiseResolve<int>& resolve, const QPromiseReject<int>&) { QtPromisePrivate::qtpromise_defer([=]() { resolve(42); }); }); QCOMPARE(p.isPending(), true); QCOMPARE(waitForError(p, QString()), QString()); QCOMPARE(waitForValue(p, -1), 42); QCOMPARE(p.isFulfilled(), true); } } void tst_qpromise::rejectSync() { QPromise<int> p([](const QPromiseResolve<int>&, const QPromiseReject<int>& reject) { reject(QString("foo")); }); QCOMPARE(p.isRejected(), true); QCOMPARE(waitForValue(p, -1), -1); QCOMPARE(waitForError(p, QString()), QString("foo")); } void tst_qpromise::rejectDelayed() { QPromise<int> p([](const QPromiseResolve<int>&, const QPromiseReject<int>& reject) { QtPromisePrivate::qtpromise_defer([=]() { reject(QString("foo")); }); }); QCOMPARE(p.isPending(), true); QCOMPARE(waitForValue(p, -1), -1); QCOMPARE(waitForError(p, QString()), QString("foo")); QCOMPARE(p.isRejected(), true); } void tst_qpromise::rejectThrows() { { // resolver(resolve) QPromise<int> p([](const QPromiseResolve<int>&) { throw QString("foo"); }); QCOMPARE(p.isRejected(), true); QCOMPARE(waitForValue(p, -1), -1); QCOMPARE(waitForError(p, QString()), QString("foo")); } { // resolver(resolve, reject) QPromise<int> p([](const QPromiseResolve<int>&, const QPromiseReject<int>&) { throw QString("foo"); }); QCOMPARE(p.isRejected(), true); QCOMPARE(waitForValue(p, -1), -1); QCOMPARE(waitForError(p, QString()), QString("foo")); } } void tst_qpromise::thenReturns() { auto p = QPromise<int>::resolve(42); QVariantList values; p.then([&](int res) { values << res; return QString::number(res+1); }).then([&](const QString& res) { values << res; }).then([&]() { values << 44; }).wait(); QCOMPARE(values, QVariantList({42, QString("43"), 44})); } void tst_qpromise::thenThrows() { auto input = QPromise<int>::resolve(42); auto output = input.then([](int res) { throw QString("foo%1").arg(res); return 42; }); QString error; output.then([&](int res) { error += "bar" + QString::number(res); }).fail([&](const QString& err) { error += err; }).wait(); QCOMPARE(input.isFulfilled(), true); QCOMPARE(output.isRejected(), true); QCOMPARE(error, QString("foo42")); } void tst_qpromise::thenNullPtr() { { // resolved auto p = QPromise<int>::resolve(42).then(nullptr); QCOMPARE(waitForValue(p, -1), 42); QCOMPARE(p.isFulfilled(), true); } { // rejected auto p = QPromise<int>::reject(QString("foo")).then(nullptr); QCOMPARE(waitForError(p, QString()), QString("foo")); QCOMPARE(p.isRejected(), true); } } void tst_qpromise::thenSkipResult() { auto p = QPromise<int>::resolve(42); int value = -1; p.then([&]() { value = 43; }).wait(); Q_STATIC_ASSERT((std::is_same<decltype(p), QPromise<int> >::value)); QCOMPARE(value, 43); } void tst_qpromise::thenDelayedResolved() { auto p = QPromise<int>::resolve(42).then([](int res) { return QPromise<QString>([=](const QPromiseResolve<QString>& resolve) { QtPromisePrivate::qtpromise_defer([=]() { resolve(QString("foo%1").arg(res)); }); }); }); Q_STATIC_ASSERT((std::is_same<decltype(p), QPromise<QString> >::value)); QCOMPARE(waitForValue(p, QString()), QString("foo42")); } void tst_qpromise::thenDelayedRejected() { auto p = QPromise<int>::resolve(42).then([](int res) { return QPromise<void>([=](const QPromiseResolve<void>&, const QPromiseReject<void>& reject) { QtPromisePrivate::qtpromise_defer([=]() { reject(QString("foo%1").arg(res)); }); }); }); Q_STATIC_ASSERT((std::is_same<decltype(p), QPromise<void> >::value)); QCOMPARE(waitForError(p, QString()), QString("foo42")); } void tst_qpromise::failSameType() { // http://en.cppreference.com/w/cpp/error/exception auto p = QPromise<int>::reject(std::out_of_range("foo")); QString error; p.fail([&](const std::domain_error& e) { error += QString(e.what()) + "0"; return -1; }).fail([&](const std::out_of_range& e) { error += QString(e.what()) + "1"; return -1; }).fail([&](const std::exception& e) { error += QString(e.what()) + "2"; return -1; }).wait(); QCOMPARE(error, QString("foo1")); } void tst_qpromise::failBaseClass() { // http://en.cppreference.com/w/cpp/error/exception auto p = QPromise<int>::reject(std::out_of_range("foo")); QString error; p.fail([&](const std::runtime_error& e) { error += QString(e.what()) + "0"; return -1; }).fail([&](const std::logic_error& e) { error += QString(e.what()) + "1"; return -1; }).fail([&](const std::exception& e) { error += QString(e.what()) + "2"; return -1; }).wait(); QCOMPARE(error, QString("foo1")); } void tst_qpromise::failCatchAll() { auto p = QPromise<int>::reject(std::out_of_range("foo")); QString error; p.fail([&](const std::runtime_error& e) { error += QString(e.what()) + "0"; return -1; }).fail([&]() { error += "bar"; return -1; }).fail([&](const std::exception& e) { error += QString(e.what()) + "2"; return -1; }).wait(); QCOMPARE(error, QString("bar")); } void tst_qpromise::finallyReturns() { { // fulfilled int value = -1; auto p = QPromise<int>::resolve(42).finally([&]() { value = 8; return 16; // ignored! }); Q_STATIC_ASSERT((std::is_same<decltype(p), QPromise<int> >::value)); QCOMPARE(waitForValue(p, -1), 42); QCOMPARE(p.isFulfilled(), true); QCOMPARE(value, 8); } { // rejected int value = -1; auto p = QPromise<int>::reject(QString("foo")).finally([&]() { value = 8; return 16; // ignored! }); Q_STATIC_ASSERT((std::is_same<decltype(p), QPromise<int> >::value)); QCOMPARE(waitForError(p, QString()), QString("foo")); QCOMPARE(p.isRejected(), true); QCOMPARE(value, 8); } } void tst_qpromise::finallyReturns_void() { { // fulfilled int value = -1; auto p = QPromise<void>::resolve().finally([&]() { value = 8; return 16; // ignored! }); Q_STATIC_ASSERT((std::is_same<decltype(p), QPromise<void> >::value)); QCOMPARE(waitForValue(p, -1, 42), 42); QCOMPARE(p.isFulfilled(), true); QCOMPARE(value, 8); } { // rejected int value = -1; auto p = QPromise<void>::reject(QString("foo")).finally([&]() { value = 8; return 16; // ignored! }); Q_STATIC_ASSERT((std::is_same<decltype(p), QPromise<void> >::value)); QCOMPARE(waitForError(p, QString()), QString("foo")); QCOMPARE(p.isRejected(), true); QCOMPARE(value, 8); } } void tst_qpromise::finallyThrows() { { // fulfilled auto p = QPromise<int>::resolve(42).finally([&]() { throw QString("bar"); }); Q_STATIC_ASSERT((std::is_same<decltype(p), QPromise<int> >::value)); QCOMPARE(waitForError(p, QString()), QString("bar")); QCOMPARE(p.isRejected(), true); } { // rejected auto p = QPromise<int>::reject(QString("foo")).finally([&]() { throw QString("bar"); }); Q_STATIC_ASSERT((std::is_same<decltype(p), QPromise<int> >::value)); QCOMPARE(waitForError(p, QString()), QString("bar")); QCOMPARE(p.isRejected(), true); } } void tst_qpromise::finallyThrows_void() { { // fulfilled auto p = QPromise<void>::resolve().finally([&]() { throw QString("bar"); }); Q_STATIC_ASSERT((std::is_same<decltype(p), QPromise<void> >::value)); QCOMPARE(waitForError(p, QString()), QString("bar")); QCOMPARE(p.isRejected(), true); } { // rejected auto p = QPromise<void>::reject(QString("foo")).finally([&]() { throw QString("bar"); }); Q_STATIC_ASSERT((std::is_same<decltype(p), QPromise<void> >::value)); QCOMPARE(waitForError(p, QString()), QString("bar")); QCOMPARE(p.isRejected(), true); } } void tst_qpromise::finallyDelayedResolved() { { // fulfilled QVector<int> values; auto p = QPromise<int>::resolve(42).finally([&]() { QPromise<int> p([&](const QPromiseResolve<int>& resolve) { qtpromise_defer([=, &values]() { values << 64; resolve(16); // ignored! }); }); values << 8; return p; }); QCOMPARE(waitForValue(p, -1), 42); QCOMPARE(p.isFulfilled(), true); QCOMPARE(values, QVector<int>({8, 64})); } { // rejected QVector<int> values; auto p = QPromise<int>::reject(QString("foo")).finally([&]() { QPromise<int> p([&](const QPromiseResolve<int>& resolve) { qtpromise_defer([=, &values]() { values << 64; resolve(16); // ignored! }); }); values << 8; return p; }); p.then([&](int r) { values << r; }).wait(); QCOMPARE(waitForError(p, QString()), QString("foo")); QCOMPARE(p.isRejected(), true); QCOMPARE(values, QVector<int>({8, 64})); } } void tst_qpromise::finallyDelayedRejected() { { // fulfilled auto p = QPromise<int>::resolve(42).finally([]() { return QPromise<int>([](const QPromiseResolve<int>&, const QPromiseReject<int>& reject) { qtpromise_defer([=]() { reject(QString("bar")); }); }); }); QCOMPARE(waitForError(p, QString()), QString("bar")); QCOMPARE(p.isRejected(), true); } { // rejected auto p = QPromise<int>::reject(QString("foo")).finally([]() { return QPromise<int>([](const QPromiseResolve<int>&, const QPromiseReject<int>& reject) { qtpromise_defer([=]() { reject(QString("bar")); }); }); }); QCOMPARE(waitForError(p, QString()), QString("bar")); QCOMPARE(p.isRejected(), true); } } <|endoftext|>
<commit_before>/* * Copyright 2008, 2009 Google Inc. * Copyright 2007 Nintendo Co., Ltd. * * 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 <sys/stat.h> #include <sys/types.h> #include <set> #include "java.h" namespace { FILE* createFile(const std::string package, const Node* node) { std::string filename = package; size_t pos = 0; for (;;) { pos = filename.find('.', pos); if (pos == std::string::npos) { break; } filename[pos] = '/'; } filename += "/" + node->getName() + ".java"; std::string dir; std::string path(filename); for (;;) { size_t slash = path.find("/"); if (slash == std::string::npos) { break; } dir += path.substr(0, slash); path.erase(0, slash + 1); mkdir(dir.c_str(), 0777); dir += '/'; } printf("# %s in %s\n", node->getName().c_str(), filename.c_str()); return fopen(filename.c_str(), "w"); } } // namespace class JavaInterface : public Java { // TODO: Move to Java void visitInterfaceElement(const Interface* interface, Node* element) { if (dynamic_cast<Interface*>(element)) { // Do not process Constructor. return; } optionalStage = 0; do { optionalCount = 0; element->accept(this); ++optionalStage; } while (optionalStage <= optionalCount); } public: JavaInterface(const char* source, FILE* file, const char* indent = "es") : Java(source, file, indent) { } virtual void at(const ExceptDcl* node) { writetab(); if (node->getJavadoc().size()) { write("%s\n", node->getJavadoc().c_str()); writetab(); } write("public class %s extends RuntimeException {\n", node->getName().c_str()); // TODO(Shiki): Need a constructor. printChildren(node); writeln("}"); } virtual void at(const Interface* node) { if (!currentNode) { currentNode = node->getParent(); } assert(!(node->getAttr() & Interface::Supplemental) && !node->isLeaf()); writetab(); if (node->getJavadoc().size()) { write("%s\n", node->getJavadoc().c_str()); writetab(); } std::string name = node->getQualifiedName(); name = getInterfaceName(name); write("public interface %s", name.substr(name.rfind(':') + 1).c_str()); if (node->getExtends()) { const char* separator = " extends "; for (NodeList::iterator i = node->getExtends()->begin(); i != node->getExtends()->end(); ++i) { if ((*i)->getName() == Node::getBaseObjectName()) { // Do not extend from 'Object'. continue; } write(separator); separator = ", "; (*i)->accept(this); } } write(" {\n"); for (NodeList::iterator i = node->begin(); i != node->end(); ++i) { visitInterfaceElement(node, *i); } // Expand mixins std::list<const Interface*> interfaceList; node->collectMixins(&interfaceList, node); for (std::list<const Interface*>::const_iterator i = interfaceList.begin(); i != interfaceList.end(); ++i) { if (*i == node) { continue; } writeln("// %s", (*i)->getName().c_str()); const Node* saved = currentNode; for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) { currentNode = *i; visitInterfaceElement(*i, *j); } currentNode = saved; } writeln("}"); } virtual void at(const BinaryExpr* node) { node->getLeft()->accept(this); write(" %s ", node->getName().c_str()); node->getRight()->accept(this); } virtual void at(const UnaryExpr* node) { write("%s", node->getName().c_str()); NodeList::iterator elem = node->begin(); (*elem)->accept(this); } virtual void at(const GroupingExpression* node) { write("("); NodeList::iterator elem = node->begin(); (*elem)->accept(this); write(")"); } virtual void at(const Literal* node) { write("%s", node->getName().c_str()); } virtual void at(const Member* node) { if (node->isTypedef(node->getParent())) { node->getSpec()->accept(this); } } virtual void at(const ArrayDcl* node) { assert(!node->isLeaf()); if (node->isTypedef(node->getParent())) { return; } writetab(); node->getSpec()->accept(this); write(" %s", node->getName().c_str()); for (NodeList::iterator i = node->begin(); i != node->end(); ++i) { write("["); (*i)->accept(this); write("]"); } if (node->isTypedef(node->getParent())) { write(";\n"); } } virtual void at(const ConstDcl* node) { writetab(); if (node->getJavadoc().size()) { write("%s\n", node->getJavadoc().c_str()); writetab(); } write("public static final "); node->getSpec()->accept(this); write(" %s = ", node->getName().c_str()); node->getExp()->accept(this); write(";\n"); } virtual void at(const Attribute* node) { writetab(); if (node->getJavadoc().size()) { write("%s\n", node->getJavadoc().c_str()); writetab(); } // getter Java::getter(node); write(";\n"); if (!node->isReadonly() || node->isPutForwards() || node->isReplaceable()) { // setter writetab(); Java::setter(node); write(";\n"); } } virtual void at(const OpDcl* node) { writetab(); if (node->getJavadoc().size()) { write("%s\n", node->getJavadoc().c_str()); writetab(); } Java::at(node); write(";\n"); } }; class JavaImport : public Visitor, public Formatter { std::string package; const Interface* current; bool printed; std::string prefixedName; std::set<std::string> importSet; public: JavaImport(std::string package, FILE* file, const char* indent) : Formatter(file, indent), package(package), current(0) { } virtual void at(const Node* node) { visitChildren(node); } virtual void at(const ScopedName* node) { assert(current); Node* resolved = node->search(current); node->check(resolved, "could not resolved %s.", node->getName().c_str()); if (dynamic_cast<Interface*>(resolved) || dynamic_cast<ExceptDcl*>(resolved)) { if (resolved->isBaseObject()) { return; } if (Module* module = dynamic_cast<Module*>(resolved->getParent())) { if (prefixedName != module->getPrefixedName()) { importSet.insert(Java::getPackageName(module->getPrefixedName()) + "." + node->getIdentifier()); } } } } virtual void at(const Interface* node) { if (current) { return; } current = node; if (Module* module = dynamic_cast<Module*>(node->getParent())) { prefixedName = module->getPrefixedName(); } visitChildren(node->getExtends()); visitChildren(node); // Expand mixins std::list<const Interface*> interfaceList; node->collectMixins(&interfaceList, node); for (std::list<const Interface*>::const_iterator i = interfaceList.begin(); i != interfaceList.end(); ++i) { if (*i == node) { continue; } current = *i; visitChildren(*i); } current = node; } virtual void at(const Attribute* node) { node->getSpec()->accept(this); visitChildren(node->getGetRaises()); if (!node->isReadonly() || node->isPutForwards() || node->isReplaceable()) { visitChildren(node->getSetRaises()); } } virtual void at(const OpDcl* node) { node->getSpec()->accept(this); visitChildren(node); visitChildren(node->getRaises()); } virtual void at(const ParamDcl* node) { node->getSpec()->accept(this); } void print() { if (importSet.empty()) { return; } for (std::set<std::string>::iterator i = importSet.begin(); i != importSet.end(); ++i) { write("import %s;\n", (*i).c_str()); } write("\n"); } }; class JavaVisitor : public Visitor { const char* source; const char* indent; std::string prefixedName; public: JavaVisitor(const char* source, const char* indent = "es") : source(source), indent(indent) { } virtual void at(const Node* node) { if (1 < node->getRank()) { return; } visitChildren(node); } virtual void at(const Module* node) { std::string enclosed = prefixedName; prefixedName = node->getPrefixedName(); at(static_cast<const Node*>(node)); prefixedName = enclosed; } virtual void at(const ExceptDcl* node) { if (1 < node->getRank() || node->isLeaf() || !node->isDefinedIn(source)) { return; } FILE* file = createFile(Java::getPackageName(prefixedName), node); if (!file) { return; } fprintf(file, "// Generated by esidl %s.\n\n", VERSION); fprintf(file, "package %s;\n\n", Java::getPackageName(prefixedName).c_str()); JavaInterface javaInterface(source, file, indent); javaInterface.at(node); fclose(file); } virtual void at(const Interface* node) { if (1 < node->getRank() || node->isLeaf() || !node->isDefinedIn(source) || (node->getAttr() & Interface::Supplemental)) { return; } FILE* file = createFile(Java::getPackageName(prefixedName), node); if (!file) { return; } fprintf(file, "// Generated by esidl %s.\n\n", VERSION); fprintf(file, "package %s;\n\n", Java::getPackageName(prefixedName).c_str()); JavaImport import(Java::getPackageName(prefixedName), file, indent); import.at(node); import.print(); JavaInterface javaInterface(source, file, indent); javaInterface.at(node); fclose(file); } }; void printJava(const char* source, const char* indent) { JavaVisitor visitor(source, indent); getSpecification()->accept(&visitor); } <commit_msg>(JavaImport) : Fix scope name resolution.<commit_after>/* * Copyright 2008, 2009 Google Inc. * Copyright 2007 Nintendo Co., Ltd. * * 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 <sys/stat.h> #include <sys/types.h> #include <set> #include "java.h" namespace { FILE* createFile(const std::string package, const Node* node) { std::string filename = package; size_t pos = 0; for (;;) { pos = filename.find('.', pos); if (pos == std::string::npos) { break; } filename[pos] = '/'; } filename += "/" + node->getName() + ".java"; std::string dir; std::string path(filename); for (;;) { size_t slash = path.find("/"); if (slash == std::string::npos) { break; } dir += path.substr(0, slash); path.erase(0, slash + 1); mkdir(dir.c_str(), 0777); dir += '/'; } printf("# %s in %s\n", node->getName().c_str(), filename.c_str()); return fopen(filename.c_str(), "w"); } } // namespace class JavaInterface : public Java { // TODO: Move to Java void visitInterfaceElement(const Interface* interface, Node* element) { if (dynamic_cast<Interface*>(element)) { // Do not process Constructor. return; } optionalStage = 0; do { optionalCount = 0; element->accept(this); ++optionalStage; } while (optionalStage <= optionalCount); } public: JavaInterface(const char* source, FILE* file, const char* indent = "es") : Java(source, file, indent) { } virtual void at(const ExceptDcl* node) { writetab(); if (node->getJavadoc().size()) { write("%s\n", node->getJavadoc().c_str()); writetab(); } write("public class %s extends RuntimeException {\n", node->getName().c_str()); // TODO(Shiki): Need a constructor. printChildren(node); writeln("}"); } virtual void at(const Interface* node) { if (!currentNode) { currentNode = node->getParent(); } assert(!(node->getAttr() & Interface::Supplemental) && !node->isLeaf()); writetab(); if (node->getJavadoc().size()) { write("%s\n", node->getJavadoc().c_str()); writetab(); } std::string name = node->getQualifiedName(); name = getInterfaceName(name); write("public interface %s", name.substr(name.rfind(':') + 1).c_str()); if (node->getExtends()) { const char* separator = " extends "; for (NodeList::iterator i = node->getExtends()->begin(); i != node->getExtends()->end(); ++i) { if ((*i)->getName() == Node::getBaseObjectName()) { // Do not extend from 'Object'. continue; } write(separator); separator = ", "; (*i)->accept(this); } } write(" {\n"); for (NodeList::iterator i = node->begin(); i != node->end(); ++i) { visitInterfaceElement(node, *i); } // Expand mixins std::list<const Interface*> interfaceList; node->collectMixins(&interfaceList, node); for (std::list<const Interface*>::const_iterator i = interfaceList.begin(); i != interfaceList.end(); ++i) { if (*i == node) { continue; } writeln("// %s", (*i)->getName().c_str()); const Node* saved = currentNode; for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) { currentNode = *i; visitInterfaceElement(*i, *j); } currentNode = saved; } writeln("}"); } virtual void at(const BinaryExpr* node) { node->getLeft()->accept(this); write(" %s ", node->getName().c_str()); node->getRight()->accept(this); } virtual void at(const UnaryExpr* node) { write("%s", node->getName().c_str()); NodeList::iterator elem = node->begin(); (*elem)->accept(this); } virtual void at(const GroupingExpression* node) { write("("); NodeList::iterator elem = node->begin(); (*elem)->accept(this); write(")"); } virtual void at(const Literal* node) { write("%s", node->getName().c_str()); } virtual void at(const Member* node) { if (node->isTypedef(node->getParent())) { node->getSpec()->accept(this); } } virtual void at(const ArrayDcl* node) { assert(!node->isLeaf()); if (node->isTypedef(node->getParent())) { return; } writetab(); node->getSpec()->accept(this); write(" %s", node->getName().c_str()); for (NodeList::iterator i = node->begin(); i != node->end(); ++i) { write("["); (*i)->accept(this); write("]"); } if (node->isTypedef(node->getParent())) { write(";\n"); } } virtual void at(const ConstDcl* node) { writetab(); if (node->getJavadoc().size()) { write("%s\n", node->getJavadoc().c_str()); writetab(); } write("public static final "); node->getSpec()->accept(this); write(" %s = ", node->getName().c_str()); node->getExp()->accept(this); write(";\n"); } virtual void at(const Attribute* node) { writetab(); if (node->getJavadoc().size()) { write("%s\n", node->getJavadoc().c_str()); writetab(); } // getter Java::getter(node); write(";\n"); if (!node->isReadonly() || node->isPutForwards() || node->isReplaceable()) { // setter writetab(); Java::setter(node); write(";\n"); } } virtual void at(const OpDcl* node) { writetab(); if (node->getJavadoc().size()) { write("%s\n", node->getJavadoc().c_str()); writetab(); } Java::at(node); write(";\n"); } }; class JavaImport : public Visitor, public Formatter { std::string package; const Interface* current; bool printed; std::string prefixedName; std::set<std::string> importSet; public: JavaImport(std::string package, FILE* file, const char* indent) : Formatter(file, indent), package(package), current(0) { } virtual void at(const Node* node) { visitChildren(node); } virtual void at(const ScopedName* node) { assert(current); Node* resolved = node->search(current); node->check(resolved, "could not resolved %s.", node->getName().c_str()); if (dynamic_cast<Interface*>(resolved) || dynamic_cast<ExceptDcl*>(resolved)) { if (resolved->isBaseObject()) { return; } if (Module* module = dynamic_cast<Module*>(resolved->getParent())) { if (prefixedName != module->getPrefixedName()) { importSet.insert(Java::getPackageName(module->getPrefixedName()) + "." + resolved->getName()); } } } } virtual void at(const Interface* node) { if (current) { return; } current = node; if (Module* module = dynamic_cast<Module*>(node->getParent())) { prefixedName = module->getPrefixedName(); } visitChildren(node->getExtends()); visitChildren(node); // Expand mixins std::list<const Interface*> interfaceList; node->collectMixins(&interfaceList, node); for (std::list<const Interface*>::const_iterator i = interfaceList.begin(); i != interfaceList.end(); ++i) { if (*i == node) { continue; } current = *i; visitChildren(*i); } current = node; } virtual void at(const Attribute* node) { node->getSpec()->accept(this); visitChildren(node->getGetRaises()); if (!node->isReadonly() || node->isPutForwards() || node->isReplaceable()) { visitChildren(node->getSetRaises()); } } virtual void at(const OpDcl* node) { node->getSpec()->accept(this); visitChildren(node); visitChildren(node->getRaises()); } virtual void at(const ParamDcl* node) { node->getSpec()->accept(this); } void print() { if (importSet.empty()) { return; } for (std::set<std::string>::iterator i = importSet.begin(); i != importSet.end(); ++i) { write("import %s;\n", (*i).c_str()); } write("\n"); } }; class JavaVisitor : public Visitor { const char* source; const char* indent; std::string prefixedName; public: JavaVisitor(const char* source, const char* indent = "es") : source(source), indent(indent) { } virtual void at(const Node* node) { if (1 < node->getRank()) { return; } visitChildren(node); } virtual void at(const Module* node) { std::string enclosed = prefixedName; prefixedName = node->getPrefixedName(); at(static_cast<const Node*>(node)); prefixedName = enclosed; } virtual void at(const ExceptDcl* node) { if (1 < node->getRank() || node->isLeaf() || !node->isDefinedIn(source)) { return; } FILE* file = createFile(Java::getPackageName(prefixedName), node); if (!file) { return; } fprintf(file, "// Generated by esidl %s.\n\n", VERSION); fprintf(file, "package %s;\n\n", Java::getPackageName(prefixedName).c_str()); JavaInterface javaInterface(source, file, indent); javaInterface.at(node); fclose(file); } virtual void at(const Interface* node) { if (1 < node->getRank() || node->isLeaf() || !node->isDefinedIn(source) || (node->getAttr() & Interface::Supplemental)) { return; } FILE* file = createFile(Java::getPackageName(prefixedName), node); if (!file) { return; } fprintf(file, "// Generated by esidl %s.\n\n", VERSION); fprintf(file, "package %s;\n\n", Java::getPackageName(prefixedName).c_str()); JavaImport import(Java::getPackageName(prefixedName), file, indent); import.at(node); import.print(); JavaInterface javaInterface(source, file, indent); javaInterface.at(node); fclose(file); } }; void printJava(const char* source, const char* indent) { JavaVisitor visitor(source, indent); getSpecification()->accept(&visitor); } <|endoftext|>
<commit_before>#include <iostream> #include <string> #include <fstream> #include <cstdint> using namespace std; template <typename T> struct Node { Node *left; Node *right; T data; }; template <typename T> class BinaryTree; template <typename T> std::ostream& operator<<(std::ostream&, const BinaryTree<T>&); template <typename T> class BinaryTree { private: Node<T>*root; int CountElements; public: BinaryTree(); ~BinaryTree(); Node<T>* root_()const; unsigned int count() const; void insert_node(const T&x); Node<T> *find_node(const T&, Node<T>*)const; void deleteNode(Node<T>* temp); void writing(const std::string& filename)const; friend std::ostream& operator<<<>(std::ostream&, const BinaryTree<T>&); }; template <typename T> BinaryTree<T>::BinaryTree() { root = nullptr; CountElements = 0; } template<typename T> Node<T>* BinaryTree<T>::root_() const { return root; } template <typename T> BinaryTree<T>::~BinaryTree() { deleteNode(root); } template<typename T> void BinaryTree<T>::insert_node(const T&x) { if (find_node(x, root_())) return; Node<T>* MyTree = new Node<T>; MyTree->data = x; MyTree->left = MyTree->right = 0; Node<T>* buff = root; Node<T>* temp = root; while (temp) { buff = temp; if (x < temp->data) temp = temp->left; else temp = temp->right; } if (!buff) root = MyTree; else { if (x < buff->data) buff->left = MyTree; else buff->right = MyTree; } ++CountElements; } template<typename T> Node<T>* BinaryTree<T>::find_node(const T& value, Node<T>* temp) const { if (temp == 0 || value == temp->data) return temp; if (value > temp->data) return find_node(value, temp->right); else return find_node(value, temp->left); } template<typename T> void BinaryTree<T>::deleteNode(Node<T>* temp) { if (!temp) { throw "error"; } if (temp->left) { deleteNode(temp->left); temp->left = nullptr; } if (temp->right) { deleteNode(temp->right); temp->right = nullptr; } delete temp; } template<typename T> void BinaryTree<T>::writing(const std::string& filename)const { ofstream file_1(filename); file_1 << CountElements << "\t"; output(file_1, root); file_1.close(); } template <typename T> std::ostream& output(std::ostream& ost, const Node<T>* node, unsigned int level) { if (!node) return ost; output(ost, node->right, level + 1); for (unsigned int i = 0; i < level; i++) ost << "\t"; ost << node->data << std::endl; output(ost, node->left, level + 1); return ost; } template <typename T> std::ostream& operator<<(std::ostream& ost, const BinaryTree<T>& temp) { output(ost, temp.root, 0); return ost; } <commit_msg>Update BinaryTree.hpp<commit_after>#include <iostream> #include <string> #include <fstream> #include <cstdint> using namespace std; template <typename T> struct Node { Node *left; Node *right; T data; }; template <typename T> class BinaryTree; template <typename T> std::ostream& operator<<(std::ostream&, const BinaryTree<T>&); template <typename T> class BinaryTree { private: Node<T>*root; int CountElements; public: BinaryTree(); ~BinaryTree(); Node<T>* root_()const; unsigned int count() const; void insert_node(const T&x); Node<T> *find_node(const T&, Node<T>*)const; void deleteNode(Node<T>* temp); void writing(const std::string& filename)const; friend std::ostream& operator<<<>(std::ostream&, const BinaryTree<T>&); }; template <typename T> BinaryTree<T>::BinaryTree() { root = nullptr; CountElements = 0; } template<typename T> Node<T>* BinaryTree<T>::root_() const { return root; } template <typename T> BinaryTree<T>::~BinaryTree() { deleteNode(root); } template<typename T> void BinaryTree<T>::insert_node(const T&x) { if (find_node(x, root_())) return; Node<T>* MyTree = new Node<T>; MyTree->data = x; MyTree->left = MyTree->right = 0; Node<T>* buff = root; Node<T>* temp = root; while (temp) { buff = temp; if (x < temp->data) temp = temp->left; else temp = temp->right; } if (!buff) root = MyTree; else { if (x < buff->data) buff->left = MyTree; else buff->right = MyTree; } ++CountElements; } template<typename T> Node<T>* BinaryTree<T>::find_node(const T& value, Node<T>* temp) const { if (temp == 0 || value == temp->data) return temp; if (value > temp->data) return find_node(value, temp->right); else return find_node(value, temp->left); } template<typename T> void BinaryTree<T>::deleteNode(Node<T>* temp) { if (!temp) { return; } if (temp->left) { deleteNode(temp->left); temp->left = nullptr; } if (temp->right) { deleteNode(temp->right); temp->right = nullptr; } delete temp; } template<typename T> void BinaryTree<T>::writing(const std::string& filename)const { ofstream file_1(filename); file_1 << CountElements << "\t"; output(file_1, root); file_1.close(); } template <typename T> std::ostream& output(std::ostream& ost, const Node<T>* node, unsigned int level) { if (!node) return ost; output(ost, node->right, level + 1); for (unsigned int i = 0; i < level; i++) ost << "\t"; ost << node->data << std::endl; output(ost, node->left, level + 1); return ost; } template <typename T> std::ostream& operator<<(std::ostream& ost, const BinaryTree<T>& temp) { output(ost, temp.root, 0); return ost; } <|endoftext|>
<commit_before>#include <iostream> #include <string> #include <fstream> #include <cstdint> using namespace std; template <class T> struct Node { T data; Node<T>* left; Node<T>* right; }; template <class T> class BinaryTree { private: Node<T> *root; uint16_t CountElements = 0; public: BinaryTree(); ~BinaryTree(); void deleteNode(Node<T>* temp); void insert_node(const T&); void print()const; Node<T>*root_(); Node<T> *find_node(const T&, Node<T>*)const; void reading(const std::string&); void output(std::ostream&,const Node<T>*); void writing(const std::string&)const; bool search_result(const T& value)const; Node<T>* get_pointer(const T& value, Node<T>* temp)const; friend std::ostream& show(std::ostream&, Node<T>*, unsigned int); friend std::ostream& operator<<(ostream&, BinaryTree<T>&); }; template<typename T> BinaryTree<T>::BinaryTree() { root = nullptr; } template<typename T> BinaryTree<T>::~BinaryTree() { deleteNode(root); } template<typename T> Node<T> *BinaryTree<T>::get_pointer(const T& value, Node<T>* temp)const { if (temp == 0 || value == temp->data) return temp; if (value > temp->data) return get_pointer(value, temp->right); else return get_pointer(value, temp->left); } template<typename T> Node<T>* BinaryTree<T>::root_() { return root; } template<typename T> bool BinaryTree<T>::search_result(const T& value)const { return get_pointer(value, root); } template<typename T> void BinaryTree<T>::deleteNode(Node<T>* temp) { if (!temp) return; if (temp->left) { deleteNode(temp->left); temp->left = nullptr; } if (temp->right) { deleteNode(temp->right); temp->right = nullptr; } delete temp; } template<typename T> void BinaryTree<T>::insert_node(const T&x) { if (find_node(x, root_())) return; Node<T>* MyTree = new Node<T>; MyTree->data = x; MyTree->left = MyTree->right = 0; Node<T>* buff = root; Node<T>* temp = root; while (temp) { buff = temp; if (x < temp->data) temp = temp->left; else temp = temp->right; } if (!buff) root = MyTree; else { if (x < buff->data) buff->left = MyTree; else buff->right = MyTree; } ++CountElements; } template<typename T> Node<T>* BinaryTree<T>::find_node(const T& value, Node<T>* temp) const { if (temp == 0 || value == temp->data) return temp; if (value > temp->data) return find_node(value, temp->right); else return find_node(value, temp->left); } template<typename T> void output(std::ostream& ost,const Node<T>* temp) { if (temp == nullptr) { return; } else { ost << temp->data << " "; output(ost, temp->left); output(ost, temp->right); } } template<typename T> void BinaryTree<T>::reading(const std::string& filename) { ifstream fin(filename); if (root != nullptr) deleteNode(root); int k; fin >> k; T temp; for (int i = 0; i < k; ++i) { fin >> temp; insert_node(temp); } fin.close(); } template<typename T> void BinaryTree<T>::writing(const std::string& filename)const { ofstream file_1(filename); file_1 << CountElements << "\t"; output(file_1, root); file_1.close(); } template<typename T> std::ostream& show(std::ostream& ost, Node<T>* temp, unsigned int level) { show(ost, temp->right, level + 1); for (unsigned int i = 0; i < level; i++) ost << "\t"; ost << temp->data << std::endl; show(ost, temp->left, level + 1); return ost; } template<typename T> std::ostream& operator<<(ostream& ost, BinaryTree<T>& temp) { show(ost, temp.root, 0); return ost; } <commit_msg>Update BinaryTree.hpp<commit_after>#include <iostream> #include <string> #include <fstream> #include <cstdint> using namespace std; template <class T> struct Node { T data; Node<T>* left; Node<T>* right; }; template<typename T> class BinaryTree; template<typename T> std::ostream& operator<<(ostream& ost, BinaryTree<T>& temp); template <class T> class BinaryTree { private: Node<T> *root; uint16_t CountElements = 0; public: BinaryTree(); ~BinaryTree(); void deleteNode(Node<T>* temp); void insert_node(const T&); void print()const; Node<T>*root_(); Node<T> *find_node(const T&, Node<T>*)const; void reading(const std::string&); void output(std::ostream&,const Node<T>*); void writing(const std::string&)const; bool search_result(const T& value)const; Node<T>* get_pointer(const T& value, Node<T>* temp)const; friend std::ostream& show(std::ostream&, Node<T>*, unsigned int); friend std::ostream& operator<<<>(ostream&, BinaryTree<T>&); }; template<typename T> BinaryTree<T>::BinaryTree() { root = nullptr; } template<typename T> BinaryTree<T>::~BinaryTree() { deleteNode(root); } template<typename T> Node<T> *BinaryTree<T>::get_pointer(const T& value, Node<T>* temp)const { if (temp == 0 || value == temp->data) return temp; if (value > temp->data) return get_pointer(value, temp->right); else return get_pointer(value, temp->left); } template<typename T> Node<T>* BinaryTree<T>::root_() { return root; } template<typename T> bool BinaryTree<T>::search_result(const T& value)const { return get_pointer(value, root); } template<typename T> void BinaryTree<T>::deleteNode(Node<T>* temp) { if (!temp) return; if (temp->left) { deleteNode(temp->left); temp->left = nullptr; } if (temp->right) { deleteNode(temp->right); temp->right = nullptr; } delete temp; } template<typename T> void BinaryTree<T>::insert_node(const T&x) { if (find_node(x, root_())) return; Node<T>* MyTree = new Node<T>; MyTree->data = x; MyTree->left = MyTree->right = 0; Node<T>* buff = root; Node<T>* temp = root; while (temp) { buff = temp; if (x < temp->data) temp = temp->left; else temp = temp->right; } if (!buff) root = MyTree; else { if (x < buff->data) buff->left = MyTree; else buff->right = MyTree; } ++CountElements; } template<typename T> Node<T>* BinaryTree<T>::find_node(const T& value, Node<T>* temp) const { if (temp == 0 || value == temp->data) return temp; if (value > temp->data) return find_node(value, temp->right); else return find_node(value, temp->left); } template<typename T> void output(std::ostream& ost,const Node<T>* temp) { if (temp == nullptr) { return; } else { ost << temp->data << " "; output(ost, temp->left); output(ost, temp->right); } } template<typename T> void BinaryTree<T>::reading(const std::string& filename) { ifstream fin(filename); if (root != nullptr) deleteNode(root); int k; fin >> k; T temp; for (int i = 0; i < k; ++i) { fin >> temp; insert_node(temp); } fin.close(); } template<typename T> void BinaryTree<T>::writing(const std::string& filename)const { ofstream file_1(filename); file_1 << CountElements << "\t"; output(file_1, root); file_1.close(); } template<typename T> std::ostream& show(std::ostream& ost, Node<T>* temp, unsigned int level) { show(ost, temp->right, level + 1); for (unsigned int i = 0; i < level; i++) ost << "\t"; ost << temp->data << std::endl; show(ost, temp->left, level + 1); return ost; } template<typename T> std::ostream& operator<<(ostream& ost, BinaryTree<T>& temp) { show(ost, temp.root, 0); return ost; } <|endoftext|>
<commit_before>#include <iostream> #include <string> #include <fstream> #include <cstdint> using namespace std; template <typename T> struct Node { Node *left; Node *right; T data; }; template <typename T> class BinaryTree; template <typename T> std::ostream& operator<<(std::ostream&, const BinaryTree<T>&); template <typename T> class BinaryTree { private: Node<T>*root; int count; public: BinaryTree(); ~BinaryTree(); Node<T>* root_(); int getCount()const; void insert_node(const T&x); Node<T> *find_node(const T&, Node<T>*)const; void remove_element(const T& temp); void deleteNode(Node<T>* temp); Node<T>* _deleteRoot(Node<T>* temp); void writing(const std::string& filename)const; friend std::ostream& operator<<<>(std::ostream&, const BinaryTree<T>&); }; template <typename T> BinaryTree<T>::BinaryTree() { root = nullptr; count = 0; } template<typename T> Node<T>* BinaryTree<T>::root_() { return root; count = 0; } template <typename T> BinaryTree<T>::~BinaryTree() { deleteNode(root); } template <typename T> int BinaryTree<T>::getCount()const { return count; } template<typename T> void BinaryTree<T>::insert_node(const T&x) { if (find_node(x, root_())) return; Node<T>* MyTree = new Node<T>; MyTree->data = x; MyTree->left = MyTree->right = 0; Node<T>* buff = root; Node<T>* temp = root; while (temp) { buff = temp; if (x < temp->data) temp = temp->left; else temp = temp->right; } if (!buff) root = MyTree; else { if (x < buff->data) buff->left = MyTree; else buff->right = MyTree; } ++count; } template<typename T> Node<T>* BinaryTree<T>::find_node(const T& data, Node<T>* temp) const { if (temp == 0 || data == temp->data) return temp; if (data > temp->data) return find_node(data, temp->right); else return find_node(data, temp->left); } template<typename T> void BinaryTree<T>::writing(const std::string& filename)const { ofstream file_1(filename); file_1 << count << "\t"; output(file_1, root); file_1.close(); } template<typename T> void BinaryTree<T>::deleteNode(Node<T>* temp) { if (!temp) { throw "error"; } if (temp->left) { deleteNode(temp->left); temp->left = nullptr; } if (temp->right) { deleteNode(temp->right); temp->right = nullptr; } delete temp; } template <typename T> std::ostream& output(std::ostream& ost, const Node<T>* node, unsigned int level) { if (!node) return ost; output(ost, node->right, level + 1); for (unsigned int i = 0; i < level; i++) ost << "\t"; ost << node->data << std::endl; output(ost, node->left, level + 1); return ost; } template <typename T> Node<T>* BinaryTree<T>::_deleteRoot(Node<T>* temp) { Node<T>* buff, *parent; if (temp) { buff = temp->right; if (!buff) { buff = temp->left; } else { if (buff->left) { parent = temp; while (buff->left) { parent = buff; buff = buff->left; } parent->left = buff->right; buff->right = temp->right; } buff->left = temp->left; } delete temp; return buff; } return nullptr; } template <typename T> void BinaryTree<T>::remove_element(const T& temp) { Node<T>* buff = root, *parent; if (root) { if (root->data == temp) { root = _deleteRoot(root); } else { parent = root; if (temp < parent->data) buff = parent->left; else buff = parent->right; while (buff) { if (buff->data == temp) { if (temp < parent->data) parent->left = _deleteRoot(parent->left); else parent->right = _deleteRoot(parent->right); return; } parent = buff; if (temp < parent->data) buff = parent->left; else buff = parent->right; } } } --count; } template <typename T> std::ostream& operator<<(std::ostream& ost, const BinaryTree<T>& temp) { output(ost, temp.root, 0); return ost; } <commit_msg>Update BinaryTree.hpp<commit_after>#include <iostream> #include <string> #include <fstream> #include <cstdint> using namespace std; template <typename T> struct Node { Node *left; Node *right; T data; }; template <typename T> class BinaryTree; template <typename T> std::ostream& operator<<(std::ostream&, const BinaryTree<T>&); template <typename T> class BinaryTree { private: Node<T>*root; int count; public: BinaryTree(); ~BinaryTree(); Node<T>* root_(); int getCount()const; void insert_node(const T&x); Node<T> *find_node(const T&, Node<T>*)const; void remove_element(const T& temp); void deleteNode(Node<T>* temp); Node<T>* _deleteRoot(Node<T>* temp); void writing(const std::string& filename)const; friend std::ostream& operator<<<>(std::ostream&, const BinaryTree<T>&); }; template <typename T> BinaryTree<T>::BinaryTree() { root = nullptr; count = 0; } template<typename T> Node<T>* BinaryTree<T>::root_() { return root; } template <typename T> BinaryTree<T>::~BinaryTree() { deleteNode(root); } template <typename T> int BinaryTree<T>::getCount()const { return count; } template<typename T> void BinaryTree<T>::insert_node(const T&x) { if (find_node(x, root_())) return; Node<T>* MyTree = new Node<T>; MyTree->data = x; MyTree->left = MyTree->right = 0; Node<T>* buff = root; Node<T>* temp = root; while (temp) { buff = temp; if (x < temp->data) temp = temp->left; else temp = temp->right; } if (!buff) root = MyTree; else { if (x < buff->data) buff->left = MyTree; else buff->right = MyTree; } ++count; } template<typename T> Node<T>* BinaryTree<T>::find_node(const T& data, Node<T>* temp) const { if (temp == 0 || data == temp->data) return temp; if (data > temp->data) return find_node(data, temp->right); else return find_node(data, temp->left); } template<typename T> void BinaryTree<T>::writing(const std::string& filename)const { ofstream file_1(filename); file_1 << count << "\t"; output(file_1, root); file_1.close(); } template<typename T> void BinaryTree<T>::deleteNode(Node<T>* temp) { if (!temp) { throw "error"; } if (temp->left) { deleteNode(temp->left); temp->left = nullptr; } if (temp->right) { deleteNode(temp->right); temp->right = nullptr; } delete temp; } template <typename T> std::ostream& output(std::ostream& ost, const Node<T>* node, unsigned int level) { if (!node) return ost; output(ost, node->right, level + 1); for (unsigned int i = 0; i < level; i++) ost << "\t"; ost << node->data << std::endl; output(ost, node->left, level + 1); return ost; } template <typename T> Node<T>* BinaryTree<T>::_deleteRoot(Node<T>* temp) { Node<T>* buff, *parent; if (temp) { buff = temp->right; if (!buff) { buff = temp->left; } else { if (buff->left) { parent = temp; while (buff->left) { parent = buff; buff = buff->left; } parent->left = buff->right; buff->right = temp->right; } buff->left = temp->left; } delete temp; return buff; } return nullptr; } template <typename T> void BinaryTree<T>::remove_element(const T& temp) { Node<T>* buff = root, *parent; if (root) { if (root->data == temp) { root = _deleteRoot(root); } else { parent = root; if (temp < parent->data) buff = parent->left; else buff = parent->right; while (buff) { if (buff->data == temp) { if (temp < parent->data) parent->left = _deleteRoot(parent->left); else parent->right = _deleteRoot(parent->right); return; } parent = buff; if (temp < parent->data) buff = parent->left; else buff = parent->right; } } } --count; } template <typename T> std::ostream& operator<<(std::ostream& ost, const BinaryTree<T>& temp) { output(ost, temp.root, 0); return ost; } <|endoftext|>
<commit_before>#pragma once //=====================================================================// /*! @file @brief GUI Widget ターミナル @author 平松邦仁 (hira@rvf-rc45.net) @copyright Copyright (C) 2017 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/glfw_app/blob/master/LICENSE */ //=====================================================================// #include "widgets/widget_director.hpp" #include "widgets/widget_frame.hpp" #include "utils/terminal.hpp" #include "core/glcore.hpp" namespace gui { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief GUI terminal クラス */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// struct widget_terminal : public widget { typedef widget_terminal value_type; typedef std::function< void(uint32_t ch) > input_func_type; typedef std::function< void(const utils::lstring& line) > enter_func_type; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief widget_terminal パラメーター */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// struct param { std::string font_; ///< ターミナル描画フォント uint32_t font_width_; ///< フォント幅(初期化で設定される) uint32_t font_height_; ///< フォント高 uint32_t height_; ///< 行の高さ bool echo_; ///< キー入力とエコー bool auto_fit_; ///< 等幅フォントに対するフレームの最適化 input_func_type input_func_; ///< 1文字入力毎に呼ぶ関数 enter_func_type enter_func_; ///< 「Enter」時に呼ぶ関数 param() : font_("Inconsolata"), font_width_(0), font_height_(18), height_(20), echo_(true), auto_fit_(true) { } }; widget_director& wd_; param param_; utils::terminal terminal_; uint32_t interval_; bool focus_; vtx::ipos scroll_ofs_; public: //-----------------------------------------------------------------// /*! @brief コンストラクター */ //-----------------------------------------------------------------// widget_terminal(widget_director& wd, const widget::param& bp, const param& p) : widget(bp), wd_(wd), param_(p), terminal_(), interval_(0), focus_(false), scroll_ofs_(0) { } //-----------------------------------------------------------------// /*! @brief デストラクター */ //-----------------------------------------------------------------// virtual ~widget_terminal() { } //-----------------------------------------------------------------// /*! @brief 型を取得 */ //-----------------------------------------------------------------// type_id type() const override { return get_type_id<value_type>(); } //-----------------------------------------------------------------// /*! @brief widget 型の基本名称を取得 @return widget 型の基本名称 */ //-----------------------------------------------------------------// const char* type_name() const override { return "terminal"; } //-----------------------------------------------------------------// /*! @brief ハイブリッド・ウィジェットのサイン @return ハイブリッド・ウィジェットの場合「true」を返す。 */ //-----------------------------------------------------------------// bool hybrid() const override { return false; } //-----------------------------------------------------------------// /*! @brief 個別パラメーターへの取得(ro) @return 個別パラメーター */ //-----------------------------------------------------------------// const param& get_local_param() const { return param_; } //-----------------------------------------------------------------// /*! @brief 個別パラメーターへの取得 @return 個別パラメーター */ //-----------------------------------------------------------------// param& at_local_param() { return param_; } //-----------------------------------------------------------------// /*! @brief ターミナル・インスタンスへの参照 @return ターミナル・インスタンス */ //-----------------------------------------------------------------// utils::terminal& at_terminal() { return terminal_; } //-----------------------------------------------------------------// /*! @brief 1文字出力 @param[in] wch 文字 */ //-----------------------------------------------------------------// void output(uint32_t wch) { terminal_.output(wch); } //-----------------------------------------------------------------// /*! @brief テキストの出力 @param[in] text テキスト */ //-----------------------------------------------------------------// void output(const std::string& text) { if(text.empty()) return; auto ls = utils::utf8_to_utf32(text); for(auto ch : ls) { output(ch); } } //-----------------------------------------------------------------// /*! @brief 初期化 */ //-----------------------------------------------------------------// void initialize() override { at_param().state_.set(widget::state::POSITION_LOCK); at_param().state_.set(widget::state::SIZE_LOCK); at_param().state_.set(widget::state::RESIZE_H_ENABLE, false); at_param().state_.set(widget::state::RESIZE_V_ENABLE, false); at_param().state_.set(widget::state::SERVICE); at_param().state_.set(widget::state::MOVE_ROOT, false); at_param().state_.set(widget::state::RESIZE_ROOT); at_param().state_.set(widget::state::CLIP_PARENTS); at_param().state_.set(widget::state::AREA_ROOT); using namespace gl; core& core = core::get_instance(); fonts& fonts = core.at_fonts(); fonts.push_font_face(); fonts.set_font_type(param_.font_); fonts.set_font_size(param_.font_height_); fonts.enable_proportional(false); fonts.set_spaceing(0); param_.font_width_ = fonts.get_width(' '); fonts.pop_font_face(); } //-----------------------------------------------------------------// /*! @brief アップデート */ //-----------------------------------------------------------------// void update() override { if(wd_.get_focus_widget() == this || wd_.get_focus_widget() == wd_.root_widget(this)) { focus_ = true; } else { focus_ = false; } if(get_focus()) { const vtx::spos& scr = wd_.get_scroll(); scroll_ofs_ += scr; if(scroll_ofs_.y < 0) scroll_ofs_.y = 0; } if(get_param().parents_ && get_state(widget::state::AREA_ROOT)) { if(get_param().parents_->type() == get_type_id<widget_frame>()) { // 親になってるフレームを取得 widget_frame* w = static_cast<widget_frame*>(at_param().parents_); if(w) { bool resize = false; vtx::irect sr = w->get_draw_area(); if(param_.auto_fit_) { vtx::ipos ss(sr.size.x / param_.font_width_, sr.size.y / param_.height_); ss.x *= param_.font_width_; // if(ss.x < w->get_param().resize_min_.x) { // ss.x = w->get_param().resize_min_.x / param_.font_width_; // ss.x *= param_.font_width_; // } ss.y *= param_.height_; // if(ss.y < w->get_param().resize_min_.y) { // ss.y = w->get_param().resize_min_.y / param_.height_; // ss.y *= param_.height_; // } w->set_draw_area(ss); sr = w->get_draw_area(); } if(sr.size != get_rect().size) resize = true; at_rect() = sr; if(resize) { } } } } } //-----------------------------------------------------------------// /*! @brief サービス */ //-----------------------------------------------------------------// void service() override { if(!get_state(state::ENABLE)) { focus_ = false; return; } if(focus_) { if(param_.echo_) { auto s = wd_.at_keyboard().input(); terminal_.output(s); if(!s.empty()) { if(param_.input_func_ != nullptr) { for(auto ch : s) { param_.input_func_(ch); } } if(param_.enter_func_ != nullptr && terminal_.get_last_char() == 0x0D) { param_.enter_func_(terminal_.get_last_text32()); } } } } } //-----------------------------------------------------------------// /*! @brief レンダリング */ //-----------------------------------------------------------------// void render() override { using namespace gl; core& core = core::get_instance(); const vtx::spos& vsz = core.get_size(); // const vtx::spos& siz = core.get_rect().size; gl::fonts& fonts = core.at_fonts(); const widget::param& wp = get_param(); if(wp.clip_.size.x > 0 && wp.clip_.size.y > 0) { glPushMatrix(); vtx::irect rect; if(wp.state_[widget::state::CLIP_PARENTS]) { rect.org = wp.rpos_; rect.size = wp.rect_.size; } else { rect.org.set(0); rect.size = wp.rect_.size; } fonts.push_font_face(); fonts.set_font_type(param_.font_); fonts.set_font_size(param_.font_height_); vtx::irect clip_ = wp.clip_; // float sx = vsz.x / siz.x; float sx = core.get_dpi_scale(); // float sy = vsz.y / siz.y; float sy = core.get_dpi_scale(); glViewport(clip_.org.x * sx, vsz.y - clip_.org.y * sy - clip_.size.y * sy, clip_.size.x * sx, clip_.size.y * sy); fonts.setup_matrix(clip_.size.x, clip_.size.y); fonts.enable_center(false); fonts.enable_proportional(false); const img::rgbaf& cf = wd_.get_color(); vtx::ipos limit(clip_.size.x / param_.font_width_, clip_.size.y / param_.height_); vtx::ipos chs(rect.org); auto ln = terminal_.get_line_num(); vtx::ipos ofs(0); if(ln > limit.y) ofs.y = ln - limit.y; auto npy = ofs.y - scroll_ofs_.y; if(npy < 0) { npy = 0; scroll_ofs_.y = ofs.y; } else if(npy > ofs.y) { npy = ofs.y; } ofs.y = npy; vtx::ipos pos; for(pos.y = 0; pos.y < limit.y; ++pos.y) { for(pos.x = 0; pos.x < limit.x; ++pos.x) { const auto& t = terminal_.get_char(pos + ofs); img::rgba8 fc = t.fc_; fc *= cf.r; fc.alpha_scale(cf.a); fonts.set_fore_color(fc); img::rgba8 bc = t.bc_; bc *= cf.r; bc.alpha_scale(cf.a); fonts.set_back_color(bc); if(focus_ && (pos + ofs) == terminal_.get_cursor()) { if((interval_ % 40) < 20) { fonts.swap_color(); } } auto cha = t.cha_; if(cha < 0x20) cha = 0x3F; // 制御コードは DEL-char として扱う if(cha > 0x7f) { fonts.pop_font_face(); } int fw = fonts.get_width(cha); vtx::irect br(chs, vtx::ipos(fw, param_.height_)); fonts.draw_back(br); chs.x += fonts.draw(chs, cha); fonts.swap_color(false); if(cha > 0x7f) { fonts.push_font_face(); fonts.set_font_type(param_.font_); } } chs.y += param_.height_; chs.x = rect.org.x; } ++interval_; fonts.restore_matrix(); fonts.pop_font_face(); glPopMatrix(); glViewport(0, 0, vsz.x, vsz.y); } } //-----------------------------------------------------------------// /*! @brief 状態のセーブ @param[in] pre プリファレンス参照 @return エラーが無い場合「true」 */ //-----------------------------------------------------------------// bool save(sys::preference& pre) override { return false; } //-----------------------------------------------------------------// /*! @brief 状態のロード @param[in] pre プリファレンス参照 @return エラーが無い場合「true」 */ //-----------------------------------------------------------------// bool load(const sys::preference& pre) override { return false; } }; } <commit_msg>update: comment<commit_after>#pragma once //=====================================================================// /*! @file @brief GUI Widget ターミナル @author 平松邦仁 (hira@rvf-rc45.net) @copyright Copyright (C) 2017 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/glfw_app/blob/master/LICENSE */ //=====================================================================// #include "widgets/widget_director.hpp" #include "widgets/widget_frame.hpp" #include "utils/terminal.hpp" #include "core/glcore.hpp" namespace gui { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief GUI terminal クラス */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// struct widget_terminal : public widget { typedef widget_terminal value_type; typedef std::function< void(uint32_t ch) > input_func_type; typedef std::function< void(const utils::lstring& line) > enter_func_type; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief widget_terminal パラメーター */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// struct param { std::string font_; ///< ターミナル描画フォント uint32_t font_width_; ///< フォント幅(初期化で設定される) uint32_t font_height_; ///< フォント高 uint32_t height_; ///< 行の高さ bool echo_; ///< キー入力とエコー bool auto_fit_; ///< 等幅フォントに対するフレームの最適化 input_func_type input_func_; ///< 1文字入力毎に呼ぶ関数 enter_func_type enter_func_; ///< 「Enter」時に呼ぶ関数 param() : font_("Inconsolata"), font_width_(0), font_height_(18), height_(20), echo_(true), auto_fit_(true) { } }; widget_director& wd_; param param_; utils::terminal terminal_; uint32_t interval_; bool focus_; vtx::ipos scroll_ofs_; public: //-----------------------------------------------------------------// /*! @brief コンストラクター */ //-----------------------------------------------------------------// widget_terminal(widget_director& wd, const widget::param& bp, const param& p) : widget(bp), wd_(wd), param_(p), terminal_(), interval_(0), focus_(false), scroll_ofs_(0) { } //-----------------------------------------------------------------// /*! @brief デストラクター */ //-----------------------------------------------------------------// virtual ~widget_terminal() { } //-----------------------------------------------------------------// /*! @brief 型を取得 */ //-----------------------------------------------------------------// type_id type() const override { return get_type_id<value_type>(); } //-----------------------------------------------------------------// /*! @brief widget 型の基本名称を取得 @return widget 型の基本名称 */ //-----------------------------------------------------------------// const char* type_name() const override { return "terminal"; } //-----------------------------------------------------------------// /*! @brief ハイブリッド・ウィジェットのサイン @return ハイブリッド・ウィジェットの場合「true」を返す。 */ //-----------------------------------------------------------------// bool hybrid() const override { return false; } //-----------------------------------------------------------------// /*! @brief 個別パラメーターへの取得(ro) @return 個別パラメーター */ //-----------------------------------------------------------------// const param& get_local_param() const { return param_; } //-----------------------------------------------------------------// /*! @brief 個別パラメーターへの取得 @return 個別パラメーター */ //-----------------------------------------------------------------// param& at_local_param() { return param_; } //-----------------------------------------------------------------// /*! @brief ターミナル・インスタンスへの参照 @return ターミナル・インスタンス */ //-----------------------------------------------------------------// utils::terminal& at_terminal() { return terminal_; } //-----------------------------------------------------------------// /*! @brief 1文字出力 @param[in] wch 文字 */ //-----------------------------------------------------------------// void output(uint32_t wch) { terminal_.output(wch); } //-----------------------------------------------------------------// /*! @brief テキストの出力 @param[in] text テキスト */ //-----------------------------------------------------------------// void output(const std::string& text) { if(text.empty()) return; auto ls = utils::utf8_to_utf32(text); for(auto ch : ls) { output(ch); } } //-----------------------------------------------------------------// /*! @brief 初期化 */ //-----------------------------------------------------------------// void initialize() override { at_param().state_.set(widget::state::POSITION_LOCK); at_param().state_.set(widget::state::SIZE_LOCK); at_param().state_.set(widget::state::RESIZE_H_ENABLE, false); at_param().state_.set(widget::state::RESIZE_V_ENABLE, false); at_param().state_.set(widget::state::SERVICE); at_param().state_.set(widget::state::MOVE_ROOT, false); at_param().state_.set(widget::state::RESIZE_ROOT); at_param().state_.set(widget::state::CLIP_PARENTS); at_param().state_.set(widget::state::AREA_ROOT); using namespace gl; core& core = core::get_instance(); fonts& fonts = core.at_fonts(); fonts.push_font_face(); fonts.set_font_type(param_.font_); fonts.set_font_size(param_.font_height_); fonts.enable_proportional(false); fonts.set_spaceing(0); param_.font_width_ = fonts.get_width(' '); fonts.pop_font_face(); } //-----------------------------------------------------------------// /*! @brief アップデート */ //-----------------------------------------------------------------// void update() override { if(wd_.get_focus_widget() == this || wd_.get_focus_widget() == wd_.root_widget(this)) { focus_ = true; } else { focus_ = false; } // スクロール処理、マウスホイール if(get_focus()) { const vtx::spos& scr = wd_.get_scroll(); scroll_ofs_ += scr; if(scroll_ofs_.y < 0) scroll_ofs_.y = 0; } if(get_param().parents_ && get_state(widget::state::AREA_ROOT)) { if(get_param().parents_->type() == get_type_id<widget_frame>()) { // 親になってるフレームを取得 widget_frame* w = static_cast<widget_frame*>(at_param().parents_); if(w) { bool resize = false; vtx::irect sr = w->get_draw_area(); if(param_.auto_fit_) { vtx::ipos ss(sr.size.x / param_.font_width_, sr.size.y / param_.height_); ss.x *= param_.font_width_; // if(ss.x < w->get_param().resize_min_.x) { // ss.x = w->get_param().resize_min_.x / param_.font_width_; // ss.x *= param_.font_width_; // } ss.y *= param_.height_; // if(ss.y < w->get_param().resize_min_.y) { // ss.y = w->get_param().resize_min_.y / param_.height_; // ss.y *= param_.height_; // } w->set_draw_area(ss); sr = w->get_draw_area(); } if(sr.size != get_rect().size) resize = true; at_rect() = sr; if(resize) { } } } } } //-----------------------------------------------------------------// /*! @brief サービス */ //-----------------------------------------------------------------// void service() override { if(!get_state(state::ENABLE)) { focus_ = false; return; } if(focus_) { if(param_.echo_) { auto s = wd_.at_keyboard().input(); terminal_.output(s); if(!s.empty()) { if(param_.input_func_ != nullptr) { for(auto ch : s) { param_.input_func_(ch); } } if(param_.enter_func_ != nullptr && terminal_.get_last_char() == 0x0D) { param_.enter_func_(terminal_.get_last_text32()); } } } } } //-----------------------------------------------------------------// /*! @brief レンダリング */ //-----------------------------------------------------------------// void render() override { using namespace gl; core& core = core::get_instance(); const vtx::spos& vsz = core.get_size(); // const vtx::spos& siz = core.get_rect().size; gl::fonts& fonts = core.at_fonts(); const widget::param& wp = get_param(); if(wp.clip_.size.x > 0 && wp.clip_.size.y > 0) { glPushMatrix(); vtx::irect rect; if(wp.state_[widget::state::CLIP_PARENTS]) { rect.org = wp.rpos_; rect.size = wp.rect_.size; } else { rect.org.set(0); rect.size = wp.rect_.size; } fonts.push_font_face(); fonts.set_font_type(param_.font_); fonts.set_font_size(param_.font_height_); vtx::irect clip_ = wp.clip_; // float sx = vsz.x / siz.x; float sx = core.get_dpi_scale(); // float sy = vsz.y / siz.y; float sy = core.get_dpi_scale(); glViewport(clip_.org.x * sx, vsz.y - clip_.org.y * sy - clip_.size.y * sy, clip_.size.x * sx, clip_.size.y * sy); fonts.setup_matrix(clip_.size.x, clip_.size.y); fonts.enable_center(false); fonts.enable_proportional(false); const img::rgbaf& cf = wd_.get_color(); vtx::ipos limit(clip_.size.x / param_.font_width_, clip_.size.y / param_.height_); vtx::ipos chs(rect.org); auto ln = terminal_.get_line_num(); vtx::ipos ofs(0); if(ln > limit.y) ofs.y = ln - limit.y; auto npy = ofs.y - scroll_ofs_.y; if(npy < 0) { npy = 0; scroll_ofs_.y = ofs.y; } else if(npy > ofs.y) { npy = ofs.y; } ofs.y = npy; vtx::ipos pos; for(pos.y = 0; pos.y < limit.y; ++pos.y) { for(pos.x = 0; pos.x < limit.x; ++pos.x) { const auto& t = terminal_.get_char(pos + ofs); img::rgba8 fc = t.fc_; fc *= cf.r; fc.alpha_scale(cf.a); fonts.set_fore_color(fc); img::rgba8 bc = t.bc_; bc *= cf.r; bc.alpha_scale(cf.a); fonts.set_back_color(bc); if(focus_ && (pos + ofs) == terminal_.get_cursor()) { if((interval_ % 40) < 20) { fonts.swap_color(); } } auto cha = t.cha_; if(cha < 0x20) cha = 0x3F; // 制御コードは DEL-char として扱う if(cha > 0x7f) { fonts.pop_font_face(); } int fw = fonts.get_width(cha); vtx::irect br(chs, vtx::ipos(fw, param_.height_)); fonts.draw_back(br); chs.x += fonts.draw(chs, cha); fonts.swap_color(false); if(cha > 0x7f) { fonts.push_font_face(); fonts.set_font_type(param_.font_); } } chs.y += param_.height_; chs.x = rect.org.x; } ++interval_; fonts.restore_matrix(); fonts.pop_font_face(); glPopMatrix(); glViewport(0, 0, vsz.x, vsz.y); } } //-----------------------------------------------------------------// /*! @brief 状態のセーブ @param[in] pre プリファレンス参照 @return エラーが無い場合「true」 */ //-----------------------------------------------------------------// bool save(sys::preference& pre) override { return false; } //-----------------------------------------------------------------// /*! @brief 状態のロード @param[in] pre プリファレンス参照 @return エラーが無い場合「true」 */ //-----------------------------------------------------------------// bool load(const sys::preference& pre) override { return false; } }; } <|endoftext|>
<commit_before> #include "cmdline/cmdline.h" #include "mhap/overlap.h" #include "mhap/parser.h" #include "ra/include/ra/ra.hpp" #include <algorithm> #include <ctime> #include <fstream> #include <iostream> #include <vector> #include <sys/stat.h> // trimming params int READ_LEN_THRESHOLD = 100000; // BFS params in bubble popping size_t MAX_NODES = 750; int MAX_DISTANCE = MAX_NODES * 10000; double MAX_DIFFERENCE = 0.25; // contig extraction params size_t MAX_BRANCHES = 16; size_t MAX_START_NODES = 30; using std::cerr; using std::cin; using std::cout; using std::endl; using std::fstream; using std::max; using std::string; using std::vector; // map reads so we can access reads with mapped[read_id] void map_reads(vector<Read*>* mapped, vector<Read*>& reads) { int max_id = -1; for (auto r: reads) { max_id = max(max_id, r->getId()); } mapped->resize(max_id + 1, nullptr); for (auto r: reads) { (*mapped)[r->getId()] = r; } } string output_dir_name() { time_t rawtime; struct tm* timeinfo; char buffer[80]; time(&rawtime); timeinfo = localtime(&rawtime); strftime(buffer, 80, "layout_%Y%m%d_%H%M%S", timeinfo); return string(buffer); } void must_mkdir(const string& path) { if (mkdir(path.c_str(), 0755) == -1) { fprintf(stderr, "Can't create directory %s\n", path.c_str()); exit(1); } } void print_contigs_info(const vector<Contig *>& contigs, const vector<Read*>& reads) { for (uint32_t i = 0; i < contigs.size(); ++i) { const auto& contig = contigs[i]; const auto& parts = contig->getParts(); const auto& last_part = contig->getParts().back(); fprintf(stdout, "contig %u; length: ≈%lu, reads: %lu\n", i, last_part.offset + reads[last_part.src]->getLength(), parts.size() ); for (const auto& p: parts) { fprintf(stdout, "%d ", p.src); } fprintf(stdout, "\n"); } } int main(int argc, char **argv) { cmdline::parser args; // input params args.add<string>("reads", 'r', "reads file", true); args.add<string>("reads_format", 's', "reads format; supported: fasta, fastq, afg", false, "fasta"); args.add<int>("reads_id_offset", 'a', "reads id offset (first read id)", false, 0); args.add<string>("overlaps", 'x', "overlaps file", true); args.add<string>("overlaps_format", 'f', "overlaps file format; supported: afg, mhap", false, "afg"); args.add<bool>("verbose", 'v', "verbose output", false); // bubble popping params args.add<int>("bp_max_nodes", 'm', "max nodes in bubble branch", false, 750); args.add<double>("bp_max_diff", 'n', "max difference between bubble branches", false, 0.25); args.parse_check(argc, argv); const int thread_num = std::max(std::thread::hardware_concurrency(), 1U); const string reads_filename = args.get<string>("reads"); const string reads_format = args.get<string>("reads_format"); const string overlaps_filename = args.get<string>("overlaps"); const string overlaps_format = args.get<string>("overlaps_format"); const bool verbose_output = args.get<bool>("verbose"); const int reads_id_offset = args.get<int>("reads_id_offset"); const string output_dir = output_dir_name(); MAX_NODES = args.get<int>("bp_max_nodes"); MAX_DISTANCE = MAX_NODES * 10000; MAX_DIFFERENCE = args.get<double>("bp_max_diff"); vector<Overlap*> overlaps, filtered; vector<Read*> reads; vector<Read*> reads_mapped; must_mkdir(output_dir); std::cerr << "Output dir: " << output_dir << std::endl; if (reads_format == "fasta") { readFastaReads(reads, reads_filename.c_str()); } else if (reads_format == "fastq") { readFastqReads(reads, reads_filename.c_str()); } else if (reads_format == "afg") { readAfgReads(reads, reads_filename.c_str()); } else { assert(false); } // map reads so we have reads_mapped[read_id] -> read map_reads(&reads_mapped, reads); std::cerr << "Read " << reads.size() << " reads" << std::endl; if (overlaps_format == "afg") { readAfgOverlaps(overlaps, overlaps_filename.c_str()); } else if (overlaps_format == "mhap") { fstream overlaps_file(overlaps_filename); MHAP::read_overlaps(overlaps_file, &overlaps); overlaps_file.close(); } else { assert(false); } // fix overlap read ids for (auto o: overlaps) { o->setA(o->getA() - reads_id_offset); o->setB(o->getB() - reads_id_offset); } for (auto o: overlaps) { const auto a = o->getA(); const auto b = o->getB(); if (reads_mapped[a] == nullptr) { cerr << "Read " << a << " not found" << endl; exit(1); } if (reads_mapped[b] == nullptr) { cerr << "Read " << b << " not found" << endl; exit(1); } o->setReadA(reads_mapped[a]); o->setReadB(reads_mapped[b]); } cerr << overlaps.size() << " overlaps read" << endl; vector<Overlap*> nocontainments; filterContainedOverlaps(nocontainments, overlaps, reads_mapped, true); if (verbose_output) { writeOverlaps(nocontainments, (output_dir + "/nocont.afg").c_str()); } vector<Overlap*> notransitives; filterTransitiveOverlaps(notransitives, nocontainments, thread_num, true); if (verbose_output) { writeOverlaps(notransitives, (output_dir + "/nocont.notran.afg").c_str()); } createReverseComplements(reads, thread_num); StringGraph* graph = new StringGraph(reads, notransitives); graph->simplify(); if (verbose_output) { vector<Overlap*> simplified_overlaps; graph->extractOverlaps(simplified_overlaps); writeOverlaps(simplified_overlaps, (output_dir + "/simplified.afg").c_str()); } std::vector<StringGraphComponent*> components; graph->extractComponents(components); std::vector<Contig*> contigs; auto contigs_fast = fopen((output_dir + "/contigs_fast.fasta").c_str(), "w"); int idx = 0; for (const auto& component : components) { string seq; component->extractSequence(seq); fprintf(contigs_fast, ">seq%d\n", idx); fprintf(contigs_fast, "%s\n", seq.c_str()); idx++; ContigExtractor* extractor = new ContigExtractor(component); const auto& contig = extractor->extractContig(); if (contig == nullptr) { continue; } contigs.emplace_back(contig); } fclose(contigs_fast); std::cerr << "number of contigs " << contigs.size() << std::endl; print_contigs_info(contigs, reads_mapped); writeAfgContigs(contigs, (output_dir + "/contigs.afg").c_str()); for (auto r: reads) delete r; for (auto o: overlaps) delete o; for (auto c: components) delete c; for (auto c: contigs) delete c; delete graph; return 0; } <commit_msg>change BP params, add filtering reads with len < 3k<commit_after> #include "cmdline/cmdline.h" #include "mhap/overlap.h" #include "mhap/parser.h" #include "ra/include/ra/ra.hpp" #include <algorithm> #include <ctime> #include <fstream> #include <iostream> #include <vector> #include <sys/stat.h> // trimming params int READ_LEN_THRESHOLD = 100000; // BFS params in bubble popping size_t MAX_NODES = 100; int MAX_DISTANCE = MAX_NODES * 10000; double MAX_DIFFERENCE = 0.25; // contig extraction params size_t MAX_BRANCHES = 18; size_t MAX_START_NODES = 30; using std::cerr; using std::cin; using std::cout; using std::endl; using std::fstream; using std::max; using std::string; using std::vector; // map reads so we can access reads with mapped[read_id] void map_reads(vector<Read*>* mapped, vector<Read*>& reads) { int max_id = -1; for (auto r: reads) { max_id = max(max_id, r->getId()); } mapped->resize(max_id + 1, nullptr); for (auto r: reads) { (*mapped)[r->getId()] = r; } } string output_dir_name() { time_t rawtime; struct tm* timeinfo; char buffer[80]; time(&rawtime); timeinfo = localtime(&rawtime); strftime(buffer, 80, "layout_%Y%m%d_%H%M%S", timeinfo); return string(buffer); } void must_mkdir(const string& path) { if (mkdir(path.c_str(), 0755) == -1) { fprintf(stderr, "Can't create directory %s\n", path.c_str()); exit(1); } } void print_contigs_info(const vector<Contig *>& contigs, const vector<Read*>& reads) { for (uint32_t i = 0; i < contigs.size(); ++i) { const auto& contig = contigs[i]; const auto& parts = contig->getParts(); const auto& last_part = contig->getParts().back(); fprintf(stdout, "contig %u; length: ≈%lu, reads: %lu\n", i, last_part.offset + reads[last_part.src]->getLength(), parts.size() ); for (const auto& p: parts) { fprintf(stdout, "%d ", p.src); } fprintf(stdout, "\n"); } } int main(int argc, char **argv) { cmdline::parser args; // input params args.add<string>("reads", 'r', "reads file", true); args.add<string>("reads_format", 's', "reads format; supported: fasta, fastq, afg", false, "fasta"); args.add<int>("reads_id_offset", 'a', "reads id offset (first read id)", false, 0); args.add<string>("overlaps", 'x', "overlaps file", true); args.add<string>("overlaps_format", 'f', "overlaps file format; supported: afg, mhap", false, "afg"); args.add<bool>("verbose", 'v', "verbose output", false); // bubble popping params args.add<int>("bp_max_nodes", 'm', "max nodes in bubble branch", false, 750); args.add<double>("bp_max_diff", 'n', "max difference between bubble branches", false, 0.25); args.parse_check(argc, argv); const int thread_num = std::max(std::thread::hardware_concurrency(), 1U); const string reads_filename = args.get<string>("reads"); const string reads_format = args.get<string>("reads_format"); const string overlaps_filename = args.get<string>("overlaps"); const string overlaps_format = args.get<string>("overlaps_format"); const bool verbose_output = args.get<bool>("verbose"); const int reads_id_offset = args.get<int>("reads_id_offset"); const string output_dir = output_dir_name(); MAX_NODES = args.get<int>("bp_max_nodes"); MAX_DISTANCE = MAX_NODES * 10000; MAX_DIFFERENCE = args.get<double>("bp_max_diff"); vector<Overlap*> overlaps, filtered; vector<Read*> reads; vector<Read*> reads_mapped; must_mkdir(output_dir); std::cerr << "Output dir: " << output_dir << std::endl; if (reads_format == "fasta") { readFastaReads(reads, reads_filename.c_str()); } else if (reads_format == "fastq") { readFastqReads(reads, reads_filename.c_str()); } else if (reads_format == "afg") { readAfgReads(reads, reads_filename.c_str()); } else { assert(false); } // map reads so we have reads_mapped[read_id] -> read map_reads(&reads_mapped, reads); std::cerr << "Read " << reads.size() << " reads" << std::endl; if (overlaps_format == "afg") { readAfgOverlaps(overlaps, overlaps_filename.c_str()); } else if (overlaps_format == "mhap") { fstream overlaps_file(overlaps_filename); MHAP::read_overlaps(overlaps_file, &overlaps); overlaps_file.close(); } else { assert(false); } // fix overlap read ids for (auto o: overlaps) { o->setA(o->getA() - reads_id_offset); o->setB(o->getB() - reads_id_offset); } for (auto o: overlaps) { const auto a = o->getA(); const auto b = o->getB(); if (reads_mapped[a] == nullptr) { cerr << "Read " << a << " not found" << endl; exit(1); } if (reads_mapped[b] == nullptr) { cerr << "Read " << b << " not found" << endl; exit(1); } o->setReadA(reads_mapped[a]); o->setReadB(reads_mapped[b]); } cerr << overlaps.size() << " overlaps read" << endl; int skipped = 0; for (uint32_t i = 0; i < overlaps.size(); ++i) { const auto o = overlaps[i]; if (o->getReadA()->getLength() < 3000 || o->getReadB()->getLength() < 3000) { skipped++; continue; } overlaps[i - skipped] = overlaps[i]; } overlaps.resize(overlaps.size() - skipped); vector<Overlap*> nocontainments; filterContainedOverlaps(nocontainments, overlaps, reads_mapped, true); if (verbose_output) { writeOverlaps(nocontainments, (output_dir + "/nocont.afg").c_str()); } vector<Overlap*> notransitives; filterTransitiveOverlaps(notransitives, nocontainments, thread_num, true); if (verbose_output) { writeOverlaps(notransitives, (output_dir + "/nocont.notran.afg").c_str()); } createReverseComplements(reads, thread_num); StringGraph* graph = new StringGraph(reads, notransitives); graph->simplify(); if (verbose_output) { vector<Overlap*> simplified_overlaps; graph->extractOverlaps(simplified_overlaps); writeOverlaps(simplified_overlaps, (output_dir + "/simplified.afg").c_str()); } std::vector<StringGraphComponent*> components; graph->extractComponents(components); std::vector<Contig*> contigs; auto contigs_fast = fopen((output_dir + "/contigs_fast.fasta").c_str(), "w"); int idx = 0; for (const auto& component : components) { string seq; component->extractSequence(seq); fprintf(contigs_fast, ">seq%d\n", idx); fprintf(contigs_fast, "%s\n", seq.c_str()); idx++; ContigExtractor* extractor = new ContigExtractor(component); const auto& contig = extractor->extractContig(); if (contig == nullptr) { continue; } contigs.emplace_back(contig); } fclose(contigs_fast); std::cerr << "number of contigs " << contigs.size() << std::endl; print_contigs_info(contigs, reads_mapped); writeAfgContigs(contigs, (output_dir + "/contigs.afg").c_str()); for (auto r: reads) delete r; for (auto o: overlaps) delete o; for (auto c: components) delete c; for (auto c: contigs) delete c; delete graph; return 0; } <|endoftext|>
<commit_before>// @(#)root/gui:$Id$ // Author: Fons Rademakers 05/01/98 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ /************************************************************************** This source is based on Xclass95, a Win95-looking GUI toolkit. Copyright (C) 1996, 1997 David Barth, Ricky Ralston, Hector Peraza. Xclass95 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. **************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TGIcon // // // // This class handles GUI icons. // // // ////////////////////////////////////////////////////////////////////////// #include "TGIcon.h" #include "TGPicture.h" #include "TSystem.h" #include "TImage.h" #include "Riostream.h" #include "TMath.h" #include "TGFileDialog.h" #include "TGMsgBox.h" #include "TVirtualDragManager.h" ClassImp(TGIcon) //______________________________________________________________________________ TGIcon::TGIcon(const TGWindow *p, const char *image) : TGFrame(p, 1, 1) { // Create icon. fPic = 0; char *path; if (!image) image = "bld_rgb.xpm"; path = StrDup(image); fPath = gSystem->DirName(path); fImage = TImage::Open(path); fPic = fClient->GetPicturePool()->GetPicture(gSystem->BaseName(path), fImage->GetPixmap(), fImage->GetMask()); TGFrame::Resize(fImage->GetWidth(), fImage->GetHeight()); SetWindowName(); delete [] path; } //______________________________________________________________________________ TGIcon::~TGIcon() { // Delete icon and free picture. if (fPic) fClient->FreePicture(fPic); } //______________________________________________________________________________ void TGIcon::SetPicture(const TGPicture *pic) { // Set icon picture. fPic = pic; gVirtualX->ClearWindow(fId); fClient->NeedRedraw(this); } //______________________________________________________________________________ void TGIcon::SetImage(const char *img) { // Set icon image. //delete fImage; TImage *i = TImage::Open(img); fPath = gSystem->DirName(img); SetImage(i); } //______________________________________________________________________________ void TGIcon::SetImage(TImage *img) { // Change icon image. if (!img) { return; } delete fImage; // !! mem.leak!! fImage = img; Resize(fImage->GetWidth(), fImage->GetHeight()); fClient->NeedRedraw(this); } //______________________________________________________________________________ TGDimension TGIcon::GetDefaultSize() const { // Return size of icon. return TGDimension((fPic) ? fPic->GetWidth() : fWidth, (fPic) ? fPic->GetHeight() : fHeight); } //______________________________________________________________________________ void TGIcon::DoRedraw() { // Redraw picture. Bool_t border = (GetOptions() & kRaisedFrame) || (GetOptions() & kSunkenFrame) || (GetOptions() & kDoubleBorder); if (fPic) fPic->Draw(fId, GetBckgndGC()(), border, border); if (border) DrawBorder(); } //______________________________________________________________________________ void TGIcon::Resize(UInt_t w, UInt_t h) { // Resize. TGFrame::Resize(w, h); // allow scaled resize for icons with TImage if (!fImage) { return; } gVirtualX->ClearWindow(fId); if (fPic) { fClient->FreePicture(fPic); } Bool_t border = (GetOptions() & kRaisedFrame) || (GetOptions() & kSunkenFrame) || (GetOptions() & kDoubleBorder); fImage->Scale(w - 2*border, h - 2*border); fPic = fClient->GetPicturePool()->GetPicture(fImage->GetName(), fImage->GetPixmap(), fImage->GetMask()); DoRedraw(); } //______________________________________________________________________________ void TGIcon::MoveResize(Int_t x, Int_t y, UInt_t w, UInt_t h) { // Move icon to (x,y) and resize it to (w,h). Move(x, y); Resize(w, h); } //______________________________________________________________________________ void TGIcon::Reset() { // Reset icon to original image. It can be used only via context menu. if (!fImage || !fClient->IsEditable()) return; TString name = fImage->GetName(); name.Chop(); char *path = gSystem->ConcatFileName(fPath.Data(), name.Data()); SetImage(path); delete [] path; } //______________________________________________________________________________ void TGIcon::SetImagePath(const char *path) { // Set directory where image is located if (!path) { return; } fPath = gSystem->ExpandPathName(gSystem->UnixPathName(path)); } //______________________________________________________________________________ void TGIcon::SavePrimitive(ostream &out, Option_t *option /*= ""*/) { // Save an icon widget as a C++ statement(s) on output stream out. char quote = '"'; if (fBackground != GetDefaultFrameBackground()) SaveUserColor(out, option); if (!fPic) { Error("SavePrimitive()", "icon pixmap not found "); return; } const char *picname = fPic->GetName(); out <<" TGIcon *"; if (!fImage) { out << GetName() << " = new TGIcon(" << fParent->GetName() << ",gClient->GetPicture(" << quote << gSystem->ExpandPathName(gSystem->UnixPathName(picname)) // if no path << quote << ")" << "," << GetWidth() << "," << GetHeight(); if (fBackground == GetDefaultFrameBackground()) { if (!GetOptions()) { out <<");" << endl; } else { out << "," << GetOptionString() <<");" << endl; } } else { out << "," << GetOptionString() << ",ucolor);" << endl; } } else { TString name = fPath; name += "/"; name += fImage->GetName(); name.Chop(); out << GetName() << " = new TGIcon(" << fParent->GetName() << "," << quote << name.Data() << quote << ");" << endl; } if (option && strstr(option, "keep_names")) out << " " << GetName() << "->SetName(\"" << GetName() << "\");" << endl; } <commit_msg>Fix coverity reports (dereference null return value )<commit_after>// @(#)root/gui:$Id$ // Author: Fons Rademakers 05/01/98 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ /************************************************************************** This source is based on Xclass95, a Win95-looking GUI toolkit. Copyright (C) 1996, 1997 David Barth, Ricky Ralston, Hector Peraza. Xclass95 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. **************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TGIcon // // // // This class handles GUI icons. // // // ////////////////////////////////////////////////////////////////////////// #include "TGIcon.h" #include "TGPicture.h" #include "TSystem.h" #include "TImage.h" #include "Riostream.h" #include "TMath.h" #include "TGFileDialog.h" #include "TGMsgBox.h" #include "TVirtualDragManager.h" ClassImp(TGIcon) //______________________________________________________________________________ TGIcon::TGIcon(const TGWindow *p, const char *image) : TGFrame(p, 1, 1) { // Create icon. fPic = 0; char *path; if (!image) image = "bld_rgb.xpm"; path = StrDup(image); fPath = gSystem->DirName(path); fImage = TImage::Open(path); if (fImage) { fPic = fClient->GetPicturePool()->GetPicture(gSystem->BaseName(path), fImage->GetPixmap(), fImage->GetMask()); TGFrame::Resize(fImage->GetWidth(), fImage->GetHeight()); } SetWindowName(); delete [] path; } //______________________________________________________________________________ TGIcon::~TGIcon() { // Delete icon and free picture. if (fPic) fClient->FreePicture(fPic); } //______________________________________________________________________________ void TGIcon::SetPicture(const TGPicture *pic) { // Set icon picture. fPic = pic; gVirtualX->ClearWindow(fId); fClient->NeedRedraw(this); } //______________________________________________________________________________ void TGIcon::SetImage(const char *img) { // Set icon image. //delete fImage; TImage *i = TImage::Open(img); fPath = gSystem->DirName(img); SetImage(i); } //______________________________________________________________________________ void TGIcon::SetImage(TImage *img) { // Change icon image. if (!img) { return; } delete fImage; // !! mem.leak!! fImage = img; Resize(fImage->GetWidth(), fImage->GetHeight()); fClient->NeedRedraw(this); } //______________________________________________________________________________ TGDimension TGIcon::GetDefaultSize() const { // Return size of icon. return TGDimension((fPic) ? fPic->GetWidth() : fWidth, (fPic) ? fPic->GetHeight() : fHeight); } //______________________________________________________________________________ void TGIcon::DoRedraw() { // Redraw picture. Bool_t border = (GetOptions() & kRaisedFrame) || (GetOptions() & kSunkenFrame) || (GetOptions() & kDoubleBorder); if (fPic) fPic->Draw(fId, GetBckgndGC()(), border, border); if (border) DrawBorder(); } //______________________________________________________________________________ void TGIcon::Resize(UInt_t w, UInt_t h) { // Resize. TGFrame::Resize(w, h); // allow scaled resize for icons with TImage if (!fImage) { return; } gVirtualX->ClearWindow(fId); if (fPic) { fClient->FreePicture(fPic); } Bool_t border = (GetOptions() & kRaisedFrame) || (GetOptions() & kSunkenFrame) || (GetOptions() & kDoubleBorder); fImage->Scale(w - 2*border, h - 2*border); fPic = fClient->GetPicturePool()->GetPicture(fImage->GetName(), fImage->GetPixmap(), fImage->GetMask()); DoRedraw(); } //______________________________________________________________________________ void TGIcon::MoveResize(Int_t x, Int_t y, UInt_t w, UInt_t h) { // Move icon to (x,y) and resize it to (w,h). Move(x, y); Resize(w, h); } //______________________________________________________________________________ void TGIcon::Reset() { // Reset icon to original image. It can be used only via context menu. if (!fImage || !fClient->IsEditable()) return; TString name = fImage->GetName(); name.Chop(); char *path = gSystem->ConcatFileName(fPath.Data(), name.Data()); SetImage(path); delete [] path; } //______________________________________________________________________________ void TGIcon::SetImagePath(const char *path) { // Set directory where image is located if (!path) { return; } fPath = gSystem->ExpandPathName(gSystem->UnixPathName(path)); } //______________________________________________________________________________ void TGIcon::SavePrimitive(ostream &out, Option_t *option /*= ""*/) { // Save an icon widget as a C++ statement(s) on output stream out. char quote = '"'; if (fBackground != GetDefaultFrameBackground()) SaveUserColor(out, option); if (!fPic) { Error("SavePrimitive()", "icon pixmap not found "); return; } const char *picname = fPic->GetName(); out <<" TGIcon *"; if (!fImage) { out << GetName() << " = new TGIcon(" << fParent->GetName() << ",gClient->GetPicture(" << quote << gSystem->ExpandPathName(gSystem->UnixPathName(picname)) // if no path << quote << ")" << "," << GetWidth() << "," << GetHeight(); if (fBackground == GetDefaultFrameBackground()) { if (!GetOptions()) { out <<");" << endl; } else { out << "," << GetOptionString() <<");" << endl; } } else { out << "," << GetOptionString() << ",ucolor);" << endl; } } else { TString name = fPath; name += "/"; name += fImage->GetName(); name.Chop(); out << GetName() << " = new TGIcon(" << fParent->GetName() << "," << quote << name.Data() << quote << ");" << endl; } if (option && strstr(option, "keep_names")) out << " " << GetName() << "->SetName(\"" << GetName() << "\");" << endl; } <|endoftext|>
<commit_before>/* * Copyright © 2012 Intel Corporation * * 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, see <http://www.gnu.org/licenses/>. * * Author: Benjamin Segovia <benjamin.segovia@intel.com> * Heldge RHodin <alice.rhodin@alice-dsl.net> */ /** * \file llvm_passes.cpp * \author Benjamin Segovia <benjamin.segovia@intel.com> * \author Heldge RHodin <alice.rhodin@alice-dsl.net> */ /* THIS CODE IS DERIVED FROM GPL LLVM PTX BACKEND. CODE IS HERE: * http://sourceforge.net/scm/?type=git&group_id=319085 * Note that however, the original author, Heldge Rhodin, granted me (Benjamin * Segovia) the right to use another license for it (MIT here) */ #include "llvm/Config/llvm-config.h" #if LLVM_VERSION_MINOR <= 2 #include "llvm/CallingConv.h" #include "llvm/Constants.h" #include "llvm/DerivedTypes.h" #include "llvm/Module.h" #include "llvm/Instructions.h" #else #include "llvm/IR/CallingConv.h" #include "llvm/IR/Constants.h" #include "llvm/IR/DerivedTypes.h" #include "llvm/IR/Module.h" #include "llvm/IR/Instructions.h" #endif /* LLVM_VERSION_MINOR <= 2 */ #include "llvm/Pass.h" #include "llvm/PassManager.h" #if LLVM_VERSION_MINOR <= 2 #include "llvm/Intrinsics.h" #include "llvm/IntrinsicInst.h" #include "llvm/InlineAsm.h" #else #include "llvm/IR/Intrinsics.h" #include "llvm/IR/IntrinsicInst.h" #include "llvm/IR/InlineAsm.h" #endif /* LLVM_VERSION_MINOR <= 2 */ #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/STLExtras.h" #include "llvm/Analysis/ConstantsScanner.h" #include "llvm/Analysis/FindUsedTypes.h" #include "llvm/Analysis/LoopInfo.h" #include "llvm/Analysis/ValueTracking.h" #include "llvm/CodeGen/Passes.h" #include "llvm/CodeGen/IntrinsicLowering.h" #if LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR >=5 #include "llvm/IR/Mangler.h" #else #include "llvm/Target/Mangler.h" #endif #include "llvm/Transforms/Scalar.h" #include "llvm/MC/MCAsmInfo.h" #include "llvm/MC/MCContext.h" #include "llvm/MC/MCInstrInfo.h" #include "llvm/MC/MCObjectFileInfo.h" #include "llvm/MC/MCRegisterInfo.h" #include "llvm/MC/MCSubtargetInfo.h" #include "llvm/MC/MCSymbol.h" #if !defined(LLVM_VERSION_MAJOR) || (LLVM_VERSION_MINOR == 1) #include "llvm/Target/TargetData.h" #elif LLVM_VERSION_MINOR == 2 #include "llvm/DataLayout.h" #else #include "llvm/IR/DataLayout.h" #endif #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/FormattedStream.h" #if (LLVM_VERSION_MAJOR == 3) && (LLVM_VERSION_MINOR <= 2) #include "llvm/Support/InstVisitor.h" #elif LLVM_VERSION_MINOR >= 5 #include "llvm/IR/InstVisitor.h" #else #include "llvm/InstVisitor.h" #endif #include "llvm/Support/MathExtras.h" #include "llvm/Support/TargetRegistry.h" #include "llvm/Support/Host.h" #include "llvm/Support/ToolOutputFile.h" #include "llvm/Support/SourceMgr.h" #include "llvm/llvm_gen_backend.hpp" #include "ir/unit.hpp" #include "sys/map.hpp" using namespace llvm; namespace gbe { bool isKernelFunction(const llvm::Function &F) { const Module *module = F.getParent(); const Module::NamedMDListType& globalMD = module->getNamedMDList(); bool bKernel = false; for(auto i = globalMD.begin(); i != globalMD.end(); i++) { const NamedMDNode &md = *i; if(strcmp(md.getName().data(), "opencl.kernels") != 0) continue; uint32_t ops = md.getNumOperands(); for(uint32_t x = 0; x < ops; x++) { MDNode* node = md.getOperand(x); Value * op = node->getOperand(0); if(op == &F) bKernel = true; } } return bKernel; } int32_t getPadding(int32_t offset, int32_t align) { return (align - (offset % align)) % align; } uint32_t getAlignmentByte(const ir::Unit &unit, Type* Ty) { switch (Ty->getTypeID()) { case Type::VoidTyID: NOT_SUPPORTED; case Type::VectorTyID: { const VectorType* VecTy = cast<VectorType>(Ty); uint32_t elemNum = VecTy->getNumElements(); if (elemNum == 3) elemNum = 4; // OCL spec return elemNum * getTypeByteSize(unit, VecTy->getElementType()); } case Type::PointerTyID: case Type::IntegerTyID: case Type::FloatTyID: case Type::DoubleTyID: case Type::HalfTyID: return getTypeBitSize(unit, Ty)/8; case Type::ArrayTyID: return getAlignmentByte(unit, cast<ArrayType>(Ty)->getElementType()); case Type::StructTyID: { const StructType* StrTy = cast<StructType>(Ty); uint32_t maxa = 0; for(uint32_t subtype = 0; subtype < StrTy->getNumElements(); subtype++) { maxa = std::max(getAlignmentByte(unit, StrTy->getElementType(subtype)), maxa); } return maxa; } default: NOT_SUPPORTED; } return 0u; } uint32_t getTypeBitSize(const ir::Unit &unit, Type* Ty) { switch (Ty->getTypeID()) { case Type::VoidTyID: NOT_SUPPORTED; case Type::PointerTyID: return unit.getPointerSize(); case Type::IntegerTyID: { // use S16 to represent SLM bool variables. int bitWidth = cast<IntegerType>(Ty)->getBitWidth(); return (bitWidth == 1) ? 16 : bitWidth; } case Type::HalfTyID: return 16; case Type::FloatTyID: return 32; case Type::DoubleTyID: return 64; case Type::VectorTyID: { const VectorType* VecTy = cast<VectorType>(Ty); uint32_t numElem = VecTy->getNumElements(); if(numElem == 3) numElem = 4; // OCL spec return numElem * getTypeBitSize(unit, VecTy->getElementType()); } case Type::ArrayTyID: { const ArrayType* ArrTy = cast<ArrayType>(Ty); Type* elementType = ArrTy->getElementType(); uint32_t size_element = getTypeBitSize(unit, elementType); uint32_t size = ArrTy->getNumElements() * size_element; uint32_t align = 8 * getAlignmentByte(unit, elementType); size += (ArrTy->getNumElements()-1) * getPadding(size_element, align); return size; } case Type::StructTyID: { const StructType* StrTy = cast<StructType>(Ty); uint32_t size = 0; for(uint32_t subtype=0; subtype < StrTy->getNumElements(); subtype++) { Type* elementType = StrTy->getElementType(subtype); uint32_t align = 8 * getAlignmentByte(unit, elementType); size += getPadding(size, align); size += getTypeBitSize(unit, elementType); } return size; } default: NOT_SUPPORTED; } return 0u; } uint32_t getTypeByteSize(const ir::Unit &unit, Type* Ty) { uint32_t size_bit = getTypeBitSize(unit, Ty); assert((size_bit%8==0) && "no multiple of 8"); return size_bit/8; } class GenRemoveGEPPasss : public BasicBlockPass { public: static char ID; #define FORMER_VERSION 0 #if FORMER_VERSION GenRemoveGEPPasss(map<const Value *, const Value *>& parentCompositePointer) : BasicBlockPass(ID), parentPointers(parentCompositePointer) {} map<const Value *, const Value *>& parentPointers; #else GenRemoveGEPPasss(const ir::Unit &unit) : BasicBlockPass(ID), unit(unit) {} const ir::Unit &unit; #endif void getAnalysisUsage(AnalysisUsage &AU) const { AU.setPreservesCFG(); } virtual const char *getPassName() const { return "SPIR backend: insert special spir instructions"; } bool simplifyGEPInstructions(GetElementPtrInst* GEPInst); virtual bool runOnBasicBlock(BasicBlock &BB) { bool changedBlock = false; iplist<Instruction>::iterator I = BB.getInstList().begin(); for (auto nextI = I, E = --BB.getInstList().end(); I != E; I = nextI) { iplist<Instruction>::iterator I = nextI++; if(GetElementPtrInst* gep = dyn_cast<GetElementPtrInst>(&*I)) changedBlock = (simplifyGEPInstructions(gep) || changedBlock); } return changedBlock; } }; char GenRemoveGEPPasss::ID = 0; bool GenRemoveGEPPasss::simplifyGEPInstructions(GetElementPtrInst* GEPInst) { const uint32_t ptrSize = unit.getPointerSize(); Value* parentPointer = GEPInst->getOperand(0); #if FORMER_VERSION Value* topParent = parentPointer; #endif CompositeType* CompTy = cast<CompositeType>(parentPointer->getType()); Value* currentAddrInst = new PtrToIntInst(parentPointer, IntegerType::get(GEPInst->getContext(), ptrSize), "", GEPInst); uint32_t constantOffset = 0; for(uint32_t op=1; op<GEPInst->getNumOperands(); ++op) { int32_t TypeIndex; //we have a constant struct/array acces if(ConstantInt* ConstOP = dyn_cast<ConstantInt>(GEPInst->getOperand(op))) { int32_t offset = 0; TypeIndex = ConstOP->getZExtValue(); int32_t step = TypeIndex > 0 ? 1 : -1; if (op == 1) { if (TypeIndex != 0) { Type *elementType = (cast<PointerType>(parentPointer->getType()))->getElementType(); uint32_t elementSize = getTypeByteSize(unit, elementType); uint32_t align = getAlignmentByte(unit, elementType); elementSize += getPadding(elementSize, align); offset += elementSize * TypeIndex; } } else { for(int32_t ty_i=0; ty_i != TypeIndex; ty_i += step) { Type* elementType = CompTy->getTypeAtIndex(ty_i); uint32_t align = getAlignmentByte(unit, elementType); offset += getPadding(offset, align * step); offset += getTypeByteSize(unit, elementType) * step; } //add getPaddingding for accessed type const uint32_t align = getAlignmentByte(unit, CompTy->getTypeAtIndex(TypeIndex)); offset += getPadding(offset, align * step); } constantOffset += offset; } // none constant index (=> only array/verctor allowed) else { // we only have array/vectors here, // therefore all elements have the same size TypeIndex = 0; Type* elementType = CompTy->getTypeAtIndex(TypeIndex); uint32_t size = getTypeByteSize(unit, elementType); //add padding uint32_t align = getAlignmentByte(unit, elementType); size += getPadding(size, align); Constant* newConstSize = ConstantInt::get(IntegerType::get(GEPInst->getContext(), ptrSize), size); Value *operand = GEPInst->getOperand(op); //HACK TODO: Inserted by type replacement.. this code could break something???? if(getTypeByteSize(unit, operand->getType())>4) { GBE_ASSERTM(false, "CHECK IT"); operand->dump(); //previous instruction is sext or zext instr. ignore it CastInst *cast = dyn_cast<CastInst>(operand); if(cast && (isa<ZExtInst>(operand) || isa<SExtInst>(operand))) { //hope that CastInst is a s/zext operand = cast->getOperand(0); } else { //trunctate operand = new TruncInst(operand, IntegerType::get(GEPInst->getContext(), ptrSize), "", GEPInst); } } BinaryOperator* tmpMul = BinaryOperator::Create(Instruction::Mul, newConstSize, operand, "", GEPInst); currentAddrInst = BinaryOperator::Create(Instruction::Add, currentAddrInst, tmpMul, "", GEPInst); } //step down in type hirachy CompTy = dyn_cast<CompositeType>(CompTy->getTypeAtIndex(TypeIndex)); } //insert addition of new offset before GEPInst Constant* newConstOffset = ConstantInt::get(IntegerType::get(GEPInst->getContext(), ptrSize), constantOffset); currentAddrInst = BinaryOperator::Create(Instruction::Add, currentAddrInst, newConstOffset, "", GEPInst); //convert offset to ptr type (nop) IntToPtrInst* intToPtrInst = new IntToPtrInst(currentAddrInst,GEPInst->getType(),"", GEPInst); //replace uses of the GEP instruction with the newly calculated pointer GEPInst->replaceAllUsesWith(intToPtrInst); GEPInst->dropAllReferences(); GEPInst->eraseFromParent(); #if FORMER_VERSION //insert new pointer into parent list while(parentPointers.find(topParent)!=parentPointers.end()) topParent = parentPointers.find(topParent)->second; parentPointers[intToPtrInst] = topParent; #endif return true; } BasicBlockPass *createRemoveGEPPass(const ir::Unit &unit) { return new GenRemoveGEPPasss(unit); } } /* namespace gbe */ <commit_msg>GBE: optimize GEP constant offset calculation.<commit_after>/* * Copyright © 2012 Intel Corporation * * 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, see <http://www.gnu.org/licenses/>. * * Author: Benjamin Segovia <benjamin.segovia@intel.com> * Heldge RHodin <alice.rhodin@alice-dsl.net> */ /** * \file llvm_passes.cpp * \author Benjamin Segovia <benjamin.segovia@intel.com> * \author Heldge RHodin <alice.rhodin@alice-dsl.net> */ /* THIS CODE IS DERIVED FROM GPL LLVM PTX BACKEND. CODE IS HERE: * http://sourceforge.net/scm/?type=git&group_id=319085 * Note that however, the original author, Heldge Rhodin, granted me (Benjamin * Segovia) the right to use another license for it (MIT here) */ #include "llvm/Config/llvm-config.h" #if LLVM_VERSION_MINOR <= 2 #include "llvm/CallingConv.h" #include "llvm/Constants.h" #include "llvm/DerivedTypes.h" #include "llvm/Module.h" #include "llvm/Instructions.h" #else #include "llvm/IR/CallingConv.h" #include "llvm/IR/Constants.h" #include "llvm/IR/DerivedTypes.h" #include "llvm/IR/Module.h" #include "llvm/IR/Instructions.h" #endif /* LLVM_VERSION_MINOR <= 2 */ #include "llvm/Pass.h" #include "llvm/PassManager.h" #if LLVM_VERSION_MINOR <= 2 #include "llvm/Intrinsics.h" #include "llvm/IntrinsicInst.h" #include "llvm/InlineAsm.h" #else #include "llvm/IR/Intrinsics.h" #include "llvm/IR/IntrinsicInst.h" #include "llvm/IR/InlineAsm.h" #endif /* LLVM_VERSION_MINOR <= 2 */ #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/STLExtras.h" #include "llvm/Analysis/ConstantsScanner.h" #include "llvm/Analysis/FindUsedTypes.h" #include "llvm/Analysis/LoopInfo.h" #include "llvm/Analysis/ValueTracking.h" #include "llvm/CodeGen/Passes.h" #include "llvm/CodeGen/IntrinsicLowering.h" #if LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR >=5 #include "llvm/IR/Mangler.h" #else #include "llvm/Target/Mangler.h" #endif #include "llvm/Transforms/Scalar.h" #include "llvm/MC/MCAsmInfo.h" #include "llvm/MC/MCContext.h" #include "llvm/MC/MCInstrInfo.h" #include "llvm/MC/MCObjectFileInfo.h" #include "llvm/MC/MCRegisterInfo.h" #include "llvm/MC/MCSubtargetInfo.h" #include "llvm/MC/MCSymbol.h" #if !defined(LLVM_VERSION_MAJOR) || (LLVM_VERSION_MINOR == 1) #include "llvm/Target/TargetData.h" #elif LLVM_VERSION_MINOR == 2 #include "llvm/DataLayout.h" #else #include "llvm/IR/DataLayout.h" #endif #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/FormattedStream.h" #if (LLVM_VERSION_MAJOR == 3) && (LLVM_VERSION_MINOR <= 2) #include "llvm/Support/InstVisitor.h" #elif LLVM_VERSION_MINOR >= 5 #include "llvm/IR/InstVisitor.h" #else #include "llvm/InstVisitor.h" #endif #include "llvm/Support/MathExtras.h" #include "llvm/Support/TargetRegistry.h" #include "llvm/Support/Host.h" #include "llvm/Support/ToolOutputFile.h" #include "llvm/Support/SourceMgr.h" #include "llvm/llvm_gen_backend.hpp" #include "ir/unit.hpp" #include "sys/map.hpp" using namespace llvm; namespace gbe { bool isKernelFunction(const llvm::Function &F) { const Module *module = F.getParent(); const Module::NamedMDListType& globalMD = module->getNamedMDList(); bool bKernel = false; for(auto i = globalMD.begin(); i != globalMD.end(); i++) { const NamedMDNode &md = *i; if(strcmp(md.getName().data(), "opencl.kernels") != 0) continue; uint32_t ops = md.getNumOperands(); for(uint32_t x = 0; x < ops; x++) { MDNode* node = md.getOperand(x); Value * op = node->getOperand(0); if(op == &F) bKernel = true; } } return bKernel; } int32_t getPadding(int32_t offset, int32_t align) { return (align - (offset % align)) % align; } uint32_t getAlignmentByte(const ir::Unit &unit, Type* Ty) { switch (Ty->getTypeID()) { case Type::VoidTyID: NOT_SUPPORTED; case Type::VectorTyID: { const VectorType* VecTy = cast<VectorType>(Ty); uint32_t elemNum = VecTy->getNumElements(); if (elemNum == 3) elemNum = 4; // OCL spec return elemNum * getTypeByteSize(unit, VecTy->getElementType()); } case Type::PointerTyID: case Type::IntegerTyID: case Type::FloatTyID: case Type::DoubleTyID: case Type::HalfTyID: return getTypeBitSize(unit, Ty)/8; case Type::ArrayTyID: return getAlignmentByte(unit, cast<ArrayType>(Ty)->getElementType()); case Type::StructTyID: { const StructType* StrTy = cast<StructType>(Ty); uint32_t maxa = 0; for(uint32_t subtype = 0; subtype < StrTy->getNumElements(); subtype++) { maxa = std::max(getAlignmentByte(unit, StrTy->getElementType(subtype)), maxa); } return maxa; } default: NOT_SUPPORTED; } return 0u; } uint32_t getTypeBitSize(const ir::Unit &unit, Type* Ty) { switch (Ty->getTypeID()) { case Type::VoidTyID: NOT_SUPPORTED; case Type::PointerTyID: return unit.getPointerSize(); case Type::IntegerTyID: { // use S16 to represent SLM bool variables. int bitWidth = cast<IntegerType>(Ty)->getBitWidth(); return (bitWidth == 1) ? 16 : bitWidth; } case Type::HalfTyID: return 16; case Type::FloatTyID: return 32; case Type::DoubleTyID: return 64; case Type::VectorTyID: { const VectorType* VecTy = cast<VectorType>(Ty); uint32_t numElem = VecTy->getNumElements(); if(numElem == 3) numElem = 4; // OCL spec return numElem * getTypeBitSize(unit, VecTy->getElementType()); } case Type::ArrayTyID: { const ArrayType* ArrTy = cast<ArrayType>(Ty); Type* elementType = ArrTy->getElementType(); uint32_t size_element = getTypeBitSize(unit, elementType); uint32_t size = ArrTy->getNumElements() * size_element; uint32_t align = 8 * getAlignmentByte(unit, elementType); size += (ArrTy->getNumElements()-1) * getPadding(size_element, align); return size; } case Type::StructTyID: { const StructType* StrTy = cast<StructType>(Ty); uint32_t size = 0; for(uint32_t subtype=0; subtype < StrTy->getNumElements(); subtype++) { Type* elementType = StrTy->getElementType(subtype); uint32_t align = 8 * getAlignmentByte(unit, elementType); size += getPadding(size, align); size += getTypeBitSize(unit, elementType); } return size; } default: NOT_SUPPORTED; } return 0u; } uint32_t getTypeByteSize(const ir::Unit &unit, Type* Ty) { uint32_t size_bit = getTypeBitSize(unit, Ty); assert((size_bit%8==0) && "no multiple of 8"); return size_bit/8; } class GenRemoveGEPPasss : public BasicBlockPass { public: static char ID; #define FORMER_VERSION 0 #if FORMER_VERSION GenRemoveGEPPasss(map<const Value *, const Value *>& parentCompositePointer) : BasicBlockPass(ID), parentPointers(parentCompositePointer) {} map<const Value *, const Value *>& parentPointers; #else GenRemoveGEPPasss(const ir::Unit &unit) : BasicBlockPass(ID), unit(unit) {} const ir::Unit &unit; #endif void getAnalysisUsage(AnalysisUsage &AU) const { AU.setPreservesCFG(); } virtual const char *getPassName() const { return "SPIR backend: insert special spir instructions"; } bool simplifyGEPInstructions(GetElementPtrInst* GEPInst); virtual bool runOnBasicBlock(BasicBlock &BB) { bool changedBlock = false; iplist<Instruction>::iterator I = BB.getInstList().begin(); for (auto nextI = I, E = --BB.getInstList().end(); I != E; I = nextI) { iplist<Instruction>::iterator I = nextI++; if(GetElementPtrInst* gep = dyn_cast<GetElementPtrInst>(&*I)) changedBlock = (simplifyGEPInstructions(gep) || changedBlock); } return changedBlock; } }; char GenRemoveGEPPasss::ID = 0; bool GenRemoveGEPPasss::simplifyGEPInstructions(GetElementPtrInst* GEPInst) { const uint32_t ptrSize = unit.getPointerSize(); Value* parentPointer = GEPInst->getOperand(0); #if FORMER_VERSION Value* topParent = parentPointer; #endif CompositeType* CompTy = cast<CompositeType>(parentPointer->getType()); Value* currentAddrInst = new PtrToIntInst(parentPointer, IntegerType::get(GEPInst->getContext(), ptrSize), "", GEPInst); int32_t constantOffset = 0; for(uint32_t op=1; op<GEPInst->getNumOperands(); ++op) { int32_t TypeIndex; //we have a constant struct/array acces if(ConstantInt* ConstOP = dyn_cast<ConstantInt>(GEPInst->getOperand(op))) { int32_t offset = 0; TypeIndex = ConstOP->getZExtValue(); int32_t step = TypeIndex > 0 ? 1 : -1; SequentialType * seqType = dyn_cast<SequentialType>(CompTy); if (seqType != NULL) { if (TypeIndex != 0) { Type *elementType = seqType->getElementType(); uint32_t elementSize = getTypeByteSize(unit, elementType); uint32_t align = getAlignmentByte(unit, elementType); elementSize += getPadding(elementSize, align); offset += elementSize * TypeIndex; } } else { GBE_ASSERT(CompTy->isStructTy()); for(int32_t ty_i=0; ty_i != TypeIndex; ty_i += step) { Type* elementType = CompTy->getTypeAtIndex(ty_i); uint32_t align = getAlignmentByte(unit, elementType); offset += getPadding(offset, align * step); offset += getTypeByteSize(unit, elementType) * step; } //add getPaddingding for accessed type const uint32_t align = getAlignmentByte(unit, CompTy->getTypeAtIndex(TypeIndex)); offset += getPadding(offset, align * step); } constantOffset += offset; } // none constant index (=> only array/verctor allowed) else { // we only have array/vectors here, // therefore all elements have the same size TypeIndex = 0; Type* elementType = CompTy->getTypeAtIndex(TypeIndex); uint32_t size = getTypeByteSize(unit, elementType); //add padding uint32_t align = getAlignmentByte(unit, elementType); size += getPadding(size, align); Constant* newConstSize = ConstantInt::get(IntegerType::get(GEPInst->getContext(), ptrSize), size); Value *operand = GEPInst->getOperand(op); //HACK TODO: Inserted by type replacement.. this code could break something???? if(getTypeByteSize(unit, operand->getType())>4) { GBE_ASSERTM(false, "CHECK IT"); operand->dump(); //previous instruction is sext or zext instr. ignore it CastInst *cast = dyn_cast<CastInst>(operand); if(cast && (isa<ZExtInst>(operand) || isa<SExtInst>(operand))) { //hope that CastInst is a s/zext operand = cast->getOperand(0); } else { //trunctate operand = new TruncInst(operand, IntegerType::get(GEPInst->getContext(), ptrSize), "", GEPInst); } } BinaryOperator* tmpMul = BinaryOperator::Create(Instruction::Mul, newConstSize, operand, "", GEPInst); currentAddrInst = BinaryOperator::Create(Instruction::Add, currentAddrInst, tmpMul, "", GEPInst); } //step down in type hirachy CompTy = dyn_cast<CompositeType>(CompTy->getTypeAtIndex(TypeIndex)); } //insert addition of new offset before GEPInst Constant* newConstOffset = ConstantInt::get(IntegerType::get(GEPInst->getContext(), ptrSize), constantOffset); currentAddrInst = BinaryOperator::Create(Instruction::Add, currentAddrInst, newConstOffset, "", GEPInst); //convert offset to ptr type (nop) IntToPtrInst* intToPtrInst = new IntToPtrInst(currentAddrInst,GEPInst->getType(),"", GEPInst); //replace uses of the GEP instruction with the newly calculated pointer GEPInst->replaceAllUsesWith(intToPtrInst); GEPInst->dropAllReferences(); GEPInst->eraseFromParent(); #if FORMER_VERSION //insert new pointer into parent list while(parentPointers.find(topParent)!=parentPointers.end()) topParent = parentPointers.find(topParent)->second; parentPointers[intToPtrInst] = topParent; #endif return true; } BasicBlockPass *createRemoveGEPPass(const ir::Unit &unit) { return new GenRemoveGEPPasss(unit); } } /* namespace gbe */ <|endoftext|>
<commit_before>//===----- CGOpenMPRuntime.cpp - Interface to OpenMP Runtimes -------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This provides a class for OpenMP runtime code generation. // //===----------------------------------------------------------------------===// #include "CGOpenMPRuntime.h" #include "CodeGenFunction.h" #include "clang/AST/Decl.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/IR/DerivedTypes.h" #include "llvm/IR/GlobalValue.h" #include "llvm/IR/Value.h" #include "llvm/Support/raw_ostream.h" #include <cassert> using namespace clang; using namespace CodeGen; CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM) : CGM(CGM), DefaultOpenMPPSource(nullptr) { IdentTy = llvm::StructType::create( "ident_t", CGM.Int32Ty /* reserved_1 */, CGM.Int32Ty /* flags */, CGM.Int32Ty /* reserved_2 */, CGM.Int32Ty /* reserved_3 */, CGM.Int8PtrTy /* psource */, NULL); // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...) llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty), llvm::PointerType::getUnqual(CGM.Int32Ty)}; Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true); } llvm::Value * CGOpenMPRuntime::GetOrCreateDefaultOpenMPLocation(OpenMPLocationFlags Flags) { llvm::Value *Entry = OpenMPDefaultLocMap.lookup(Flags); if (!Entry) { if (!DefaultOpenMPPSource) { // Initialize default location for psource field of ident_t structure of // all ident_t objects. Format is ";file;function;line;column;;". // Taken from // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp_str.c DefaultOpenMPPSource = CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;"); DefaultOpenMPPSource = llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy); } llvm::GlobalVariable *DefaultOpenMPLocation = cast<llvm::GlobalVariable>( CGM.CreateRuntimeVariable(IdentTy, ".kmpc_default_loc.addr")); DefaultOpenMPLocation->setUnnamedAddr(true); DefaultOpenMPLocation->setConstant(true); DefaultOpenMPLocation->setLinkage(llvm::GlobalValue::PrivateLinkage); llvm::Constant *Zero = llvm::ConstantInt::get(CGM.Int32Ty, 0, true); llvm::Constant *Values[] = {Zero, llvm::ConstantInt::get(CGM.Int32Ty, Flags), Zero, Zero, DefaultOpenMPPSource}; llvm::Constant *Init = llvm::ConstantStruct::get(IdentTy, Values); DefaultOpenMPLocation->setInitializer(Init); return DefaultOpenMPLocation; } return Entry; } llvm::Value *CGOpenMPRuntime::EmitOpenMPUpdateLocation( CodeGenFunction &CGF, SourceLocation Loc, OpenMPLocationFlags Flags) { // If no debug info is generated - return global default location. if (CGM.getCodeGenOpts().getDebugInfo() == CodeGenOptions::NoDebugInfo || Loc.isInvalid()) return GetOrCreateDefaultOpenMPLocation(Flags); assert(CGF.CurFn && "No function in current CodeGenFunction."); llvm::Value *LocValue = nullptr; OpenMPLocMapTy::iterator I = OpenMPLocMap.find(CGF.CurFn); if (I != OpenMPLocMap.end()) { LocValue = I->second; } else { // Generate "ident_t .kmpc_loc.addr;" llvm::AllocaInst *AI = CGF.CreateTempAlloca(IdentTy, ".kmpc_loc.addr"); AI->setAlignment(CGM.getDataLayout().getPrefTypeAlignment(IdentTy)); OpenMPLocMap[CGF.CurFn] = AI; LocValue = AI; CGBuilderTy::InsertPointGuard IPG(CGF.Builder); CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt); CGF.Builder.CreateMemCpy(LocValue, GetOrCreateDefaultOpenMPLocation(Flags), llvm::ConstantExpr::getSizeOf(IdentTy), CGM.PointerAlignInBytes); } // char **psource = &.kmpc_loc_<flags>.addr.psource; llvm::Value *PSource = CGF.Builder.CreateConstInBoundsGEP2_32(LocValue, 0, IdentField_PSource); auto OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding()); if (OMPDebugLoc == nullptr) { SmallString<128> Buffer2; llvm::raw_svector_ostream OS2(Buffer2); // Build debug location PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc); OS2 << ";" << PLoc.getFilename() << ";"; if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl)) { OS2 << FD->getQualifiedNameAsString(); } OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;"; OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str()); OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc; } // *psource = ";<File>;<Function>;<Line>;<Column>;;"; CGF.Builder.CreateStore(OMPDebugLoc, PSource); return LocValue; } llvm::Value *CGOpenMPRuntime::GetOpenMPGlobalThreadNum(CodeGenFunction &CGF, SourceLocation Loc) { assert(CGF.CurFn && "No function in current CodeGenFunction."); llvm::Value *GTid = nullptr; OpenMPGtidMapTy::iterator I = OpenMPGtidMap.find(CGF.CurFn); if (I != OpenMPGtidMap.end()) { GTid = I->second; } else { // Generate "int32 .kmpc_global_thread_num.addr;" CGBuilderTy::InsertPointGuard IPG(CGF.Builder); CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt); llvm::Value *Args[] = {EmitOpenMPUpdateLocation(CGF, Loc)}; GTid = CGF.EmitRuntimeCall( CreateRuntimeFunction(OMPRTL__kmpc_global_thread_num), Args); OpenMPGtidMap[CGF.CurFn] = GTid; } return GTid; } void CGOpenMPRuntime::FunctionFinished(CodeGenFunction &CGF) { assert(CGF.CurFn && "No function in current CodeGenFunction."); if (OpenMPGtidMap.count(CGF.CurFn)) OpenMPGtidMap.erase(CGF.CurFn); if (OpenMPLocMap.count(CGF.CurFn)) OpenMPLocMap.erase(CGF.CurFn); } llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() { return llvm::PointerType::getUnqual(IdentTy); } llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() { return llvm::PointerType::getUnqual(Kmpc_MicroTy); } llvm::Constant * CGOpenMPRuntime::CreateRuntimeFunction(OpenMPRTLFunction Function) { llvm::Constant *RTLFn = nullptr; switch (Function) { case OMPRTL__kmpc_fork_call: { // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro // microtask, ...); llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, getKmpc_MicroPointerTy()}; llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, TypeParams, true); RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call"); break; } case OMPRTL__kmpc_global_thread_num: { // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc); llvm::Type *TypeParams[] = {getIdentTyPointerTy()}; llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.Int32Ty, TypeParams, false); RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num"); break; } } return RTLFn; } <commit_msg>[OPENMP] Improved codegen for outlined functions for 'parallel' directives.<commit_after>//===----- CGOpenMPRuntime.cpp - Interface to OpenMP Runtimes -------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This provides a class for OpenMP runtime code generation. // //===----------------------------------------------------------------------===// #include "CGOpenMPRuntime.h" #include "CodeGenFunction.h" #include "clang/AST/Decl.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/IR/DerivedTypes.h" #include "llvm/IR/GlobalValue.h" #include "llvm/IR/Value.h" #include "llvm/Support/raw_ostream.h" #include <cassert> using namespace clang; using namespace CodeGen; CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM) : CGM(CGM), DefaultOpenMPPSource(nullptr) { IdentTy = llvm::StructType::create( "ident_t", CGM.Int32Ty /* reserved_1 */, CGM.Int32Ty /* flags */, CGM.Int32Ty /* reserved_2 */, CGM.Int32Ty /* reserved_3 */, CGM.Int8PtrTy /* psource */, NULL); // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...) llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty), llvm::PointerType::getUnqual(CGM.Int32Ty)}; Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true); } llvm::Value * CGOpenMPRuntime::GetOrCreateDefaultOpenMPLocation(OpenMPLocationFlags Flags) { llvm::Value *Entry = OpenMPDefaultLocMap.lookup(Flags); if (!Entry) { if (!DefaultOpenMPPSource) { // Initialize default location for psource field of ident_t structure of // all ident_t objects. Format is ";file;function;line;column;;". // Taken from // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp_str.c DefaultOpenMPPSource = CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;"); DefaultOpenMPPSource = llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy); } llvm::GlobalVariable *DefaultOpenMPLocation = cast<llvm::GlobalVariable>( CGM.CreateRuntimeVariable(IdentTy, ".kmpc_default_loc.addr")); DefaultOpenMPLocation->setUnnamedAddr(true); DefaultOpenMPLocation->setConstant(true); DefaultOpenMPLocation->setLinkage(llvm::GlobalValue::PrivateLinkage); llvm::Constant *Zero = llvm::ConstantInt::get(CGM.Int32Ty, 0, true); llvm::Constant *Values[] = {Zero, llvm::ConstantInt::get(CGM.Int32Ty, Flags), Zero, Zero, DefaultOpenMPPSource}; llvm::Constant *Init = llvm::ConstantStruct::get(IdentTy, Values); DefaultOpenMPLocation->setInitializer(Init); return DefaultOpenMPLocation; } return Entry; } llvm::Value *CGOpenMPRuntime::EmitOpenMPUpdateLocation( CodeGenFunction &CGF, SourceLocation Loc, OpenMPLocationFlags Flags) { // If no debug info is generated - return global default location. if (CGM.getCodeGenOpts().getDebugInfo() == CodeGenOptions::NoDebugInfo || Loc.isInvalid()) return GetOrCreateDefaultOpenMPLocation(Flags); assert(CGF.CurFn && "No function in current CodeGenFunction."); llvm::Value *LocValue = nullptr; OpenMPLocMapTy::iterator I = OpenMPLocMap.find(CGF.CurFn); if (I != OpenMPLocMap.end()) { LocValue = I->second; } else { // Generate "ident_t .kmpc_loc.addr;" llvm::AllocaInst *AI = CGF.CreateTempAlloca(IdentTy, ".kmpc_loc.addr"); AI->setAlignment(CGM.getDataLayout().getPrefTypeAlignment(IdentTy)); OpenMPLocMap[CGF.CurFn] = AI; LocValue = AI; CGBuilderTy::InsertPointGuard IPG(CGF.Builder); CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt); CGF.Builder.CreateMemCpy(LocValue, GetOrCreateDefaultOpenMPLocation(Flags), llvm::ConstantExpr::getSizeOf(IdentTy), CGM.PointerAlignInBytes); } // char **psource = &.kmpc_loc_<flags>.addr.psource; llvm::Value *PSource = CGF.Builder.CreateConstInBoundsGEP2_32(LocValue, 0, IdentField_PSource); auto OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding()); if (OMPDebugLoc == nullptr) { SmallString<128> Buffer2; llvm::raw_svector_ostream OS2(Buffer2); // Build debug location PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc); OS2 << ";" << PLoc.getFilename() << ";"; if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl)) { OS2 << FD->getQualifiedNameAsString(); } OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;"; OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str()); OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc; } // *psource = ";<File>;<Function>;<Line>;<Column>;;"; CGF.Builder.CreateStore(OMPDebugLoc, PSource); return LocValue; } llvm::Value *CGOpenMPRuntime::GetOpenMPGlobalThreadNum(CodeGenFunction &CGF, SourceLocation Loc) { assert(CGF.CurFn && "No function in current CodeGenFunction."); llvm::Value *GTid = nullptr; OpenMPGtidMapTy::iterator I = OpenMPGtidMap.find(CGF.CurFn); if (I != OpenMPGtidMap.end()) { GTid = I->second; } else { // Check if current function is a function which has first parameter // with type int32 and name ".global_tid.". if (!CGF.CurFn->arg_empty() && CGF.CurFn->arg_begin()->getType()->isPointerTy() && CGF.CurFn->arg_begin() ->getType() ->getPointerElementType() ->isIntegerTy() && CGF.CurFn->arg_begin() ->getType() ->getPointerElementType() ->getIntegerBitWidth() == 32 && CGF.CurFn->arg_begin()->hasName() && CGF.CurFn->arg_begin()->getName() == ".global_tid.") { CGBuilderTy::InsertPointGuard IPG(CGF.Builder); CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt); GTid = CGF.Builder.CreateLoad(CGF.CurFn->arg_begin()); } else { // Generate "int32 .kmpc_global_thread_num.addr;" CGBuilderTy::InsertPointGuard IPG(CGF.Builder); CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt); llvm::Value *Args[] = {EmitOpenMPUpdateLocation(CGF, Loc)}; GTid = CGF.EmitRuntimeCall( CreateRuntimeFunction(OMPRTL__kmpc_global_thread_num), Args); } OpenMPGtidMap[CGF.CurFn] = GTid; } return GTid; } void CGOpenMPRuntime::FunctionFinished(CodeGenFunction &CGF) { assert(CGF.CurFn && "No function in current CodeGenFunction."); if (OpenMPGtidMap.count(CGF.CurFn)) OpenMPGtidMap.erase(CGF.CurFn); if (OpenMPLocMap.count(CGF.CurFn)) OpenMPLocMap.erase(CGF.CurFn); } llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() { return llvm::PointerType::getUnqual(IdentTy); } llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() { return llvm::PointerType::getUnqual(Kmpc_MicroTy); } llvm::Constant * CGOpenMPRuntime::CreateRuntimeFunction(OpenMPRTLFunction Function) { llvm::Constant *RTLFn = nullptr; switch (Function) { case OMPRTL__kmpc_fork_call: { // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro // microtask, ...); llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, getKmpc_MicroPointerTy()}; llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, TypeParams, true); RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call"); break; } case OMPRTL__kmpc_global_thread_num: { // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc); llvm::Type *TypeParams[] = {getIdentTyPointerTy()}; llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.Int32Ty, TypeParams, false); RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num"); break; } } return RTLFn; } <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium OS 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 "update_engine/full_update_generator.h" #include <inttypes.h> #include <fcntl.h> #include <tr1/memory> #include <base/string_util.h> #include <base/stringprintf.h> #include "update_engine/bzip.h" #include "update_engine/utils.h" using std::deque; using std::min; using std::max; using std::string; using std::tr1::shared_ptr; using std::vector; namespace chromeos_update_engine { namespace { // This class encapsulates a full update chunk processing thread. The processor // reads a chunk of data from the input file descriptor and compresses it. The // processor needs to be started through Start() then waited on through Wait(). class ChunkProcessor { public: // Read a chunk of |size| bytes from |fd| starting at offset |offset|. ChunkProcessor(int fd, off_t offset, size_t size) : thread_(NULL), fd_(fd), offset_(offset), buffer_in_(size) {} ~ChunkProcessor() { Wait(); } off_t offset() const { return offset_; } const vector<char>& buffer_in() const { return buffer_in_; } const vector<char>& buffer_compressed() const { return buffer_compressed_; } // Starts the processor. Returns true on success, false on failure. bool Start(); // Waits for the processor to complete. Returns true on success, false on // failure. bool Wait(); bool ShouldCompress() const { return buffer_compressed_.size() < buffer_in_.size(); } private: // Reads the input data into |buffer_in_| and compresses it into // |buffer_compressed_|. Returns true on success, false otherwise. bool ReadAndCompress(); static gpointer ReadAndCompressThread(gpointer data); GThread* thread_; int fd_; off_t offset_; vector<char> buffer_in_; vector<char> buffer_compressed_; DISALLOW_COPY_AND_ASSIGN(ChunkProcessor); }; bool ChunkProcessor::Start() { thread_ = g_thread_create(ReadAndCompressThread, this, TRUE, NULL); TEST_AND_RETURN_FALSE(thread_ != NULL); return true; } bool ChunkProcessor::Wait() { if (!thread_) { return false; } gpointer result = g_thread_join(thread_); thread_ = NULL; TEST_AND_RETURN_FALSE(result == this); return true; } gpointer ChunkProcessor::ReadAndCompressThread(gpointer data) { return reinterpret_cast<ChunkProcessor*>(data)->ReadAndCompress() ? data : NULL; } bool ChunkProcessor::ReadAndCompress() { ssize_t bytes_read = -1; TEST_AND_RETURN_FALSE(utils::PReadAll(fd_, buffer_in_.data(), buffer_in_.size(), offset_, &bytes_read)); TEST_AND_RETURN_FALSE(bytes_read == static_cast<ssize_t>(buffer_in_.size())); TEST_AND_RETURN_FALSE(BzipCompress(buffer_in_, &buffer_compressed_)); return true; } } // namespace bool FullUpdateGenerator::Run( Graph* graph, const std::string& new_kernel_part, const std::string& new_image, off_t image_size, int fd, off_t* data_file_size, off_t chunk_size, off_t block_size, vector<DeltaArchiveManifest_InstallOperation>* kernel_ops, std::vector<Vertex::Index>* final_order) { TEST_AND_RETURN_FALSE(chunk_size > 0); TEST_AND_RETURN_FALSE((chunk_size % block_size) == 0); size_t max_threads = max(sysconf(_SC_NPROCESSORS_ONLN), 4L); LOG(INFO) << "Max threads: " << max_threads; // Get the sizes early in the function, so we can fail fast if the user // passed us bad paths. TEST_AND_RETURN_FALSE(image_size >= 0 && image_size <= utils::FileSize(new_image)); // Always do the root image, the kernel may not be used in all cases int partitions = 1; off_t kernel_size = 0; if (!new_kernel_part.empty()) { kernel_size = utils::FileSize(new_kernel_part); partitions++; } off_t part_sizes[] = { image_size, kernel_size }; string paths[] = { new_image, new_kernel_part }; for (int partition = 0; partition < partitions; ++partition) { const string& path = paths[partition]; LOG(INFO) << "compressing " << path; int in_fd = open(path.c_str(), O_RDONLY, 0); TEST_AND_RETURN_FALSE(in_fd >= 0); ScopedFdCloser in_fd_closer(&in_fd); deque<shared_ptr<ChunkProcessor> > threads; int last_progress_update = INT_MIN; off_t bytes_left = part_sizes[partition], counter = 0, offset = 0; while (bytes_left > 0 || !threads.empty()) { // Check and start new chunk processors if possible. while (threads.size() < max_threads && bytes_left > 0) { shared_ptr<ChunkProcessor> processor( new ChunkProcessor(in_fd, offset, min(bytes_left, chunk_size))); threads.push_back(processor); TEST_AND_RETURN_FALSE(processor->Start()); bytes_left -= chunk_size; offset += chunk_size; } // Need to wait for a chunk processor to complete and process its ouput // before spawning new processors. shared_ptr<ChunkProcessor> processor = threads.front(); threads.pop_front(); TEST_AND_RETURN_FALSE(processor->Wait()); DeltaArchiveManifest_InstallOperation* op = NULL; if (partition == 0) { graph->resize(graph->size() + 1); graph->back().file_name = StringPrintf("<rootfs-operation-%" PRIi64 ">", counter++); op = &graph->back().op; final_order->push_back(graph->size() - 1); } else { kernel_ops->resize(kernel_ops->size() + 1); op = &kernel_ops->back(); } const bool compress = processor->ShouldCompress(); const vector<char>& use_buf = compress ? processor->buffer_compressed() : processor->buffer_in(); op->set_type(compress ? DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ : DeltaArchiveManifest_InstallOperation_Type_REPLACE); op->set_data_offset(*data_file_size); TEST_AND_RETURN_FALSE(utils::WriteAll(fd, &use_buf[0], use_buf.size())); *data_file_size += use_buf.size(); op->set_data_length(use_buf.size()); Extent* dst_extent = op->add_dst_extents(); dst_extent->set_start_block(processor->offset() / block_size); dst_extent->set_num_blocks(chunk_size / block_size); int progress = static_cast<int>( (processor->offset() + processor->buffer_in().size()) * 100.0 / part_sizes[partition]); if (last_progress_update < progress && (last_progress_update + 10 <= progress || progress == 100)) { LOG(INFO) << progress << "% complete (output size: " << *data_file_size << ")"; last_progress_update = progress; } } } return true; } } // namespace chromeos_update_engine <commit_msg>Replace deprecated g_thread_create with g_thread_try_new<commit_after>// Copyright (c) 2012 The Chromium OS 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 "update_engine/full_update_generator.h" #include <inttypes.h> #include <fcntl.h> #include <tr1/memory> #include <base/string_util.h> #include <base/stringprintf.h> #include "update_engine/bzip.h" #include "update_engine/utils.h" using std::deque; using std::min; using std::max; using std::string; using std::tr1::shared_ptr; using std::vector; namespace chromeos_update_engine { namespace { // This class encapsulates a full update chunk processing thread. The processor // reads a chunk of data from the input file descriptor and compresses it. The // processor needs to be started through Start() then waited on through Wait(). class ChunkProcessor { public: // Read a chunk of |size| bytes from |fd| starting at offset |offset|. ChunkProcessor(int fd, off_t offset, size_t size) : thread_(NULL), fd_(fd), offset_(offset), buffer_in_(size) {} ~ChunkProcessor() { Wait(); } off_t offset() const { return offset_; } const vector<char>& buffer_in() const { return buffer_in_; } const vector<char>& buffer_compressed() const { return buffer_compressed_; } // Starts the processor. Returns true on success, false on failure. bool Start(); // Waits for the processor to complete. Returns true on success, false on // failure. bool Wait(); bool ShouldCompress() const { return buffer_compressed_.size() < buffer_in_.size(); } private: // Reads the input data into |buffer_in_| and compresses it into // |buffer_compressed_|. Returns true on success, false otherwise. bool ReadAndCompress(); static gpointer ReadAndCompressThread(gpointer data); GThread* thread_; int fd_; off_t offset_; vector<char> buffer_in_; vector<char> buffer_compressed_; DISALLOW_COPY_AND_ASSIGN(ChunkProcessor); }; bool ChunkProcessor::Start() { // g_thread_create is deprecated since glib 2.32. Use // g_thread_new instead. thread_ = g_thread_try_new("chunk_proc", ReadAndCompressThread, this, NULL); TEST_AND_RETURN_FALSE(thread_ != NULL); return true; } bool ChunkProcessor::Wait() { if (!thread_) { return false; } gpointer result = g_thread_join(thread_); thread_ = NULL; TEST_AND_RETURN_FALSE(result == this); return true; } gpointer ChunkProcessor::ReadAndCompressThread(gpointer data) { return reinterpret_cast<ChunkProcessor*>(data)->ReadAndCompress() ? data : NULL; } bool ChunkProcessor::ReadAndCompress() { ssize_t bytes_read = -1; TEST_AND_RETURN_FALSE(utils::PReadAll(fd_, buffer_in_.data(), buffer_in_.size(), offset_, &bytes_read)); TEST_AND_RETURN_FALSE(bytes_read == static_cast<ssize_t>(buffer_in_.size())); TEST_AND_RETURN_FALSE(BzipCompress(buffer_in_, &buffer_compressed_)); return true; } } // namespace bool FullUpdateGenerator::Run( Graph* graph, const std::string& new_kernel_part, const std::string& new_image, off_t image_size, int fd, off_t* data_file_size, off_t chunk_size, off_t block_size, vector<DeltaArchiveManifest_InstallOperation>* kernel_ops, std::vector<Vertex::Index>* final_order) { TEST_AND_RETURN_FALSE(chunk_size > 0); TEST_AND_RETURN_FALSE((chunk_size % block_size) == 0); size_t max_threads = max(sysconf(_SC_NPROCESSORS_ONLN), 4L); LOG(INFO) << "Max threads: " << max_threads; // Get the sizes early in the function, so we can fail fast if the user // passed us bad paths. TEST_AND_RETURN_FALSE(image_size >= 0 && image_size <= utils::FileSize(new_image)); // Always do the root image, the kernel may not be used in all cases int partitions = 1; off_t kernel_size = 0; if (!new_kernel_part.empty()) { kernel_size = utils::FileSize(new_kernel_part); partitions++; } off_t part_sizes[] = { image_size, kernel_size }; string paths[] = { new_image, new_kernel_part }; for (int partition = 0; partition < partitions; ++partition) { const string& path = paths[partition]; LOG(INFO) << "compressing " << path; int in_fd = open(path.c_str(), O_RDONLY, 0); TEST_AND_RETURN_FALSE(in_fd >= 0); ScopedFdCloser in_fd_closer(&in_fd); deque<shared_ptr<ChunkProcessor> > threads; int last_progress_update = INT_MIN; off_t bytes_left = part_sizes[partition], counter = 0, offset = 0; while (bytes_left > 0 || !threads.empty()) { // Check and start new chunk processors if possible. while (threads.size() < max_threads && bytes_left > 0) { shared_ptr<ChunkProcessor> processor( new ChunkProcessor(in_fd, offset, min(bytes_left, chunk_size))); threads.push_back(processor); TEST_AND_RETURN_FALSE(processor->Start()); bytes_left -= chunk_size; offset += chunk_size; } // Need to wait for a chunk processor to complete and process its ouput // before spawning new processors. shared_ptr<ChunkProcessor> processor = threads.front(); threads.pop_front(); TEST_AND_RETURN_FALSE(processor->Wait()); DeltaArchiveManifest_InstallOperation* op = NULL; if (partition == 0) { graph->resize(graph->size() + 1); graph->back().file_name = StringPrintf("<rootfs-operation-%" PRIi64 ">", counter++); op = &graph->back().op; final_order->push_back(graph->size() - 1); } else { kernel_ops->resize(kernel_ops->size() + 1); op = &kernel_ops->back(); } const bool compress = processor->ShouldCompress(); const vector<char>& use_buf = compress ? processor->buffer_compressed() : processor->buffer_in(); op->set_type(compress ? DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ : DeltaArchiveManifest_InstallOperation_Type_REPLACE); op->set_data_offset(*data_file_size); TEST_AND_RETURN_FALSE(utils::WriteAll(fd, &use_buf[0], use_buf.size())); *data_file_size += use_buf.size(); op->set_data_length(use_buf.size()); Extent* dst_extent = op->add_dst_extents(); dst_extent->set_start_block(processor->offset() / block_size); dst_extent->set_num_blocks(chunk_size / block_size); int progress = static_cast<int>( (processor->offset() + processor->buffer_in().size()) * 100.0 / part_sizes[partition]); if (last_progress_update < progress && (last_progress_update + 10 <= progress || progress == 100)) { LOG(INFO) << progress << "% complete (output size: " << *data_file_size << ")"; last_progress_update = progress; } } } return true; } } // namespace chromeos_update_engine <|endoftext|>
<commit_before>//===-- JIT.cpp - LLVM Just in Time Compiler ------------------------------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This tool implements a just-in-time compiler for LLVM, allowing direct // execution of LLVM bytecode in an efficient manner. // //===----------------------------------------------------------------------===// #include "JIT.h" #include "llvm/Constants.h" #include "llvm/DerivedTypes.h" #include "llvm/Function.h" #include "llvm/GlobalVariable.h" #include "llvm/Instructions.h" #include "llvm/ModuleProvider.h" #include "llvm/CodeGen/MachineCodeEmitter.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/ExecutionEngine/GenericValue.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetJITInfo.h" #include "llvm/Support/DynamicLinker.h" #include <iostream> using namespace llvm; JIT::JIT(ModuleProvider *MP, TargetMachine &tm, TargetJITInfo &tji) : ExecutionEngine(MP), TM(tm), TJI(tji), PM(MP) { setTargetData(TM.getTargetData()); // Initialize MCE MCE = createEmitter(*this); // Add target data PM.add(new TargetData(TM.getTargetData())); // Compile LLVM Code down to machine code in the intermediate representation TJI.addPassesToJITCompile(PM); // Turn the machine code intermediate representation into bytes in memory that // may be executed. if (TM.addPassesToEmitMachineCode(PM, *MCE)) { std::cerr << "Target '" << TM.getName() << "' doesn't support machine code emission!\n"; abort(); } } JIT::~JIT() { delete MCE; delete &TM; } /// run - Start execution with the specified function and arguments. /// GenericValue JIT::runFunction(Function *F, const std::vector<GenericValue> &ArgValues) { assert(F && "Function *F was null at entry to run()"); void *FPtr = getPointerToFunction(F); assert(FPtr && "Pointer to fn's code was null after getPointerToFunction"); const FunctionType *FTy = F->getFunctionType(); const Type *RetTy = FTy->getReturnType(); assert((FTy->getNumParams() <= ArgValues.size() || FTy->isVarArg()) && "Too many arguments passed into function!"); assert(FTy->getNumParams() == ArgValues.size() && "This doesn't support passing arguments through varargs (yet)!"); // Handle some common cases first. These cases correspond to common `main' // prototypes. if (RetTy == Type::IntTy || RetTy == Type::UIntTy || RetTy == Type::VoidTy) { switch (ArgValues.size()) { case 3: if ((FTy->getParamType(0) == Type::IntTy || FTy->getParamType(0) == Type::UIntTy) && isa<PointerType>(FTy->getParamType(1)) && isa<PointerType>(FTy->getParamType(2))) { int (*PF)(int, char **, const char **) = (int(*)(int, char **, const char **))FPtr; // Call the function. GenericValue rv; rv.IntVal = PF(ArgValues[0].IntVal, (char **)GVTOP(ArgValues[1]), (const char **)GVTOP(ArgValues[2])); return rv; } break; case 2: if ((FTy->getParamType(0) == Type::IntTy || FTy->getParamType(0) == Type::UIntTy) && isa<PointerType>(FTy->getParamType(1))) { int (*PF)(int, char **) = (int(*)(int, char **))FPtr; // Call the function. GenericValue rv; rv.IntVal = PF(ArgValues[0].IntVal, (char **)GVTOP(ArgValues[1])); return rv; } break; case 1: if (FTy->getNumParams() == 1 && (FTy->getParamType(0) == Type::IntTy || FTy->getParamType(0) == Type::UIntTy)) { GenericValue rv; int (*PF)(int) = (int(*)(int))FPtr; rv.IntVal = PF(ArgValues[0].IntVal); return rv; } break; } } // Handle cases where no arguments are passed first. if (ArgValues.empty()) { GenericValue rv; switch (RetTy->getTypeID()) { default: assert(0 && "Unknown return type for function call!"); case Type::BoolTyID: rv.BoolVal = ((bool(*)())FPtr)(); return rv; case Type::SByteTyID: case Type::UByteTyID: rv.SByteVal = ((char(*)())FPtr)(); return rv; case Type::ShortTyID: case Type::UShortTyID: rv.ShortVal = ((short(*)())FPtr)(); return rv; case Type::VoidTyID: case Type::IntTyID: case Type::UIntTyID: rv.IntVal = ((int(*)())FPtr)(); return rv; case Type::LongTyID: case Type::ULongTyID: rv.LongVal = ((int64_t(*)())FPtr)(); return rv; case Type::FloatTyID: rv.FloatVal = ((float(*)())FPtr)(); return rv; case Type::DoubleTyID: rv.DoubleVal = ((double(*)())FPtr)(); return rv; case Type::PointerTyID: return PTOGV(((void*(*)())FPtr)()); } } // Okay, this is not one of our quick and easy cases. Because we don't have a // full FFI, we have to codegen a nullary stub function that just calls the // function we are interested in, passing in constants for all of the // arguments. Make this function and return. // First, create the function. FunctionType *STy=FunctionType::get(RetTy, std::vector<const Type*>(), false); Function *Stub = new Function(STy, Function::InternalLinkage, "", F->getParent()); // Insert a basic block. BasicBlock *StubBB = new BasicBlock("", Stub); // Convert all of the GenericValue arguments over to constants. Note that we // currently don't support varargs. std::vector<Value*> Args; for (unsigned i = 0, e = ArgValues.size(); i != e; ++i) { Constant *C = 0; const Type *ArgTy = FTy->getParamType(i); const GenericValue &AV = ArgValues[i]; switch (ArgTy->getTypeID()) { default: assert(0 && "Unknown argument type for function call!"); case Type::BoolTyID: C = ConstantBool::get(AV.BoolVal); break; case Type::SByteTyID: C = ConstantSInt::get(ArgTy, AV.SByteVal); break; case Type::UByteTyID: C = ConstantUInt::get(ArgTy, AV.UByteVal); break; case Type::ShortTyID: C = ConstantSInt::get(ArgTy, AV.ShortVal); break; case Type::UShortTyID: C = ConstantUInt::get(ArgTy, AV.UShortVal); break; case Type::IntTyID: C = ConstantSInt::get(ArgTy, AV.IntVal); break; case Type::UIntTyID: C = ConstantUInt::get(ArgTy, AV.UIntVal); break; case Type::LongTyID: C = ConstantSInt::get(ArgTy, AV.LongVal); break; case Type::ULongTyID: C = ConstantUInt::get(ArgTy, AV.ULongVal); break; case Type::FloatTyID: C = ConstantFP ::get(ArgTy, AV.FloatVal); break; case Type::DoubleTyID: C = ConstantFP ::get(ArgTy, AV.DoubleVal); break; case Type::PointerTyID: void *ArgPtr = GVTOP(AV); if (sizeof(void*) == 4) { C = ConstantSInt::get(Type::IntTy, (int)(intptr_t)ArgPtr); } else { C = ConstantSInt::get(Type::LongTy, (intptr_t)ArgPtr); } C = ConstantExpr::getCast(C, ArgTy); // Cast the integer to pointer break; } Args.push_back(C); } Value *TheCall = new CallInst(F, Args, "", StubBB); if (TheCall->getType() != Type::VoidTy) new ReturnInst(TheCall, StubBB); // Return result of the call. else new ReturnInst(StubBB); // Just return void. // Finally, return the value returned by our nullary stub function. return runFunction(Stub, std::vector<GenericValue>()); } /// runJITOnFunction - Run the FunctionPassManager full of /// just-in-time compilation passes on F, hopefully filling in /// GlobalAddress[F] with the address of F's machine code. /// void JIT::runJITOnFunction(Function *F) { static bool isAlreadyCodeGenerating = false; assert(!isAlreadyCodeGenerating && "Error: Recursive compilation detected!"); // JIT the function isAlreadyCodeGenerating = true; PM.run(*F); isAlreadyCodeGenerating = false; // If the function referred to a global variable that had not yet been // emitted, it allocates memory for the global, but doesn't emit it yet. Emit // all of these globals now. while (!PendingGlobals.empty()) { const GlobalVariable *GV = PendingGlobals.back(); PendingGlobals.pop_back(); EmitGlobalVariable(GV); } } /// getPointerToFunction - This method is used to get the address of the /// specified function, compiling it if neccesary. /// void *JIT::getPointerToFunction(Function *F) { if (void *Addr = getPointerToGlobalIfAvailable(F)) return Addr; // Check if function already code gen'd // Make sure we read in the function if it exists in this Module if (F->hasNotBeenReadFromBytecode()) try { MP->materializeFunction(F); } catch ( std::string& errmsg ) { std::cerr << "Error reading function '" << F->getName() << "' from bytecode file: " << errmsg << "\n"; abort(); } catch (...) { std::cerr << "Error reading function '" << F->getName() << "from bytecode file!\n"; abort(); } if (F->isExternal()) { void *Addr = getPointerToNamedFunction(F->getName()); addGlobalMapping(F, Addr); return Addr; } runJITOnFunction(F); void *Addr = getPointerToGlobalIfAvailable(F); assert(Addr && "Code generation didn't add function to GlobalAddress table!"); return Addr; } // getPointerToFunctionOrStub - If the specified function has been // code-gen'd, return a pointer to the function. If not, compile it, or use // a stub to implement lazy compilation if available. // void *JIT::getPointerToFunctionOrStub(Function *F) { // If we have already code generated the function, just return the address. if (void *Addr = getPointerToGlobalIfAvailable(F)) return Addr; // If the target supports "stubs" for functions, get a stub now. if (void *Ptr = TJI.getJITStubForFunction(F, *MCE)) return Ptr; // Otherwise, if the target doesn't support it, just codegen the function. return getPointerToFunction(F); } /// getOrEmitGlobalVariable - Return the address of the specified global /// variable, possibly emitting it to memory if needed. This is used by the /// Emitter. void *JIT::getOrEmitGlobalVariable(const GlobalVariable *GV) { void *Ptr = getPointerToGlobalIfAvailable(GV); if (Ptr) return Ptr; // If the global is external, just remember the address. if (GV->isExternal()) { Ptr = GetAddressOfSymbol(GV->getName().c_str()); if (Ptr == 0) { std::cerr << "Could not resolve external global address: " << GV->getName() << "\n"; abort(); } } else { // If the global hasn't been emitted to memory yet, allocate space. We will // actually initialize the global after current function has finished // compilation. Ptr =new char[getTargetData().getTypeSize(GV->getType()->getElementType())]; PendingGlobals.push_back(GV); } addGlobalMapping(GV, Ptr); return Ptr; } /// recompileAndRelinkFunction - This method is used to force a function /// which has already been compiled, to be compiled again, possibly /// after it has been modified. Then the entry to the old copy is overwritten /// with a branch to the new copy. If there was no old copy, this acts /// just like JIT::getPointerToFunction(). /// void *JIT::recompileAndRelinkFunction(Function *F) { void *OldAddr = getPointerToGlobalIfAvailable(F); // If it's not already compiled there is no reason to patch it up. if (OldAddr == 0) { return getPointerToFunction(F); } // Delete the old function mapping. addGlobalMapping(F, 0); // Recodegen the function runJITOnFunction(F); // Update state, forward the old function to the new function. void *Addr = getPointerToGlobalIfAvailable(F); assert(Addr && "Code generation didn't add function to GlobalAddress table!"); TJI.replaceMachineCodeForFunction(OldAddr, Addr); return Addr; } /// freeMachineCodeForFunction - release machine code memory for given Function /// void JIT::freeMachineCodeForFunction(Function *F) { // currently a no-op } <commit_msg>This method does not exist any longer.<commit_after>//===-- JIT.cpp - LLVM Just in Time Compiler ------------------------------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This tool implements a just-in-time compiler for LLVM, allowing direct // execution of LLVM bytecode in an efficient manner. // //===----------------------------------------------------------------------===// #include "JIT.h" #include "llvm/Constants.h" #include "llvm/DerivedTypes.h" #include "llvm/Function.h" #include "llvm/GlobalVariable.h" #include "llvm/Instructions.h" #include "llvm/ModuleProvider.h" #include "llvm/CodeGen/MachineCodeEmitter.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/ExecutionEngine/GenericValue.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetJITInfo.h" #include "llvm/Support/DynamicLinker.h" #include <iostream> using namespace llvm; JIT::JIT(ModuleProvider *MP, TargetMachine &tm, TargetJITInfo &tji) : ExecutionEngine(MP), TM(tm), TJI(tji), PM(MP) { setTargetData(TM.getTargetData()); // Initialize MCE MCE = createEmitter(*this); // Add target data PM.add(new TargetData(TM.getTargetData())); // Compile LLVM Code down to machine code in the intermediate representation TJI.addPassesToJITCompile(PM); // Turn the machine code intermediate representation into bytes in memory that // may be executed. if (TM.addPassesToEmitMachineCode(PM, *MCE)) { std::cerr << "Target '" << TM.getName() << "' doesn't support machine code emission!\n"; abort(); } } JIT::~JIT() { delete MCE; delete &TM; } /// run - Start execution with the specified function and arguments. /// GenericValue JIT::runFunction(Function *F, const std::vector<GenericValue> &ArgValues) { assert(F && "Function *F was null at entry to run()"); void *FPtr = getPointerToFunction(F); assert(FPtr && "Pointer to fn's code was null after getPointerToFunction"); const FunctionType *FTy = F->getFunctionType(); const Type *RetTy = FTy->getReturnType(); assert((FTy->getNumParams() <= ArgValues.size() || FTy->isVarArg()) && "Too many arguments passed into function!"); assert(FTy->getNumParams() == ArgValues.size() && "This doesn't support passing arguments through varargs (yet)!"); // Handle some common cases first. These cases correspond to common `main' // prototypes. if (RetTy == Type::IntTy || RetTy == Type::UIntTy || RetTy == Type::VoidTy) { switch (ArgValues.size()) { case 3: if ((FTy->getParamType(0) == Type::IntTy || FTy->getParamType(0) == Type::UIntTy) && isa<PointerType>(FTy->getParamType(1)) && isa<PointerType>(FTy->getParamType(2))) { int (*PF)(int, char **, const char **) = (int(*)(int, char **, const char **))FPtr; // Call the function. GenericValue rv; rv.IntVal = PF(ArgValues[0].IntVal, (char **)GVTOP(ArgValues[1]), (const char **)GVTOP(ArgValues[2])); return rv; } break; case 2: if ((FTy->getParamType(0) == Type::IntTy || FTy->getParamType(0) == Type::UIntTy) && isa<PointerType>(FTy->getParamType(1))) { int (*PF)(int, char **) = (int(*)(int, char **))FPtr; // Call the function. GenericValue rv; rv.IntVal = PF(ArgValues[0].IntVal, (char **)GVTOP(ArgValues[1])); return rv; } break; case 1: if (FTy->getNumParams() == 1 && (FTy->getParamType(0) == Type::IntTy || FTy->getParamType(0) == Type::UIntTy)) { GenericValue rv; int (*PF)(int) = (int(*)(int))FPtr; rv.IntVal = PF(ArgValues[0].IntVal); return rv; } break; } } // Handle cases where no arguments are passed first. if (ArgValues.empty()) { GenericValue rv; switch (RetTy->getTypeID()) { default: assert(0 && "Unknown return type for function call!"); case Type::BoolTyID: rv.BoolVal = ((bool(*)())FPtr)(); return rv; case Type::SByteTyID: case Type::UByteTyID: rv.SByteVal = ((char(*)())FPtr)(); return rv; case Type::ShortTyID: case Type::UShortTyID: rv.ShortVal = ((short(*)())FPtr)(); return rv; case Type::VoidTyID: case Type::IntTyID: case Type::UIntTyID: rv.IntVal = ((int(*)())FPtr)(); return rv; case Type::LongTyID: case Type::ULongTyID: rv.LongVal = ((int64_t(*)())FPtr)(); return rv; case Type::FloatTyID: rv.FloatVal = ((float(*)())FPtr)(); return rv; case Type::DoubleTyID: rv.DoubleVal = ((double(*)())FPtr)(); return rv; case Type::PointerTyID: return PTOGV(((void*(*)())FPtr)()); } } // Okay, this is not one of our quick and easy cases. Because we don't have a // full FFI, we have to codegen a nullary stub function that just calls the // function we are interested in, passing in constants for all of the // arguments. Make this function and return. // First, create the function. FunctionType *STy=FunctionType::get(RetTy, std::vector<const Type*>(), false); Function *Stub = new Function(STy, Function::InternalLinkage, "", F->getParent()); // Insert a basic block. BasicBlock *StubBB = new BasicBlock("", Stub); // Convert all of the GenericValue arguments over to constants. Note that we // currently don't support varargs. std::vector<Value*> Args; for (unsigned i = 0, e = ArgValues.size(); i != e; ++i) { Constant *C = 0; const Type *ArgTy = FTy->getParamType(i); const GenericValue &AV = ArgValues[i]; switch (ArgTy->getTypeID()) { default: assert(0 && "Unknown argument type for function call!"); case Type::BoolTyID: C = ConstantBool::get(AV.BoolVal); break; case Type::SByteTyID: C = ConstantSInt::get(ArgTy, AV.SByteVal); break; case Type::UByteTyID: C = ConstantUInt::get(ArgTy, AV.UByteVal); break; case Type::ShortTyID: C = ConstantSInt::get(ArgTy, AV.ShortVal); break; case Type::UShortTyID: C = ConstantUInt::get(ArgTy, AV.UShortVal); break; case Type::IntTyID: C = ConstantSInt::get(ArgTy, AV.IntVal); break; case Type::UIntTyID: C = ConstantUInt::get(ArgTy, AV.UIntVal); break; case Type::LongTyID: C = ConstantSInt::get(ArgTy, AV.LongVal); break; case Type::ULongTyID: C = ConstantUInt::get(ArgTy, AV.ULongVal); break; case Type::FloatTyID: C = ConstantFP ::get(ArgTy, AV.FloatVal); break; case Type::DoubleTyID: C = ConstantFP ::get(ArgTy, AV.DoubleVal); break; case Type::PointerTyID: void *ArgPtr = GVTOP(AV); if (sizeof(void*) == 4) { C = ConstantSInt::get(Type::IntTy, (int)(intptr_t)ArgPtr); } else { C = ConstantSInt::get(Type::LongTy, (intptr_t)ArgPtr); } C = ConstantExpr::getCast(C, ArgTy); // Cast the integer to pointer break; } Args.push_back(C); } Value *TheCall = new CallInst(F, Args, "", StubBB); if (TheCall->getType() != Type::VoidTy) new ReturnInst(TheCall, StubBB); // Return result of the call. else new ReturnInst(StubBB); // Just return void. // Finally, return the value returned by our nullary stub function. return runFunction(Stub, std::vector<GenericValue>()); } /// runJITOnFunction - Run the FunctionPassManager full of /// just-in-time compilation passes on F, hopefully filling in /// GlobalAddress[F] with the address of F's machine code. /// void JIT::runJITOnFunction(Function *F) { static bool isAlreadyCodeGenerating = false; assert(!isAlreadyCodeGenerating && "Error: Recursive compilation detected!"); // JIT the function isAlreadyCodeGenerating = true; PM.run(*F); isAlreadyCodeGenerating = false; // If the function referred to a global variable that had not yet been // emitted, it allocates memory for the global, but doesn't emit it yet. Emit // all of these globals now. while (!PendingGlobals.empty()) { const GlobalVariable *GV = PendingGlobals.back(); PendingGlobals.pop_back(); EmitGlobalVariable(GV); } } /// getPointerToFunction - This method is used to get the address of the /// specified function, compiling it if neccesary. /// void *JIT::getPointerToFunction(Function *F) { if (void *Addr = getPointerToGlobalIfAvailable(F)) return Addr; // Check if function already code gen'd // Make sure we read in the function if it exists in this Module if (F->hasNotBeenReadFromBytecode()) try { MP->materializeFunction(F); } catch ( std::string& errmsg ) { std::cerr << "Error reading function '" << F->getName() << "' from bytecode file: " << errmsg << "\n"; abort(); } catch (...) { std::cerr << "Error reading function '" << F->getName() << "from bytecode file!\n"; abort(); } if (F->isExternal()) { void *Addr = getPointerToNamedFunction(F->getName()); addGlobalMapping(F, Addr); return Addr; } runJITOnFunction(F); void *Addr = getPointerToGlobalIfAvailable(F); assert(Addr && "Code generation didn't add function to GlobalAddress table!"); return Addr; } // getPointerToFunctionOrStub - If the specified function has been // code-gen'd, return a pointer to the function. If not, compile it, or use // a stub to implement lazy compilation if available. // void *JIT::getPointerToFunctionOrStub(Function *F) { // If we have already code generated the function, just return the address. if (void *Addr = getPointerToGlobalIfAvailable(F)) return Addr; // Otherwise, if the target doesn't support it, just codegen the function. return getPointerToFunction(F); } /// getOrEmitGlobalVariable - Return the address of the specified global /// variable, possibly emitting it to memory if needed. This is used by the /// Emitter. void *JIT::getOrEmitGlobalVariable(const GlobalVariable *GV) { void *Ptr = getPointerToGlobalIfAvailable(GV); if (Ptr) return Ptr; // If the global is external, just remember the address. if (GV->isExternal()) { Ptr = GetAddressOfSymbol(GV->getName().c_str()); if (Ptr == 0) { std::cerr << "Could not resolve external global address: " << GV->getName() << "\n"; abort(); } } else { // If the global hasn't been emitted to memory yet, allocate space. We will // actually initialize the global after current function has finished // compilation. Ptr =new char[getTargetData().getTypeSize(GV->getType()->getElementType())]; PendingGlobals.push_back(GV); } addGlobalMapping(GV, Ptr); return Ptr; } /// recompileAndRelinkFunction - This method is used to force a function /// which has already been compiled, to be compiled again, possibly /// after it has been modified. Then the entry to the old copy is overwritten /// with a branch to the new copy. If there was no old copy, this acts /// just like JIT::getPointerToFunction(). /// void *JIT::recompileAndRelinkFunction(Function *F) { void *OldAddr = getPointerToGlobalIfAvailable(F); // If it's not already compiled there is no reason to patch it up. if (OldAddr == 0) { return getPointerToFunction(F); } // Delete the old function mapping. addGlobalMapping(F, 0); // Recodegen the function runJITOnFunction(F); // Update state, forward the old function to the new function. void *Addr = getPointerToGlobalIfAvailable(F); assert(Addr && "Code generation didn't add function to GlobalAddress table!"); TJI.replaceMachineCodeForFunction(OldAddr, Addr); return Addr; } /// freeMachineCodeForFunction - release machine code memory for given Function /// void JIT::freeMachineCodeForFunction(Function *F) { // currently a no-op } <|endoftext|>
<commit_before>// Copyright Steinwurf ApS 2011-2012. // Distributed under the "STEINWURF RESEARCH LICENSE 1.0". // See accompanying file LICENSE.rst or // http://www.steinwurf.com/licensing #include <ctime> #include <cstdint> #include <cstdio> #include <cstdlib> #include <cstring> // for memset, memcmp #include <vector> #include <set> #include <gauge/gauge.hpp> extern "C" { #include "erasure_code.h" #include "test.h" } #include "../throughput_benchmark.hpp" #define TEST_SOURCES 250 #define MMAX TEST_SOURCES #define KMAX TEST_SOURCES struct isa_encoder { isa_encoder(uint32_t symbols, uint32_t symbol_size) : m_symbols(symbols), m_symbol_size(symbol_size) { k = m_symbols; m = m_symbols + 6; m_block_size = m_symbols * m_symbol_size; m_payload_count = m_symbols; // Symbol size must be a multiple of 64 assert(m_symbol_size % 64 == 0); // Allocate the arrays int i, j; void* buf = 0; for (i = 0; i < m; i++) { if (posix_memalign(&buf, 64, m_symbol_size)) { printf("alloc error: Fail\n"); } m_buffs[i] = (uint8_t*)buf; } // Make random data for(i = 0; i < k; i++) for(j = 0; j < (int)m_symbol_size; j++) m_buffs[i][j] = rand(); } ~isa_encoder() { for (int i = 0; i < m; i++) { free(m_buffs[i]); } } void encode_all() { assert(m_payload_count == (uint32_t)(m-k)); gf_gen_rs_matrix(a, m, k); // Make parity vects ec_init_tables(k, m - k, &a[k * k], g_tbls); ec_encode_data_sse(m_symbol_size, k, m - k, g_tbls, m_buffs, &m_buffs[k]); } uint32_t block_size() { return m_block_size; } uint32_t symbol_size() { return m_symbol_size; } uint32_t payload_size() { return m_symbol_size; } uint32_t payload_count() { return m_payload_count; } protected: friend class isa_decoder; uint8_t* m_buffs[TEST_SOURCES]; uint8_t a[MMAX*KMAX]; uint8_t g_tbls[KMAX*TEST_SOURCES*32]; // Code parameters int k, m; // Number of symbols uint32_t m_symbols; // Size of k+m symbols uint32_t m_symbol_size; // Size of a full generation (k symbols) uint32_t m_block_size; // Number of generated payloads uint32_t m_payload_count; }; struct isa_decoder { isa_decoder(uint32_t symbols, uint32_t symbol_size) : m_symbols(symbols), m_symbol_size(symbol_size) { k = m_symbols; m = m_symbols + 6; m_block_size = m_symbols * m_symbol_size; m_decoding_result = -1; // Allocate the arrays int i; void* buf = 0; for (i = 0; i < m; i++) { if (posix_memalign(&buf, 64, m_symbol_size)) { printf("alloc error: Fail\n"); } m_buffs[i] = (uint8_t*)buf; } // Simulate m-k erasures (erase all original symbols) // No original symbols used during decoding (worst case) memset(src_in_err, 0, TEST_SOURCES); std::set<uint8_t> erased; while (erased.size() < m - k) { uint8_t random_symbol = rand() % k; auto ret = erased.insert(random_symbol); // Skip this symbol if it was already included in the erased set if (ret.second==false) continue; // Indicate the erasure src_in_err[random_symbol] = 1; } // Fill the erasure list int errors = 0; for (const uint8_t& e : erased) { src_err_list[errors++] = e; } nerrs = erased.size(); assert(nerrs == m - k); gf_gen_rs_matrix(a, m, k); } ~isa_decoder() { for (int i = 0; i < m; i++) { free(m_buffs[i]); } } void decode_all(std::shared_ptr<isa_encoder> encoder) { uint32_t payload_count = encoder->payload_count(); assert(payload_count == (uint32_t)(m - k)); int i, j, r; // Construct b by removing error rows from a // a contains m rows and k columns for (i = 0, r = 0; i < k; i++, r++) { while (src_in_err[r]) r++; for (j = 0; j < k; j++) b[k * i + j] = a[k * r + j]; } // Invert the b matrix into d if (gf_invert_matrix(b, d, k) < 0) { printf("BAD MATRIX\n"); m_decoding_result = -1; return; } // Set data pointers to point to the encoder payloads for (i = 0, r = 0; i < k; i++, r++) { while (src_in_err[r]) r++; data[i] = encoder->m_buffs[r]; } // Construct c by copying the erasure rows from the inverse matrix d for (i = 0; i < nerrs; i++) { for (j = 0; j < k; j++) c[k * i + j] = d[k * src_err_list[i] + j]; } // Recover data ec_init_tables(k, nerrs, c, g_tbls); ec_encode_data_sse(m_symbol_size, k, nerrs, g_tbls, &data[0], &m_buffs[0]); m_decoding_result = 0; } bool verify_data(std::shared_ptr<isa_encoder> encoder) { assert(m_block_size == encoder->block_size()); for (int i = 0; i < nerrs; i++) { if (memcmp(m_buffs[i], encoder->m_buffs[src_err_list[i]], m_symbol_size)) { return false; } } return true; } bool is_complete() { return (m_decoding_result != -1); } uint32_t block_size() { return m_block_size; } uint32_t symbol_size() { return m_symbol_size; } uint32_t payload_size() { return m_symbol_size; } protected: uint8_t* m_buffs[TEST_SOURCES]; uint8_t a[MMAX*KMAX], b[MMAX*KMAX], c[MMAX*KMAX], d[MMAX*KMAX]; uint8_t g_tbls[KMAX*TEST_SOURCES*32]; uint8_t src_in_err[TEST_SOURCES]; uint8_t src_err_list[TEST_SOURCES]; uint8_t* data[TEST_SOURCES]; // Code parameters int k, m; // Number of erasures int nerrs; // Number of symbols uint32_t m_symbols; // Size of k+m symbols uint32_t m_symbol_size; // Size of a full generation (k symbols) uint32_t m_block_size; int m_decoding_result; }; BENCHMARK_OPTION(throughput_options) { gauge::po::options_description options; std::vector<uint32_t> symbols; symbols.push_back(16); // symbols.push_back(32); // symbols.push_back(64); // symbols.push_back(128); // symbols.push_back(256); // symbols.push_back(512); auto default_symbols = gauge::po::value<std::vector<uint32_t> >()->default_value( symbols, "")->multitoken(); // Symbol size must be a multiple of 64 std::vector<uint32_t> symbol_size; symbol_size.push_back(1000000); auto default_symbol_size = gauge::po::value<std::vector<uint32_t> >()->default_value( symbol_size, "")->multitoken(); std::vector<std::string> types; types.push_back("encoder"); types.push_back("decoder"); auto default_types = gauge::po::value<std::vector<std::string> >()->default_value( types, "")->multitoken(); options.add_options() ("symbols", default_symbols, "Set the number of symbols"); options.add_options() ("symbol_size", default_symbol_size, "Set the symbol size in bytes"); options.add_options() ("type", default_types, "Set type [encoder|decoder]"); gauge::runner::instance().register_options(options); } //------------------------------------------------------------------ // ISA Erasure Code //------------------------------------------------------------------ typedef throughput_benchmark<isa_encoder, isa_decoder> isa_throughput; BENCHMARK_F(isa_throughput, ISA, ErasureCode, 10) { run_benchmark(); } int main(int argc, const char* argv[]) { srand(static_cast<uint32_t>(time(0))); gauge::runner::add_default_printers(); gauge::runner::run_benchmarks(argc, argv); return 0; } <commit_msg>Remove ISA encoder payload count assert<commit_after>// Copyright Steinwurf ApS 2011-2012. // Distributed under the "STEINWURF RESEARCH LICENSE 1.0". // See accompanying file LICENSE.rst or // http://www.steinwurf.com/licensing #include <ctime> #include <cstdint> #include <cstdio> #include <cstdlib> #include <cstring> // for memset, memcmp #include <vector> #include <set> #include <gauge/gauge.hpp> extern "C" { #include "erasure_code.h" #include "test.h" } #include "../throughput_benchmark.hpp" #define TEST_SOURCES 250 #define MMAX TEST_SOURCES #define KMAX TEST_SOURCES struct isa_encoder { isa_encoder(uint32_t symbols, uint32_t symbol_size) : m_symbols(symbols), m_symbol_size(symbol_size) { k = m_symbols; m = m_symbols + 6; m_block_size = m_symbols * m_symbol_size; m_payload_count = m - k; // Symbol size must be a multiple of 64 assert(m_symbol_size % 64 == 0); // Allocate the arrays int i, j; void* buf = 0; for (i = 0; i < m; i++) { if (posix_memalign(&buf, 64, m_symbol_size)) { printf("alloc error: Fail\n"); } m_buffs[i] = (uint8_t*)buf; } // Make random data for(i = 0; i < k; i++) for(j = 0; j < (int)m_symbol_size; j++) m_buffs[i][j] = rand(); } ~isa_encoder() { for (int i = 0; i < m; i++) { free(m_buffs[i]); } } void encode_all() { //assert(m_payload_count == (uint32_t)(m-k)); gf_gen_rs_matrix(a, m, k); // Make parity vects ec_init_tables(k, m - k, &a[k * k], g_tbls); ec_encode_data_sse(m_symbol_size, k, m - k, g_tbls, m_buffs, &m_buffs[k]); } uint32_t block_size() { return m_block_size; } uint32_t symbol_size() { return m_symbol_size; } uint32_t payload_size() { return m_symbol_size; } uint32_t payload_count() { return m_payload_count; } protected: friend class isa_decoder; uint8_t* m_buffs[TEST_SOURCES]; uint8_t a[MMAX*KMAX]; uint8_t g_tbls[KMAX*TEST_SOURCES*32]; // Code parameters int k, m; // Number of symbols uint32_t m_symbols; // Size of k+m symbols uint32_t m_symbol_size; // Size of a full generation (k symbols) uint32_t m_block_size; // Number of generated payloads uint32_t m_payload_count; }; struct isa_decoder { isa_decoder(uint32_t symbols, uint32_t symbol_size) : m_symbols(symbols), m_symbol_size(symbol_size) { k = m_symbols; m = m_symbols + 6; m_block_size = m_symbols * m_symbol_size; m_decoding_result = -1; // Allocate the arrays int i; void* buf = 0; for (i = 0; i < m; i++) { if (posix_memalign(&buf, 64, m_symbol_size)) { printf("alloc error: Fail\n"); } m_buffs[i] = (uint8_t*)buf; } // Simulate m-k erasures (erase all original symbols) // No original symbols used during decoding (worst case) memset(src_in_err, 0, TEST_SOURCES); std::set<uint8_t> erased; while (erased.size() < m - k) { uint8_t random_symbol = rand() % k; auto ret = erased.insert(random_symbol); // Skip this symbol if it was already included in the erased set if (ret.second==false) continue; // Indicate the erasure src_in_err[random_symbol] = 1; } // Fill the erasure list int errors = 0; for (const uint8_t& e : erased) { src_err_list[errors++] = e; } nerrs = erased.size(); assert(nerrs == m - k); gf_gen_rs_matrix(a, m, k); } ~isa_decoder() { for (int i = 0; i < m; i++) { free(m_buffs[i]); } } void decode_all(std::shared_ptr<isa_encoder> encoder) { uint32_t payload_count = encoder->payload_count(); assert(payload_count == (uint32_t)(m - k)); int i, j, r; // Construct b by removing error rows from a // a contains m rows and k columns for (i = 0, r = 0; i < k; i++, r++) { while (src_in_err[r]) r++; for (j = 0; j < k; j++) b[k * i + j] = a[k * r + j]; } // Invert the b matrix into d if (gf_invert_matrix(b, d, k) < 0) { printf("BAD MATRIX\n"); m_decoding_result = -1; return; } // Set data pointers to point to the encoder payloads for (i = 0, r = 0; i < k; i++, r++) { while (src_in_err[r]) r++; data[i] = encoder->m_buffs[r]; } // Construct c by copying the erasure rows from the inverse matrix d for (i = 0; i < nerrs; i++) { for (j = 0; j < k; j++) c[k * i + j] = d[k * src_err_list[i] + j]; } // Recover data ec_init_tables(k, nerrs, c, g_tbls); ec_encode_data_sse(m_symbol_size, k, nerrs, g_tbls, &data[0], &m_buffs[0]); m_decoding_result = 0; } bool verify_data(std::shared_ptr<isa_encoder> encoder) { assert(m_block_size == encoder->block_size()); for (int i = 0; i < nerrs; i++) { if (memcmp(m_buffs[i], encoder->m_buffs[src_err_list[i]], m_symbol_size)) { return false; } } return true; } bool is_complete() { return (m_decoding_result != -1); } uint32_t block_size() { return m_block_size; } uint32_t symbol_size() { return m_symbol_size; } uint32_t payload_size() { return m_symbol_size; } protected: uint8_t* m_buffs[TEST_SOURCES]; uint8_t a[MMAX*KMAX], b[MMAX*KMAX], c[MMAX*KMAX], d[MMAX*KMAX]; uint8_t g_tbls[KMAX*TEST_SOURCES*32]; uint8_t src_in_err[TEST_SOURCES]; uint8_t src_err_list[TEST_SOURCES]; uint8_t* data[TEST_SOURCES]; // Code parameters int k, m; // Number of erasures int nerrs; // Number of symbols uint32_t m_symbols; // Size of k+m symbols uint32_t m_symbol_size; // Size of a full generation (k symbols) uint32_t m_block_size; int m_decoding_result; }; BENCHMARK_OPTION(throughput_options) { gauge::po::options_description options; std::vector<uint32_t> symbols; symbols.push_back(16); // symbols.push_back(32); // symbols.push_back(64); // symbols.push_back(128); // symbols.push_back(256); // symbols.push_back(512); auto default_symbols = gauge::po::value<std::vector<uint32_t> >()->default_value( symbols, "")->multitoken(); // Symbol size must be a multiple of 64 std::vector<uint32_t> symbol_size; symbol_size.push_back(1000000); auto default_symbol_size = gauge::po::value<std::vector<uint32_t> >()->default_value( symbol_size, "")->multitoken(); std::vector<std::string> types; types.push_back("encoder"); types.push_back("decoder"); auto default_types = gauge::po::value<std::vector<std::string> >()->default_value( types, "")->multitoken(); options.add_options() ("symbols", default_symbols, "Set the number of symbols"); options.add_options() ("symbol_size", default_symbol_size, "Set the symbol size in bytes"); options.add_options() ("type", default_types, "Set type [encoder|decoder]"); gauge::runner::instance().register_options(options); } //------------------------------------------------------------------ // ISA Erasure Code //------------------------------------------------------------------ typedef throughput_benchmark<isa_encoder, isa_decoder> isa_throughput; BENCHMARK_F(isa_throughput, ISA, ErasureCode, 10) { run_benchmark(); } int main(int argc, const char* argv[]) { srand(static_cast<uint32_t>(time(0))); gauge::runner::add_default_printers(); gauge::runner::run_benchmarks(argc, argv); return 0; } <|endoftext|>
<commit_before>#include "simdjson/jsonparser.h" #ifndef _MSC_VER #include "linux-perf-events.h" #include <unistd.h> #ifdef __linux__ #include <libgen.h> #endif //__linux__ #endif // _MSC_VER #include <memory> #include "benchmark.h" // #define RAPIDJSON_SSE2 // bad for performance // #define RAPIDJSON_SSE42 // bad for performance #include "rapidjson/document.h" #include "rapidjson/reader.h" #include "rapidjson/stringbuffer.h" #include "rapidjson/writer.h" #include "sajson.h" #ifdef ALLPARSER #include "fastjson.cpp" #include "fastjson_dom.cpp" #include "gason.cpp" #include "json11.cpp" extern "C" { #include "cJSON.c" #include "cJSON.h" #include "jsmn.c" #include "jsmn.h" #include "ujdecode.h" #include "ultrajsondec.c" } #include "jsoncpp.cpp" #include "json/json.h" #endif using namespace rapidjson; #ifdef ALLPARSER // fastjson has a tricky interface void on_json_error(void *, const fastjson::ErrorContext &ec) { // std::cerr<<"ERROR: "<<ec.mesg<<std::endl; } bool fastjson_parse(const char *input) { fastjson::Token token; fastjson::dom::Chunk chunk; return fastjson::dom::parse_string(input, &token, &chunk, 0, &on_json_error, NULL); } // end of fastjson stuff #endif int main(int argc, char *argv[]) { bool verbose = false; bool justdata = false; int c; while ((c = getopt(argc, argv, "vt")) != -1) switch (c) { case 't': justdata = true; break; case 'v': verbose = true; break; default: abort(); } if (optind >= argc) { std::cerr << "Usage: " << argv[0] << " <jsonfile>" << std::endl; std::cerr << "Or " << argv[0] << " -v <jsonfile>" << std::endl; std::cerr << "The '-t' flag outputs a table. " << std::endl; exit(1); } const char *filename = argv[optind]; if (optind + 1 < argc) { std::cerr << "warning: ignoring everything after " << argv[optind + 1] << std::endl; } padded_string p; try { get_corpus(filename).swap(p); } catch (const std::exception &e) { // caught by reference to base std::cout << "Could not load the file " << filename << std::endl; return EXIT_FAILURE; } if (verbose) { std::cout << "Input has "; if (p.size() > 1024 * 1024) std::cout << p.size() / (1024 * 1024) << " MB "; else if (p.size() > 1024) std::cout << p.size() / 1024 << " KB "; else std::cout << p.size() << " B "; std::cout << std::endl; } ParsedJson pj; bool allocok = pj.allocateCapacity(p.size(), 1024); if (!allocok) { std::cerr << "can't allocate memory" << std::endl; return EXIT_FAILURE; } int repeat = 50; int volume = p.size(); if (justdata) { printf("%-42s %20s %20s %20s %20s \n", "name", "cycles_per_byte", "cycles_per_byte_err", "gb_per_s", "gb_per_s_err"); } if (!justdata) BEST_TIME("simdjson (dynamic mem) ", build_parsed_json(p).isValid(), true, , repeat, volume, !justdata); // (static alloc) BEST_TIME("simdjson ", json_parse(p, pj), simdjson::SUCCESS, , repeat, volume, !justdata); rapidjson::Document d; char *buffer = (char *)malloc(p.size() + 1); memcpy(buffer, p.data(), p.size()); buffer[p.size()] = '\0'; #ifndef ALLPARSER if (!justdata) #endif BEST_TIME( "RapidJSON ", d.Parse<kParseValidateEncodingFlag>((const char *)buffer) .HasParseError(), false, memcpy(buffer, p.data(), p.size()), repeat, volume, !justdata); BEST_TIME("RapidJSON (insitu)", d.ParseInsitu<kParseValidateEncodingFlag>(buffer).HasParseError(), false, memcpy(buffer, p.data(), p.size()) && (buffer[p.size()] = '\0'), repeat, volume, !justdata); #ifndef ALLPARSER if (!justdata) #endif BEST_TIME("sajson (dynamic mem)", sajson::parse(sajson::dynamic_allocation(), sajson::mutable_string_view(p.size(), buffer)) .is_valid(), true, memcpy(buffer, p.data(), p.size()), repeat, volume, !justdata); size_t astbuffersize = p.size(); size_t *ast_buffer = (size_t *)malloc(astbuffersize * sizeof(size_t)); // (static alloc, insitu) BEST_TIME("sajson", sajson::parse(sajson::bounded_allocation(ast_buffer, astbuffersize), sajson::mutable_string_view(p.size(), buffer)) .is_valid(), true, memcpy(buffer, p.data(), p.size()), repeat, volume, !justdata); #ifdef ALLPARSER std::string json11err; BEST_TIME("dropbox (json11) ", ((json11::Json::parse(buffer, json11err).is_null()) || (!json11err.empty())), false, memcpy(buffer, p.data(), p.size()), repeat, volume, !justdata); BEST_TIME("fastjson ", fastjson_parse(buffer), true, memcpy(buffer, p.data(), p.size()), repeat, volume, !justdata); JsonValue value; JsonAllocator allocator; char *endptr; BEST_TIME("gason ", jsonParse(buffer, &endptr, &value, allocator), JSON_OK, memcpy(buffer, p.data(), p.size()), repeat, volume, !justdata); void *state; BEST_TIME("ultrajson ", (UJDecode(buffer, p.size(), NULL, &state) == NULL), false, memcpy(buffer, p.data(), p.size()), repeat, volume, !justdata); { std::unique_ptr<jsmntok_t[]> tokens = std::make_unique<jsmntok_t[]>(p.size()); jsmn_parser parser; jsmn_init(&parser); memcpy(buffer, p.data(), p.size()); buffer[p.size()] = '\0'; BEST_TIME("jsmn ", (jsmn_parse(&parser, buffer, p.size(), tokens.get(), p.size()) > 0), true, jsmn_init(&parser), repeat, volume, !justdata); } memcpy(buffer, p.data(), p.size()); buffer[p.size()] = '\0'; cJSON *tree = cJSON_Parse(buffer); BEST_TIME("cJSON ", ((tree = cJSON_Parse(buffer)) != NULL), true, cJSON_Delete(tree), repeat, volume, !justdata); cJSON_Delete(tree); Json::CharReaderBuilder b; Json::CharReader *jsoncppreader = b.newCharReader(); Json::Value root; Json::String errs; BEST_TIME("jsoncpp ", jsoncppreader->parse(buffer, buffer + volume, &root, &errs), true, , repeat, volume, !justdata); delete jsoncppreader; #endif if (!justdata) BEST_TIME("memcpy ", (memcpy(buffer, p.data(), p.size()) == buffer), true, , repeat, volume, !justdata); #ifdef __linux__ if (!justdata) { printf("\n \n <doing additional analysis with performance counters (Linux " "only)>\n"); std::vector<int> evts; evts.push_back(PERF_COUNT_HW_CPU_CYCLES); evts.push_back(PERF_COUNT_HW_INSTRUCTIONS); evts.push_back(PERF_COUNT_HW_BRANCH_MISSES); evts.push_back(PERF_COUNT_HW_CACHE_REFERENCES); evts.push_back(PERF_COUNT_HW_CACHE_MISSES); LinuxEvents<PERF_TYPE_HARDWARE> unified(evts); std::vector<unsigned long long> results; std::vector<unsigned long long> stats; results.resize(evts.size()); stats.resize(evts.size()); std::fill(stats.begin(), stats.end(), 0); // unnecessary for (int i = 0; i < repeat; i++) { unified.start(); if (json_parse(p, pj) != simdjson::SUCCESS) printf("bug\n"); unified.end(results); std::transform(stats.begin(), stats.end(), results.begin(), stats.begin(), std::plus<unsigned long long>()); } printf("simdjson : cycles %10.0f instructions %10.0f branchmisses %10.0f " "cacheref %10.0f cachemisses %10.0f bytespercachemiss %10.0f " "inspercycle %10.1f insperbyte %10.1f\n", stats[0] * 1.0 / repeat, stats[1] * 1.0 / repeat, stats[2] * 1.0 / repeat, stats[3] * 1.0 / repeat, stats[4] * 1.0 / repeat, volume * repeat * 1.0 / stats[2], stats[1] * 1.0 / stats[0], stats[1] * 1.0 / (volume * repeat)); std::fill(stats.begin(), stats.end(), 0); for (int i = 0; i < repeat; i++) { memcpy(buffer, p.data(), p.size()); buffer[p.size()] = '\0'; unified.start(); if (d.ParseInsitu<kParseValidateEncodingFlag>(buffer).HasParseError() != false) printf("bug\n"); unified.end(results); std::transform(stats.begin(), stats.end(), results.begin(), stats.begin(), std::plus<unsigned long long>()); } printf("RapidJSON: cycles %10.0f instructions %10.0f branchmisses %10.0f " "cacheref %10.0f cachemisses %10.0f bytespercachemiss %10.0f " "inspercycle %10.1f insperbyte %10.1f\n", stats[0] * 1.0 / repeat, stats[1] * 1.0 / repeat, stats[2] * 1.0 / repeat, stats[3] * 1.0 / repeat, stats[4] * 1.0 / repeat, volume * repeat * 1.0 / stats[2], stats[1] * 1.0 / stats[0], stats[1] * 1.0 / (volume * repeat)); std::fill(stats.begin(), stats.end(), 0); // unnecessary for (int i = 0; i < repeat; i++) { memcpy(buffer, p.data(), p.size()); unified.start(); if (sajson::parse(sajson::bounded_allocation(ast_buffer, astbuffersize), sajson::mutable_string_view(p.size(), buffer)) .is_valid() != true) printf("bug\n"); unified.end(results); std::transform(stats.begin(), stats.end(), results.begin(), stats.begin(), std::plus<unsigned long long>()); } printf("sajson : cycles %10.0f instructions %10.0f branchmisses %10.0f " "cacheref %10.0f cachemisses %10.0f bytespercachemiss %10.0f " "inspercycle %10.1f insperbyte %10.1f\n", stats[0] * 1.0 / repeat, stats[1] * 1.0 / repeat, stats[2] * 1.0 / repeat, stats[3] * 1.0 / repeat, stats[4] * 1.0 / repeat, volume * repeat * 1.0 / stats[2], stats[1] * 1.0 / stats[0], stats[1] * 1.0 / (volume * repeat)); } #endif // __linux__ free(ast_buffer); free(buffer); } <commit_msg>Making it practical to benchmark large files.<commit_after>#include "simdjson/jsonparser.h" #ifndef _MSC_VER #include "linux-perf-events.h" #include <unistd.h> #ifdef __linux__ #include <libgen.h> #endif //__linux__ #endif // _MSC_VER #include <memory> #include "benchmark.h" // #define RAPIDJSON_SSE2 // bad for performance // #define RAPIDJSON_SSE42 // bad for performance #include "rapidjson/document.h" #include "rapidjson/reader.h" #include "rapidjson/stringbuffer.h" #include "rapidjson/writer.h" #include "sajson.h" #ifdef ALLPARSER #include "fastjson.cpp" #include "fastjson_dom.cpp" #include "gason.cpp" #include "json11.cpp" extern "C" { #include "cJSON.c" #include "cJSON.h" #include "jsmn.c" #include "jsmn.h" #include "ujdecode.h" #include "ultrajsondec.c" } #include "jsoncpp.cpp" #include "json/json.h" #endif using namespace rapidjson; #ifdef ALLPARSER // fastjson has a tricky interface void on_json_error(void *, const fastjson::ErrorContext &ec) { // std::cerr<<"ERROR: "<<ec.mesg<<std::endl; } bool fastjson_parse(const char *input) { fastjson::Token token; fastjson::dom::Chunk chunk; return fastjson::dom::parse_string(input, &token, &chunk, 0, &on_json_error, NULL); } // end of fastjson stuff #endif int main(int argc, char *argv[]) { bool verbose = false; bool justdata = false; int c; while ((c = getopt(argc, argv, "vt")) != -1) switch (c) { case 't': justdata = true; break; case 'v': verbose = true; break; default: abort(); } if (optind >= argc) { std::cerr << "Usage: " << argv[0] << " <jsonfile>" << std::endl; std::cerr << "Or " << argv[0] << " -v <jsonfile>" << std::endl; std::cerr << "The '-t' flag outputs a table. " << std::endl; exit(1); } const char *filename = argv[optind]; if (optind + 1 < argc) { std::cerr << "warning: ignoring everything after " << argv[optind + 1] << std::endl; } padded_string p; try { get_corpus(filename).swap(p); } catch (const std::exception &e) { // caught by reference to base std::cout << "Could not load the file " << filename << std::endl; return EXIT_FAILURE; } if (verbose) { std::cout << "Input has "; if (p.size() > 1024 * 1024) std::cout << p.size() / (1024 * 1024) << " MB "; else if (p.size() > 1024) std::cout << p.size() / 1024 << " KB "; else std::cout << p.size() << " B "; std::cout << std::endl; } ParsedJson pj; bool allocok = pj.allocateCapacity(p.size(), 1024); if (!allocok) { std::cerr << "can't allocate memory" << std::endl; return EXIT_FAILURE; } int repeat = p.size() < 100 * 1000 * 1000 ? 50 : 5; int volume = p.size(); if (justdata) { printf("%-42s %20s %20s %20s %20s \n", "name", "cycles_per_byte", "cycles_per_byte_err", "gb_per_s", "gb_per_s_err"); } if (!justdata) BEST_TIME("simdjson (dynamic mem) ", build_parsed_json(p).isValid(), true, , repeat, volume, !justdata); // (static alloc) BEST_TIME("simdjson ", json_parse(p, pj), simdjson::SUCCESS, , repeat, volume, !justdata); rapidjson::Document d; char *buffer = (char *)malloc(p.size() + 1); memcpy(buffer, p.data(), p.size()); buffer[p.size()] = '\0'; #ifndef ALLPARSER if (!justdata) #endif BEST_TIME( "RapidJSON ", d.Parse<kParseValidateEncodingFlag>((const char *)buffer) .HasParseError(), false, memcpy(buffer, p.data(), p.size()), repeat, volume, !justdata); BEST_TIME("RapidJSON (insitu)", d.ParseInsitu<kParseValidateEncodingFlag>(buffer).HasParseError(), false, memcpy(buffer, p.data(), p.size()) && (buffer[p.size()] = '\0'), repeat, volume, !justdata); #ifndef ALLPARSER if (!justdata) #endif BEST_TIME("sajson (dynamic mem)", sajson::parse(sajson::dynamic_allocation(), sajson::mutable_string_view(p.size(), buffer)) .is_valid(), true, memcpy(buffer, p.data(), p.size()), repeat, volume, !justdata); size_t astbuffersize = p.size(); size_t *ast_buffer = (size_t *)malloc(astbuffersize * sizeof(size_t)); // (static alloc, insitu) BEST_TIME("sajson", sajson::parse(sajson::bounded_allocation(ast_buffer, astbuffersize), sajson::mutable_string_view(p.size(), buffer)) .is_valid(), true, memcpy(buffer, p.data(), p.size()), repeat, volume, !justdata); #ifdef ALLPARSER std::string json11err; BEST_TIME("dropbox (json11) ", ((json11::Json::parse(buffer, json11err).is_null()) || (!json11err.empty())), false, memcpy(buffer, p.data(), p.size()), repeat, volume, !justdata); BEST_TIME("fastjson ", fastjson_parse(buffer), true, memcpy(buffer, p.data(), p.size()), repeat, volume, !justdata); JsonValue value; JsonAllocator allocator; char *endptr; BEST_TIME("gason ", jsonParse(buffer, &endptr, &value, allocator), JSON_OK, memcpy(buffer, p.data(), p.size()), repeat, volume, !justdata); void *state; BEST_TIME("ultrajson ", (UJDecode(buffer, p.size(), NULL, &state) == NULL), false, memcpy(buffer, p.data(), p.size()), repeat, volume, !justdata); { std::unique_ptr<jsmntok_t[]> tokens = std::make_unique<jsmntok_t[]>(p.size()); jsmn_parser parser; jsmn_init(&parser); memcpy(buffer, p.data(), p.size()); buffer[p.size()] = '\0'; BEST_TIME("jsmn ", (jsmn_parse(&parser, buffer, p.size(), tokens.get(), p.size()) > 0), true, jsmn_init(&parser), repeat, volume, !justdata); } memcpy(buffer, p.data(), p.size()); buffer[p.size()] = '\0'; cJSON *tree = cJSON_Parse(buffer); BEST_TIME("cJSON ", ((tree = cJSON_Parse(buffer)) != NULL), true, cJSON_Delete(tree), repeat, volume, !justdata); cJSON_Delete(tree); Json::CharReaderBuilder b; Json::CharReader *jsoncppreader = b.newCharReader(); Json::Value root; Json::String errs; BEST_TIME("jsoncpp ", jsoncppreader->parse(buffer, buffer + volume, &root, &errs), true, , repeat, volume, !justdata); delete jsoncppreader; #endif if (!justdata) BEST_TIME("memcpy ", (memcpy(buffer, p.data(), p.size()) == buffer), true, , repeat, volume, !justdata); #ifdef __linux__ if (!justdata) { printf("\n \n <doing additional analysis with performance counters (Linux " "only)>\n"); std::vector<int> evts; evts.push_back(PERF_COUNT_HW_CPU_CYCLES); evts.push_back(PERF_COUNT_HW_INSTRUCTIONS); evts.push_back(PERF_COUNT_HW_BRANCH_MISSES); evts.push_back(PERF_COUNT_HW_CACHE_REFERENCES); evts.push_back(PERF_COUNT_HW_CACHE_MISSES); LinuxEvents<PERF_TYPE_HARDWARE> unified(evts); std::vector<unsigned long long> results; std::vector<unsigned long long> stats; results.resize(evts.size()); stats.resize(evts.size()); std::fill(stats.begin(), stats.end(), 0); // unnecessary for (int i = 0; i < repeat; i++) { unified.start(); if (json_parse(p, pj) != simdjson::SUCCESS) printf("bug\n"); unified.end(results); std::transform(stats.begin(), stats.end(), results.begin(), stats.begin(), std::plus<unsigned long long>()); } printf("simdjson : cycles %10.0f instructions %10.0f branchmisses %10.0f " "cacheref %10.0f cachemisses %10.0f bytespercachemiss %10.0f " "inspercycle %10.1f insperbyte %10.1f\n", stats[0] * 1.0 / repeat, stats[1] * 1.0 / repeat, stats[2] * 1.0 / repeat, stats[3] * 1.0 / repeat, stats[4] * 1.0 / repeat, volume * repeat * 1.0 / stats[2], stats[1] * 1.0 / stats[0], stats[1] * 1.0 / (volume * repeat)); std::fill(stats.begin(), stats.end(), 0); for (int i = 0; i < repeat; i++) { memcpy(buffer, p.data(), p.size()); buffer[p.size()] = '\0'; unified.start(); if (d.ParseInsitu<kParseValidateEncodingFlag>(buffer).HasParseError() != false) printf("bug\n"); unified.end(results); std::transform(stats.begin(), stats.end(), results.begin(), stats.begin(), std::plus<unsigned long long>()); } printf("RapidJSON: cycles %10.0f instructions %10.0f branchmisses %10.0f " "cacheref %10.0f cachemisses %10.0f bytespercachemiss %10.0f " "inspercycle %10.1f insperbyte %10.1f\n", stats[0] * 1.0 / repeat, stats[1] * 1.0 / repeat, stats[2] * 1.0 / repeat, stats[3] * 1.0 / repeat, stats[4] * 1.0 / repeat, volume * repeat * 1.0 / stats[2], stats[1] * 1.0 / stats[0], stats[1] * 1.0 / (volume * repeat)); std::fill(stats.begin(), stats.end(), 0); // unnecessary for (int i = 0; i < repeat; i++) { memcpy(buffer, p.data(), p.size()); unified.start(); if (sajson::parse(sajson::bounded_allocation(ast_buffer, astbuffersize), sajson::mutable_string_view(p.size(), buffer)) .is_valid() != true) printf("bug\n"); unified.end(results); std::transform(stats.begin(), stats.end(), results.begin(), stats.begin(), std::plus<unsigned long long>()); } printf("sajson : cycles %10.0f instructions %10.0f branchmisses %10.0f " "cacheref %10.0f cachemisses %10.0f bytespercachemiss %10.0f " "inspercycle %10.1f insperbyte %10.1f\n", stats[0] * 1.0 / repeat, stats[1] * 1.0 / repeat, stats[2] * 1.0 / repeat, stats[3] * 1.0 / repeat, stats[4] * 1.0 / repeat, volume * repeat * 1.0 / stats[2], stats[1] * 1.0 / stats[0], stats[1] * 1.0 / (volume * repeat)); } #endif // __linux__ free(ast_buffer); free(buffer); } <|endoftext|>
<commit_before>//======================================================================= // Copyright (c) 2014-2016 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #define CPM_LIB #include "benchmark.hpp" CPM_DIRECT_BENCH_TWO_PASS_NS_P( NARY_POLICY(VALUES_POLICY(100, 500, 550, 600, 1000, 2000, 2500), VALUES_POLICY(100, 120, 500, 1000, 1200, 2000, 5000)), "rbm_hidden [rbm]", [](std::size_t d1, std::size_t d2){ return std::make_tuple(dvec(d1), dvec(d2), dvec(d2), dvec(d2), dmat(d1, d2));}, [](dvec& v, dvec& h, dvec& b, dvec& t, dmat& w){ h = etl::sigmoid(b + etl::mul(v, w, t)); } ) CPM_DIRECT_BENCH_TWO_PASS_NS_P( NARY_POLICY(VALUES_POLICY(100, 500, 550, 600, 1000, 2000, 2500), VALUES_POLICY(100, 120, 500, 1000, 1200, 2000, 5000)), "rbm_visible [rbm]", [](std::size_t d1, std::size_t d2){ return std::make_tuple(dvec(d1), dvec(d2), dvec(d1), dvec(d1), dmat(d1, d2));}, [](dvec& v, dvec& h, dvec& c, dvec& t, dmat& w){ v = etl::sigmoid(c + etl::mul(w, h, t)); } ) //Small optimizations // 1. Some time can be saved by keeping one matrix for the im2col result and pass it to conv_2d_valid_multi // 2. fflip is already done in conv_2d_multi and fflip(fflip(A)) = A, therefore only tranpose is necessary. // This means calling the _prepared version of conv_2d_valid_multi CPM_DIRECT_BENCH_TWO_PASS_NS_P( NARY_POLICY(VALUES_POLICY(1, 1, 1, 3, 3, 3, 30, 40), VALUES_POLICY(10, 10, 30, 30, 30, 40, 40, 40), VALUES_POLICY(28, 28, 28, 28, 36, 36, 36, 36), VALUES_POLICY(5, 11, 19, 19, 19, 19, 19, 19)), "conv_rbm_hidden [crbm]", [](std::size_t nc, std::size_t k, std::size_t nv, std::size_t nh){ auto nw = nv - nh + 1; return std::make_tuple(dmat4(nc,k,nw,nw), dmat4(nc,k,nw,nw), dvec(k), dmat3(nc,nv,nv), dmat3(k, nh, nh), dmat4(2ul, k, nh, nh));}, [](dmat4& w, dmat4& w_t, dvec& b, dmat3& v, dmat3& h, dmat4 v_cv){ v_cv(1) = 0; w_t = w; for(std::size_t channel = 0; channel < etl::dim<0>(w_t); ++channel){ for(size_t k = 0; k < etl::dim<0>(b); ++k){ w_t(channel)(k).fflip_inplace(); } } for(std::size_t channel = 0; channel < etl::dim<0>(w_t); ++channel){ conv_2d_valid_multi(v(channel), w_t(channel), v_cv(0)); v_cv(1) += v_cv(0); } h = etl::sigmoid(etl::rep(b, etl::dim<1>(h), etl::dim<2>(h)) + v_cv(1)); } ) CPM_DIRECT_BENCH_TWO_PASS_NS_P( NARY_POLICY(VALUES_POLICY(1, 1, 1, 3, 3, 3, 30, 40), VALUES_POLICY(10, 10, 30, 30, 30, 40, 40, 40), VALUES_POLICY(28, 28, 28, 28, 36, 36, 36, 36), VALUES_POLICY(5, 11, 19, 19, 19, 19, 19, 19)), "conv_rbm_visible [crbm]", [](std::size_t nc, std::size_t k, std::size_t nv, std::size_t nh){ auto nw = nv - nh + 1; return std::make_tuple(dmat4(nc,k,nw,nw), dvec(k), dvec(nc), dmat3(nc,nv,nv), dmat3(k,nh,nh), dmat3(k,nv,nv));}, [](dmat4& w, dvec& b, dvec& c, dmat3& v, dmat3& h, dmat3& h_cv){ for(std::size_t channel = 0; channel < etl::dim<0>(c); ++channel){ for(std::size_t k = 0; k < etl::dim<0>(b); ++k){ h_cv(k) = etl::conv_2d_full(h(k), w(channel)(k)); } v(channel) = sigmoid(c(channel) + sum_l(h_cv)); } } ) <commit_msg>Avoid one flip<commit_after>//======================================================================= // Copyright (c) 2014-2016 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #define CPM_LIB #include "benchmark.hpp" CPM_DIRECT_BENCH_TWO_PASS_NS_P( NARY_POLICY(VALUES_POLICY(100, 500, 550, 600, 1000, 2000, 2500), VALUES_POLICY(100, 120, 500, 1000, 1200, 2000, 5000)), "rbm_hidden [rbm]", [](std::size_t d1, std::size_t d2){ return std::make_tuple(dvec(d1), dvec(d2), dvec(d2), dvec(d2), dmat(d1, d2));}, [](dvec& v, dvec& h, dvec& b, dvec& t, dmat& w){ h = etl::sigmoid(b + etl::mul(v, w, t)); } ) CPM_DIRECT_BENCH_TWO_PASS_NS_P( NARY_POLICY(VALUES_POLICY(100, 500, 550, 600, 1000, 2000, 2500), VALUES_POLICY(100, 120, 500, 1000, 1200, 2000, 5000)), "rbm_visible [rbm]", [](std::size_t d1, std::size_t d2){ return std::make_tuple(dvec(d1), dvec(d2), dvec(d1), dvec(d1), dmat(d1, d2));}, [](dvec& v, dvec& h, dvec& c, dvec& t, dmat& w){ v = etl::sigmoid(c + etl::mul(w, h, t)); } ) //Small optimizations // 1. Some time can be saved by keeping one matrix for the im2col result and pass it to conv_2d_valid_multi // 2. fflip is already done in conv_2d_multi and fflip(fflip(A)) = A, therefore only tranpose is necessary. // This means calling the _prepared version of conv_2d_valid_multi CPM_DIRECT_BENCH_TWO_PASS_NS_P( NARY_POLICY(VALUES_POLICY(1, 1, 1, 3, 3, 3, 30, 40), VALUES_POLICY(10, 10, 30, 30, 30, 40, 40, 40), VALUES_POLICY(28, 28, 28, 28, 36, 36, 36, 36), VALUES_POLICY(5, 11, 19, 19, 19, 19, 19, 19)), "conv_rbm_hidden [crbm]", [](std::size_t nc, std::size_t k, std::size_t nv, std::size_t nh){ auto nw = nv - nh + 1; return std::make_tuple(dmat4(nc,k,nw,nw), dvec(k), dmat3(nc,nv,nv), dmat3(k, nh, nh), dmat4(2ul, k, nh, nh));}, [](dmat4& w, dvec& b, dmat3& v, dmat3& h, dmat4 v_cv){ v_cv(1) = 0; for(std::size_t channel = 0; channel < etl::dim<0>(w); ++channel){ conv_2d_valid_multi_flipped(v(channel), w(channel), v_cv(0)); v_cv(1) += v_cv(0); } h = etl::sigmoid(etl::rep(b, etl::dim<1>(h), etl::dim<2>(h)) + v_cv(1)); } ) CPM_DIRECT_BENCH_TWO_PASS_NS_P( NARY_POLICY(VALUES_POLICY(1, 1, 1, 3, 3, 3, 30, 40), VALUES_POLICY(10, 10, 30, 30, 30, 40, 40, 40), VALUES_POLICY(28, 28, 28, 28, 36, 36, 36, 36), VALUES_POLICY(5, 11, 19, 19, 19, 19, 19, 19)), "conv_rbm_visible [crbm]", [](std::size_t nc, std::size_t k, std::size_t nv, std::size_t nh){ auto nw = nv - nh + 1; return std::make_tuple(dmat4(nc,k,nw,nw), dvec(k), dvec(nc), dmat3(nc,nv,nv), dmat3(k,nh,nh), dmat3(k,nv,nv));}, [](dmat4& w, dvec& b, dvec& c, dmat3& v, dmat3& h, dmat3& h_cv){ for(std::size_t channel = 0; channel < etl::dim<0>(c); ++channel){ for(std::size_t k = 0; k < etl::dim<0>(b); ++k){ h_cv(k) = etl::conv_2d_full(h(k), w(channel)(k)); } v(channel) = sigmoid(c(channel) + sum_l(h_cv)); } } ) <|endoftext|>
<commit_before>#include <celero/Celero.h> #include <forward_list> #include <annis/query.h> #include <annis/annosearch/exactannokeysearch.h> #include <annis/annosearch/exactannovaluesearch.h> #include <annis/annosearch/regexannosearch.h> #include <annis/operators/pointing.h> #include <annis/operators/precedence.h> #ifdef ENABLE_VALGRIND #include <valgrind/callgrind.h> #else #define CALLGRIND_STOP_INSTRUMENTATION #define CALLGRIND_START_INSTRUMENTATION #endif // ENABLE_VALGRIND using namespace annis; int main(int argc, char** argv) { try { celero::Run(argc, argv); return 0; } catch(std::string ex) { std::cerr << "ERROR: " << ex << std::endl; } catch(char const* ex) { std::cerr << "ERROR: " << ex << std::endl; } catch(...) { std::cerr << "Some exception was thrown!" << std::endl; } return -1; } static std::shared_ptr<ThreadPool> benchmarkThreadPool = std::make_shared<ThreadPool>(8); class GUMFixture : public celero::TestFixture { public: GUMFixture() : count_PosDepPos(246), count_UsedTo(1) { } /* virtual std::vector<std::pair<int64_t, uint64_t>> getExperimentValues() const override { std::vector<std::pair<int64_t, uint64_t>> problemSpace; for(int64_t i=1; i <= std::thread::hardware_concurrency(); i++) { problemSpace.push_back(std::make_pair(i, uint64_t(0))); } return problemSpace; } */ /// Before each run, build a vector of random integers. virtual void setUp(int64_t experimentValue) { CALLGRIND_STOP_INSTRUMENTATION; char* testDataEnv = std::getenv("ANNIS4_TEST_DATA"); std::string dataDir("data"); if (testDataEnv != NULL) { dataDir = testDataEnv; } db.load(dataDir + "/GUM", true); nonParallelConfig.numOfBackgroundTasks = 0; nonParallelConfig.threadPool = nullptr; // taskConfigs.resize(9); threadConfigs.reserve(8); for(int64_t i=1; i <= 8; i++) { QueryConfig threadCfg; threadCfg.threadPool = benchmarkThreadPool; threadCfg.numOfBackgroundTasks = i; threadConfigs.push_back(threadCfg); } } std::shared_ptr<Query> query_PosDepPos(QueryConfig config) { std::shared_ptr<Query> result = std::make_shared<Query>(db, config); result->addNode(std::make_shared<ExactAnnoKeySearch>(db, "pos")); result->addNode(std::make_shared<ExactAnnoKeySearch>(db, "pos")); Annotation edgeAnno = {db.strings.add("func"), 0, db.strings.add("dep")}; result->addOperator(std::make_shared<Pointing>(db.edges, db.strings, "", "dep", edgeAnno), 0, 1); return result; } std::shared_ptr<Query> query_UsedTo(QueryConfig config) { std::shared_ptr<Query> result = std::make_shared<Query>(db, config); result->addNode(std::make_shared<RegexAnnoSearch>(db, "pos", "NN.*")); result->addNode(std::make_shared<ExactAnnoValueSearch>(db, "annis4_internal", "tok", "used")); result->addNode(std::make_shared<ExactAnnoValueSearch>(db, "annis4_internal", "tok", "to")); result->addOperator(std::make_shared<Precedence>(db, db.edges), 0, 1); result->addOperator(std::make_shared<Precedence>(db, db.edges), 1, 2); return result; } DB db; QueryConfig nonParallelConfig; std::vector<QueryConfig> threadConfigs; const int count_PosDepPos; const int count_UsedTo; }; BASELINE_F(PosDepPos, NonParallel, GUMFixture, 0, 0) { CALLGRIND_START_INSTRUMENTATION; std::shared_ptr<Query> q = query_PosDepPos(nonParallelConfig); int counter=0; while(q->next()) { counter++; } if(counter != count_PosDepPos) { throw "Invalid count for N0, was " + std::to_string(counter) + " but should have been " + std::to_string(count_PosDepPos); } CALLGRIND_STOP_INSTRUMENTATION; } BASELINE_F(UsedTo, NonParallel, GUMFixture, 0, 0) { CALLGRIND_START_INSTRUMENTATION; std::shared_ptr<Query> q = query_UsedTo(nonParallelConfig); int counter=0; while(q->next()) { counter++; } if(counter != count_UsedTo) { throw "Invalid count for N0, was " + std::to_string(counter) + " but should have been " + std::to_string(count_UsedTo); } CALLGRIND_STOP_INSTRUMENTATION; } #define COUNT_BENCH(group, idx) \ BENCHMARK_F(group, Thread_##idx, GUMFixture, 0, 0) \ { \ CALLGRIND_START_INSTRUMENTATION;\ std::shared_ptr<Query> q = query_##group(threadConfigs[idx-1]);\ int counter=0; \ while(q->next()) { \ counter++; \ } \ if(counter != count_##group)\ {\ throw "Invalid count for Thread_" #idx ", was " + std::to_string(counter) + " but should have been " + std::to_string(count_##group);\ }\ CALLGRIND_STOP_INSTRUMENTATION;\ } COUNT_BENCH(PosDepPos, 1) COUNT_BENCH(PosDepPos, 2) COUNT_BENCH(PosDepPos, 3) COUNT_BENCH(PosDepPos, 4) COUNT_BENCH(PosDepPos, 5) COUNT_BENCH(PosDepPos, 6) COUNT_BENCH(PosDepPos, 7) COUNT_BENCH(PosDepPos, 8) COUNT_BENCH(UsedTo, 1) COUNT_BENCH(UsedTo, 2) COUNT_BENCH(UsedTo, 3) COUNT_BENCH(UsedTo, 4) COUNT_BENCH(UsedTo, 5) COUNT_BENCH(UsedTo, 6) COUNT_BENCH(UsedTo, 7) COUNT_BENCH(UsedTo, 8) BASELINE(CreateThreadPool, N1, 0, 0) { ThreadPool t(1); } BENCHMARK(CreateThreadPool, N2, 0, 0) { ThreadPool t(2); } BENCHMARK(CreateThreadPool, N3, 0, 0) { ThreadPool t(3); } BENCHMARK(CreateThreadPool, N4, 0, 0) { ThreadPool t(4); } BENCHMARK(CreateThreadPool, N5, 0, 0) { ThreadPool t(5); } BENCHMARK(CreateThreadPool, N6, 0, 0) { ThreadPool t(6); } BENCHMARK(CreateThreadPool, N7, 0, 0) { ThreadPool t(7); } BENCHMARK(CreateThreadPool, N8, 0, 0) { ThreadPool t(8); } BASELINE(MatchQueue, Vector, 0, 0) { std::list<std::vector<Match>> queue; for(int i=0; i < 1000; i++) { std::vector<Match> m(2); queue.emplace_back(m); } std::vector<Match> m; while(!queue.empty()) { m = queue.front(); queue.pop_front(); } } BENCHMARK(MatchQueue, VectorMove, 0, 0) { std::list<std::vector<Match>> queue; for(int i=0; i < 1000; i++) { std::vector<Match> m(2); queue.emplace_back(m); } std::vector<Match> m; while(!queue.empty()) { m = std::move(queue.front()); queue.pop_front(); } } BENCHMARK(MatchQueue, VectorMoveDeque, 0, 0) { std::deque<std::vector<Match>> queue; for(int i=0; i < 1000; i++) { std::vector<Match> m(2); queue.emplace_back(m); } std::vector<Match> m; while(!queue.empty()) { m = std::move(queue.front()); queue.pop_front(); } } BENCHMARK(MatchQueue, VectorSwap, 0, 0) { std::list<std::vector<Match>> queue; for(int i=0; i < 1000; i++) { std::vector<Match> m(2); queue.emplace_back(m); } std::vector<Match> m; while(!queue.empty()) { m.swap(queue.front()); queue.pop_front(); } } BENCHMARK(MatchQueue, VectorSwapDeque, 0, 0) { std::deque<std::vector<Match>> queue; for(int i=0; i < 1000; i++) { std::vector<Match> m(2); queue.emplace_back(m); } std::vector<Match> m; while(!queue.empty()) { m.swap(queue.front()); queue.pop_front(); } } BENCHMARK(MatchQueue, Deque, 0, 0) { std::list<std::deque<Match>> queue; for(int i=0; i < 1000; i++) { std::deque<Match> m(2); queue.emplace_back(m); } std::deque<Match> m; while(!queue.empty()) { m = std::move(queue.front()); queue.pop_front(); } } BENCHMARK(MatchQueue, DequeSwap, 0, 0) { std::list<std::deque<Match>> queue; for(int i=0; i < 1000; i++) { std::deque<Match> m(2); queue.emplace_back(m); } std::deque<Match> m; while(!queue.empty()) { m.swap(queue.front()); queue.pop_front(); } } BENCHMARK(MatchQueue, DequeSwapDeque, 0, 0) { std::deque<std::deque<Match>> queue; for(int i=0; i < 1000; i++) { std::deque<Match> m(2); queue.emplace_back(m); } std::deque<Match> m; while(!queue.empty()) { m.swap(queue.front()); queue.pop_front(); } } BENCHMARK(MatchQueue, List, 0, 0) { std::list<std::list<Match>> queue; for(int i=0; i < 1000; i++) { std::list<Match> m(2); queue.emplace_back(m); } std::list<Match> m; while(!queue.empty()) { m = std::move(queue.front()); queue.pop_front(); } } <commit_msg>Add more data points to the parallel benchmark.<commit_after>#include <celero/Celero.h> #include <forward_list> #include <annis/query.h> #include <annis/annosearch/exactannokeysearch.h> #include <annis/annosearch/exactannovaluesearch.h> #include <annis/annosearch/regexannosearch.h> #include <annis/operators/pointing.h> #include <annis/operators/precedence.h> #ifdef ENABLE_VALGRIND #include <valgrind/callgrind.h> #else #define CALLGRIND_STOP_INSTRUMENTATION #define CALLGRIND_START_INSTRUMENTATION #endif // ENABLE_VALGRIND using namespace annis; int main(int argc, char** argv) { try { celero::Run(argc, argv); return 0; } catch(std::string ex) { std::cerr << "ERROR: " << ex << std::endl; } catch(char const* ex) { std::cerr << "ERROR: " << ex << std::endl; } catch(...) { std::cerr << "Some exception was thrown!" << std::endl; } return -1; } static std::shared_ptr<ThreadPool> benchmarkThreadPool = std::make_shared<ThreadPool>(32); class GUMFixture : public celero::TestFixture { public: GUMFixture() : count_PosDepPos(246), count_UsedTo(1) { } /* virtual std::vector<std::pair<int64_t, uint64_t>> getExperimentValues() const override { std::vector<std::pair<int64_t, uint64_t>> problemSpace; for(int64_t i=1; i <= std::thread::hardware_concurrency(); i++) { problemSpace.push_back(std::make_pair(i, uint64_t(0))); } return problemSpace; } */ /// Before each run, build a vector of random integers. virtual void setUp(int64_t experimentValue) { CALLGRIND_STOP_INSTRUMENTATION; char* testDataEnv = std::getenv("ANNIS4_TEST_DATA"); std::string dataDir("data"); if (testDataEnv != NULL) { dataDir = testDataEnv; } db.load(dataDir + "/GUM", true); nonParallelConfig.numOfBackgroundTasks = 0; nonParallelConfig.threadPool = nullptr; // taskConfigs.resize(9); threadConfigs.resize(32); for(size_t i=1; i < threadConfigs.size(); i++) { threadConfigs[i].threadPool = benchmarkThreadPool; threadConfigs[i].numOfBackgroundTasks = i; } } std::shared_ptr<Query> query_PosDepPos(QueryConfig config) { std::shared_ptr<Query> result = std::make_shared<Query>(db, config); result->addNode(std::make_shared<ExactAnnoKeySearch>(db, "pos")); result->addNode(std::make_shared<ExactAnnoKeySearch>(db, "pos")); Annotation edgeAnno = {db.strings.add("func"), 0, db.strings.add("dep")}; result->addOperator(std::make_shared<Pointing>(db.edges, db.strings, "", "dep", edgeAnno), 0, 1); return result; } std::shared_ptr<Query> query_UsedTo(QueryConfig config) { std::shared_ptr<Query> result = std::make_shared<Query>(db, config); result->addNode(std::make_shared<RegexAnnoSearch>(db, "pos", "NN.*")); result->addNode(std::make_shared<ExactAnnoValueSearch>(db, "annis4_internal", "tok", "used")); result->addNode(std::make_shared<ExactAnnoValueSearch>(db, "annis4_internal", "tok", "to")); result->addOperator(std::make_shared<Precedence>(db, db.edges), 0, 1); result->addOperator(std::make_shared<Precedence>(db, db.edges), 1, 2); return result; } DB db; QueryConfig nonParallelConfig; std::vector<QueryConfig> threadConfigs; const int count_PosDepPos; const int count_UsedTo; }; BASELINE_F(PosDepPos, NonParallel, GUMFixture, 0, 0) { CALLGRIND_START_INSTRUMENTATION; std::shared_ptr<Query> q = query_PosDepPos(nonParallelConfig); int counter=0; while(q->next()) { counter++; } if(counter != count_PosDepPos) { throw "Invalid count for N0, was " + std::to_string(counter) + " but should have been " + std::to_string(count_PosDepPos); } CALLGRIND_STOP_INSTRUMENTATION; } BASELINE_F(UsedTo, NonParallel, GUMFixture, 0, 0) { CALLGRIND_START_INSTRUMENTATION; std::shared_ptr<Query> q = query_UsedTo(nonParallelConfig); int counter=0; while(q->next()) { counter++; } if(counter != count_UsedTo) { throw "Invalid count for N0, was " + std::to_string(counter) + " but should have been " + std::to_string(count_UsedTo); } CALLGRIND_STOP_INSTRUMENTATION; } #define COUNT_BENCH(group, idx) \ BENCHMARK_F(group, Thread_##idx, GUMFixture, 0, 0) \ { \ CALLGRIND_START_INSTRUMENTATION;\ std::shared_ptr<Query> q = query_##group(threadConfigs[idx]);\ int counter=0; \ while(q->next()) { \ counter++; \ } \ if(counter != count_##group)\ {\ throw "Invalid count for Thread_" #idx ", was " + std::to_string(counter) + " but should have been " + std::to_string(count_##group);\ }\ CALLGRIND_STOP_INSTRUMENTATION;\ } COUNT_BENCH(PosDepPos, 1) COUNT_BENCH(PosDepPos, 2) COUNT_BENCH(PosDepPos, 3) COUNT_BENCH(PosDepPos, 4) COUNT_BENCH(PosDepPos, 5) COUNT_BENCH(PosDepPos, 6) COUNT_BENCH(PosDepPos, 7) COUNT_BENCH(PosDepPos, 8) COUNT_BENCH(PosDepPos, 9) COUNT_BENCH(PosDepPos, 10) COUNT_BENCH(PosDepPos, 11) COUNT_BENCH(PosDepPos, 12) COUNT_BENCH(UsedTo, 1) COUNT_BENCH(UsedTo, 2) COUNT_BENCH(UsedTo, 3) COUNT_BENCH(UsedTo, 4) COUNT_BENCH(UsedTo, 5) COUNT_BENCH(UsedTo, 6) COUNT_BENCH(UsedTo, 7) COUNT_BENCH(UsedTo, 8) COUNT_BENCH(UsedTo, 9) COUNT_BENCH(UsedTo, 10) COUNT_BENCH(UsedTo, 11) COUNT_BENCH(UsedTo, 12) BASELINE(CreateThreadPool, N1, 0, 0) { ThreadPool t(1); } BENCHMARK(CreateThreadPool, N2, 0, 0) { ThreadPool t(2); } BENCHMARK(CreateThreadPool, N3, 0, 0) { ThreadPool t(3); } BENCHMARK(CreateThreadPool, N4, 0, 0) { ThreadPool t(4); } BENCHMARK(CreateThreadPool, N5, 0, 0) { ThreadPool t(5); } BENCHMARK(CreateThreadPool, N6, 0, 0) { ThreadPool t(6); } BENCHMARK(CreateThreadPool, N7, 0, 0) { ThreadPool t(7); } BENCHMARK(CreateThreadPool, N8, 0, 0) { ThreadPool t(8); } BASELINE(MatchQueue, Vector, 0, 0) { std::list<std::vector<Match>> queue; for(int i=0; i < 1000; i++) { std::vector<Match> m(2); queue.emplace_back(m); } std::vector<Match> m; while(!queue.empty()) { m = queue.front(); queue.pop_front(); } } BENCHMARK(MatchQueue, VectorMove, 0, 0) { std::list<std::vector<Match>> queue; for(int i=0; i < 1000; i++) { std::vector<Match> m(2); queue.emplace_back(m); } std::vector<Match> m; while(!queue.empty()) { m = std::move(queue.front()); queue.pop_front(); } } BENCHMARK(MatchQueue, VectorMoveDeque, 0, 0) { std::deque<std::vector<Match>> queue; for(int i=0; i < 1000; i++) { std::vector<Match> m(2); queue.emplace_back(m); } std::vector<Match> m; while(!queue.empty()) { m = std::move(queue.front()); queue.pop_front(); } } BENCHMARK(MatchQueue, VectorSwap, 0, 0) { std::list<std::vector<Match>> queue; for(int i=0; i < 1000; i++) { std::vector<Match> m(2); queue.emplace_back(m); } std::vector<Match> m; while(!queue.empty()) { m.swap(queue.front()); queue.pop_front(); } } BENCHMARK(MatchQueue, VectorSwapDeque, 0, 0) { std::deque<std::vector<Match>> queue; for(int i=0; i < 1000; i++) { std::vector<Match> m(2); queue.emplace_back(m); } std::vector<Match> m; while(!queue.empty()) { m.swap(queue.front()); queue.pop_front(); } } BENCHMARK(MatchQueue, Deque, 0, 0) { std::list<std::deque<Match>> queue; for(int i=0; i < 1000; i++) { std::deque<Match> m(2); queue.emplace_back(m); } std::deque<Match> m; while(!queue.empty()) { m = std::move(queue.front()); queue.pop_front(); } } BENCHMARK(MatchQueue, DequeSwap, 0, 0) { std::list<std::deque<Match>> queue; for(int i=0; i < 1000; i++) { std::deque<Match> m(2); queue.emplace_back(m); } std::deque<Match> m; while(!queue.empty()) { m.swap(queue.front()); queue.pop_front(); } } BENCHMARK(MatchQueue, DequeSwapDeque, 0, 0) { std::deque<std::deque<Match>> queue; for(int i=0; i < 1000; i++) { std::deque<Match> m(2); queue.emplace_back(m); } std::deque<Match> m; while(!queue.empty()) { m.swap(queue.front()); queue.pop_front(); } } BENCHMARK(MatchQueue, List, 0, 0) { std::list<std::list<Match>> queue; for(int i=0; i < 1000; i++) { std::list<Match> m(2); queue.emplace_back(m); } std::list<Match> m; while(!queue.empty()) { m = std::move(queue.front()); queue.pop_front(); } } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkInterpolateDataSetAttributes.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen. This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen. The following terms apply to all files associated with the software unless explicitly disclaimed in individual files. This copyright specifically does not apply to the related textbook "The Visualization Toolkit" ISBN 013199837-4 published by Prentice Hall which is covered by its own copyright. The authors hereby grant permission to use, copy, and distribute this software and its documentation for any purpose, provided that existing copyright notices are retained in all copies and that this notice is included verbatim in any distributions. Additionally, the authors grant permission to modify this software and its documentation for any purpose, provided that such modifications are not distributed without the explicit consent of the authors and that existing copyright notices are retained in all copies. Some of the algorithms implemented by this software are patented, observe all applicable patent law. IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. =========================================================================*/ #include "vtkInterpolateDataSetAttributes.h" #include "vtkPolyData.h" #include "vtkStructuredGrid.h" #include "vtkStructuredPoints.h" #include "vtkUnstructuredGrid.h" #include "vtkRectilinearGrid.h" // Create object with no input or output. vtkInterpolateDataSetAttributes::vtkInterpolateDataSetAttributes() { this->InputList = vtkDataSetCollection::New(); this->T = 0.0; this->PolyData = vtkPolyData::New(); this->PolyData->SetSource(this); this->StructuredPoints = vtkStructuredPoints::New(); this->StructuredPoints->SetSource(this); this->StructuredGrid = vtkStructuredGrid::New(); this->StructuredGrid->SetSource(this); this->UnstructuredGrid = vtkUnstructuredGrid::New(); this->UnstructuredGrid->SetSource(this); this->RectilinearGrid = vtkRectilinearGrid::New(); this->RectilinearGrid->SetSource(this); } vtkInterpolateDataSetAttributes::~vtkInterpolateDataSetAttributes() { this->InputList->Delete(); this->InputList = NULL; this->PolyData->Delete(); this->StructuredPoints->Delete(); this->StructuredGrid->Delete(); this->UnstructuredGrid->Delete(); this->RectilinearGrid->Delete(); // Output should only be one of the above. We set it to NULL // so that we don't free it twice this->Output = NULL; } // Add a dataset to the list of data to interpolate. void vtkInterpolateDataSetAttributes::AddInput(vtkDataSet *ds) { if ( ds != NULL && ! this->InputList->IsItemPresent(ds) ) { vtkDebugMacro(<<" setting Input to " << (void *)ds); this->Modified(); this->InputList->AddItem(ds); if ( ds->GetDataSetType() == VTK_POLY_DATA ) { this->Output = this->PolyData; } else if ( ds->GetDataSetType() == VTK_STRUCTURED_POINTS ) { this->Output = this->StructuredPoints; } else if ( ds->GetDataSetType() == VTK_STRUCTURED_GRID ) { this->Output = this->StructuredGrid; } else if ( ds->GetDataSetType() == VTK_UNSTRUCTURED_GRID ) { this->Output = this->UnstructuredGrid; } else if ( ds->GetDataSetType() == VTK_RECTILINEAR_GRID ) { this->Output = this->RectilinearGrid; } else { vtkErrorMacro(<<"Mismatch in data type"); } } } // Remove a dataset from the list of data to interpolate. void vtkInterpolateDataSetAttributes::RemoveInput(vtkDataSet *ds) { if ( this->InputList->IsItemPresent(ds) ) { this->Modified(); this->InputList->RemoveItem(ds); } } void vtkInterpolateDataSetAttributes::Update() { unsigned long int mtime=0, dsMtime; vtkDataSet *ds; int dataSetType; // make sure input is available if ( this->InputList->GetNumberOfItems() < 2 ) { vtkErrorMacro(<< "Need at least two inputs to interpolate!"); return; } // prevent chasing our tail if (this->Updating) { return; } this->Updating = 1; for (mtime=0, this->InputList->InitTraversal(); (ds = this->InputList->GetNextItem()); ) { if ( mtime == 0 ) //first time { dataSetType = ds->GetDataSetType(); } if ( dataSetType != ds->GetDataSetType() ) { vtkErrorMacro(<<"All input data sets must be of the same type!"); return; } ds->Update(); dsMtime = ds->GetMTime(); if ( dsMtime > mtime ) { mtime = dsMtime; } } this->Updating = 0; if ( mtime > this->ExecuteTime || this->GetMTime() > this->ExecuteTime ) { for (this->InputList->InitTraversal();(ds=this->InputList->GetNextItem());) { if ( ds->GetDataReleased() ) { ds->ForceUpdate(); } } if ( this->StartMethod ) { (*this->StartMethod)(this->StartMethodArg); } this->Output->Initialize(); //clear output // reset AbortExecute flag and Progress this->AbortExecute = 0; this->Progress = 0.0; this->Execute(); this->ExecuteTime.Modified(); if ( !this->AbortExecute ) { this->UpdateProgress(1.0); } this->SetDataReleased(0); if ( this->EndMethod ) { (*this->EndMethod)(this->EndMethodArg); } } for (this->InputList->InitTraversal();(ds = this->InputList->GetNextItem());) { if ( ds->ShouldIReleaseData() ) { ds->ReleaseData(); } } } // Interpolate the data void vtkInterpolateDataSetAttributes::Execute() { int numPts, numCells, numInputs=this->InputList->GetNumberOfItems(); int i, lowDS, highDS; vtkDataSet *ds, *ds2; vtkDataSet *output = this->GetOutput(); vtkPointData *outputPD = output->GetPointData(); vtkCellData *outputCD = output->GetCellData(); vtkPointData *inputPD, *input2PD; vtkCellData *inputCD, *input2CD; float t; vtkDebugMacro(<<"Interpolating data..."); // Check input and determine between which data sets the interpolation // is to occur. if ( this->T > (float)numInputs ) { vtkErrorMacro(<<"Bad interpolation parameter"); return; } lowDS = (int) this->T; if ( lowDS >= (numInputs-1) ) { lowDS = numInputs - 2; } highDS = lowDS + 1; t = this->T - (float)lowDS; ds = this->InputList->GetItem(lowDS); ds2 = this->InputList->GetItem(highDS); numPts = ds->GetNumberOfPoints(); numCells = ds->GetNumberOfCells(); if ( numPts != ds2->GetNumberOfPoints() || numCells != ds2->GetNumberOfCells() ) { vtkErrorMacro(<<"Data sets not consistent!"); return; } output->CopyStructure(ds); inputPD = ds->GetPointData(); inputCD = ds->GetCellData(); input2PD = ds2->GetPointData(); input2CD = ds2->GetCellData(); // Allocate the data set attributes outputPD->CopyAllOff(); if ( inputPD->GetScalars() && input2PD->GetScalars() ) { outputPD->CopyScalarsOn(); } if ( inputPD->GetVectors() && input2PD->GetVectors() ) { outputPD->CopyVectorsOn(); } if ( inputPD->GetNormals() && input2PD->GetNormals() ) { outputPD->CopyNormalsOn(); } if ( inputPD->GetTCoords() && input2PD->GetTCoords() ) { outputPD->CopyTCoordsOn(); } if ( inputPD->GetTensors() && input2PD->GetTensors() ) { outputPD->CopyTensorsOn(); } if ( inputPD->GetFieldData() && input2PD->GetFieldData() ) { outputPD->CopyFieldDataOn(); } outputPD->InterpolateAllocate(inputPD); outputCD->CopyAllOff(); if ( inputCD->GetScalars() && input2CD->GetScalars() ) { outputCD->CopyScalarsOn(); } if ( inputCD->GetVectors() && input2CD->GetVectors() ) { outputCD->CopyVectorsOn(); } if ( inputCD->GetNormals() && input2CD->GetNormals() ) { outputCD->CopyNormalsOn(); } if ( inputCD->GetTCoords() && input2CD->GetTCoords() ) { outputCD->CopyTCoordsOn(); } if ( inputCD->GetTensors() && input2CD->GetTensors() ) { outputCD->CopyTensorsOn(); } if ( inputCD->GetFieldData() && input2CD->GetFieldData() ) { outputCD->CopyFieldDataOn(); } outputCD->InterpolateAllocate(inputCD); // Interpolate point data. We'll assume that it takes 50% of the time for ( i=0; i < numPts; i++ ) { if ( ! (i % 10000) ) { this->UpdateProgress ((float)i/numPts * 0.50); if (this->GetAbortExecute()) break; } outputPD->InterpolateTime(inputPD, input2PD, i, t); } // Interpolate cell data. We'll assume that it takes 50% of the time for ( i=0; i < numCells; i++ ) { if ( ! (i % 10000) ) { this->UpdateProgress (0.5 + (float)i/numCells * 0.50); if (this->GetAbortExecute()) break; } outputCD->InterpolateTime(inputCD, input2CD, i, t); } } // Get the output as vtkPolyData. vtkPolyData *vtkInterpolateDataSetAttributes::GetPolyDataOutput() { return this->PolyData; } // Get the output as vtkStructuredPoints. vtkStructuredPoints *vtkInterpolateDataSetAttributes::GetStructuredPointsOutput() { return this->StructuredPoints; } // Get the output as vtkStructuredGrid. vtkStructuredGrid *vtkInterpolateDataSetAttributes::GetStructuredGridOutput() { return this->StructuredGrid; } // Get the output as vtkUnstructuredGrid. vtkUnstructuredGrid *vtkInterpolateDataSetAttributes::GetUnstructuredGridOutput() { return this->UnstructuredGrid; } // Get the output as vtkRectilinearGrid. vtkRectilinearGrid *vtkInterpolateDataSetAttributes::GetRectilinearGridOutput() { return this->RectilinearGrid; } void vtkInterpolateDataSetAttributes::PrintSelf(ostream& os, vtkIndent indent) { vtkFilter::PrintSelf(os,indent); os << indent << "Input Data Sets:\n"; this->InputList->PrintSelf(os,indent.GetNextIndent()); os << indent << "T: " << this->T << endl; } <commit_msg>ENH: check that interpolation parameter is <= 1.0.<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkInterpolateDataSetAttributes.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen. This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen. The following terms apply to all files associated with the software unless explicitly disclaimed in individual files. This copyright specifically does not apply to the related textbook "The Visualization Toolkit" ISBN 013199837-4 published by Prentice Hall which is covered by its own copyright. The authors hereby grant permission to use, copy, and distribute this software and its documentation for any purpose, provided that existing copyright notices are retained in all copies and that this notice is included verbatim in any distributions. Additionally, the authors grant permission to modify this software and its documentation for any purpose, provided that such modifications are not distributed without the explicit consent of the authors and that existing copyright notices are retained in all copies. Some of the algorithms implemented by this software are patented, observe all applicable patent law. IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. =========================================================================*/ #include "vtkInterpolateDataSetAttributes.h" #include "vtkPolyData.h" #include "vtkStructuredGrid.h" #include "vtkStructuredPoints.h" #include "vtkUnstructuredGrid.h" #include "vtkRectilinearGrid.h" // Create object with no input or output. vtkInterpolateDataSetAttributes::vtkInterpolateDataSetAttributes() { this->InputList = vtkDataSetCollection::New(); this->T = 0.0; this->PolyData = vtkPolyData::New(); this->PolyData->SetSource(this); this->StructuredPoints = vtkStructuredPoints::New(); this->StructuredPoints->SetSource(this); this->StructuredGrid = vtkStructuredGrid::New(); this->StructuredGrid->SetSource(this); this->UnstructuredGrid = vtkUnstructuredGrid::New(); this->UnstructuredGrid->SetSource(this); this->RectilinearGrid = vtkRectilinearGrid::New(); this->RectilinearGrid->SetSource(this); } vtkInterpolateDataSetAttributes::~vtkInterpolateDataSetAttributes() { this->InputList->Delete(); this->InputList = NULL; this->PolyData->Delete(); this->StructuredPoints->Delete(); this->StructuredGrid->Delete(); this->UnstructuredGrid->Delete(); this->RectilinearGrid->Delete(); // Output should only be one of the above. We set it to NULL // so that we don't free it twice this->Output = NULL; } // Add a dataset to the list of data to interpolate. void vtkInterpolateDataSetAttributes::AddInput(vtkDataSet *ds) { if ( ds != NULL && ! this->InputList->IsItemPresent(ds) ) { vtkDebugMacro(<<" setting Input to " << (void *)ds); this->Modified(); this->InputList->AddItem(ds); if ( ds->GetDataSetType() == VTK_POLY_DATA ) { this->Output = this->PolyData; } else if ( ds->GetDataSetType() == VTK_STRUCTURED_POINTS ) { this->Output = this->StructuredPoints; } else if ( ds->GetDataSetType() == VTK_STRUCTURED_GRID ) { this->Output = this->StructuredGrid; } else if ( ds->GetDataSetType() == VTK_UNSTRUCTURED_GRID ) { this->Output = this->UnstructuredGrid; } else if ( ds->GetDataSetType() == VTK_RECTILINEAR_GRID ) { this->Output = this->RectilinearGrid; } else { vtkErrorMacro(<<"Mismatch in data type"); } } } // Remove a dataset from the list of data to interpolate. void vtkInterpolateDataSetAttributes::RemoveInput(vtkDataSet *ds) { if ( this->InputList->IsItemPresent(ds) ) { this->Modified(); this->InputList->RemoveItem(ds); } } void vtkInterpolateDataSetAttributes::Update() { unsigned long int mtime=0, dsMtime; vtkDataSet *ds; int dataSetType; // make sure input is available if ( this->InputList->GetNumberOfItems() < 2 ) { vtkErrorMacro(<< "Need at least two inputs to interpolate!"); return; } // prevent chasing our tail if (this->Updating) { return; } this->Updating = 1; for (mtime=0, this->InputList->InitTraversal(); (ds = this->InputList->GetNextItem()); ) { if ( mtime == 0 ) //first time { dataSetType = ds->GetDataSetType(); } if ( dataSetType != ds->GetDataSetType() ) { vtkErrorMacro(<<"All input data sets must be of the same type!"); return; } ds->Update(); dsMtime = ds->GetMTime(); if ( dsMtime > mtime ) { mtime = dsMtime; } } this->Updating = 0; if ( mtime > this->ExecuteTime || this->GetMTime() > this->ExecuteTime ) { for (this->InputList->InitTraversal();(ds=this->InputList->GetNextItem());) { if ( ds->GetDataReleased() ) { ds->ForceUpdate(); } } if ( this->StartMethod ) { (*this->StartMethod)(this->StartMethodArg); } this->Output->Initialize(); //clear output // reset AbortExecute flag and Progress this->AbortExecute = 0; this->Progress = 0.0; this->Execute(); this->ExecuteTime.Modified(); if ( !this->AbortExecute ) { this->UpdateProgress(1.0); } this->SetDataReleased(0); if ( this->EndMethod ) { (*this->EndMethod)(this->EndMethodArg); } } for (this->InputList->InitTraversal();(ds = this->InputList->GetNextItem());) { if ( ds->ShouldIReleaseData() ) { ds->ReleaseData(); } } } // Interpolate the data void vtkInterpolateDataSetAttributes::Execute() { int numPts, numCells, numInputs=this->InputList->GetNumberOfItems(); int i, lowDS, highDS; vtkDataSet *ds, *ds2; vtkDataSet *output = this->GetOutput(); vtkPointData *outputPD = output->GetPointData(); vtkCellData *outputCD = output->GetCellData(); vtkPointData *inputPD, *input2PD; vtkCellData *inputCD, *input2CD; float t; vtkDebugMacro(<<"Interpolating data..."); // Check input and determine between which data sets the interpolation // is to occur. if ( this->T > (float)numInputs ) { vtkErrorMacro(<<"Bad interpolation parameter"); return; } lowDS = (int) this->T; if ( lowDS >= (numInputs-1) ) { lowDS = numInputs - 2; } highDS = lowDS + 1; t = this->T - (float)lowDS; if (t > 1.0) t =1.0; ds = this->InputList->GetItem(lowDS); ds2 = this->InputList->GetItem(highDS); numPts = ds->GetNumberOfPoints(); numCells = ds->GetNumberOfCells(); if ( numPts != ds2->GetNumberOfPoints() || numCells != ds2->GetNumberOfCells() ) { vtkErrorMacro(<<"Data sets not consistent!"); return; } output->CopyStructure(ds); inputPD = ds->GetPointData(); inputCD = ds->GetCellData(); input2PD = ds2->GetPointData(); input2CD = ds2->GetCellData(); // Allocate the data set attributes outputPD->CopyAllOff(); if ( inputPD->GetScalars() && input2PD->GetScalars() ) { outputPD->CopyScalarsOn(); } if ( inputPD->GetVectors() && input2PD->GetVectors() ) { outputPD->CopyVectorsOn(); } if ( inputPD->GetNormals() && input2PD->GetNormals() ) { outputPD->CopyNormalsOn(); } if ( inputPD->GetTCoords() && input2PD->GetTCoords() ) { outputPD->CopyTCoordsOn(); } if ( inputPD->GetTensors() && input2PD->GetTensors() ) { outputPD->CopyTensorsOn(); } if ( inputPD->GetFieldData() && input2PD->GetFieldData() ) { outputPD->CopyFieldDataOn(); } outputPD->InterpolateAllocate(inputPD); outputCD->CopyAllOff(); if ( inputCD->GetScalars() && input2CD->GetScalars() ) { outputCD->CopyScalarsOn(); } if ( inputCD->GetVectors() && input2CD->GetVectors() ) { outputCD->CopyVectorsOn(); } if ( inputCD->GetNormals() && input2CD->GetNormals() ) { outputCD->CopyNormalsOn(); } if ( inputCD->GetTCoords() && input2CD->GetTCoords() ) { outputCD->CopyTCoordsOn(); } if ( inputCD->GetTensors() && input2CD->GetTensors() ) { outputCD->CopyTensorsOn(); } if ( inputCD->GetFieldData() && input2CD->GetFieldData() ) { outputCD->CopyFieldDataOn(); } outputCD->InterpolateAllocate(inputCD); // Interpolate point data. We'll assume that it takes 50% of the time for ( i=0; i < numPts; i++ ) { if ( ! (i % 10000) ) { this->UpdateProgress ((float)i/numPts * 0.50); if (this->GetAbortExecute()) break; } outputPD->InterpolateTime(inputPD, input2PD, i, t); } // Interpolate cell data. We'll assume that it takes 50% of the time for ( i=0; i < numCells; i++ ) { if ( ! (i % 10000) ) { this->UpdateProgress (0.5 + (float)i/numCells * 0.50); if (this->GetAbortExecute()) break; } outputCD->InterpolateTime(inputCD, input2CD, i, t); } } // Get the output as vtkPolyData. vtkPolyData *vtkInterpolateDataSetAttributes::GetPolyDataOutput() { return this->PolyData; } // Get the output as vtkStructuredPoints. vtkStructuredPoints *vtkInterpolateDataSetAttributes::GetStructuredPointsOutput() { return this->StructuredPoints; } // Get the output as vtkStructuredGrid. vtkStructuredGrid *vtkInterpolateDataSetAttributes::GetStructuredGridOutput() { return this->StructuredGrid; } // Get the output as vtkUnstructuredGrid. vtkUnstructuredGrid *vtkInterpolateDataSetAttributes::GetUnstructuredGridOutput() { return this->UnstructuredGrid; } // Get the output as vtkRectilinearGrid. vtkRectilinearGrid *vtkInterpolateDataSetAttributes::GetRectilinearGridOutput() { return this->RectilinearGrid; } void vtkInterpolateDataSetAttributes::PrintSelf(ostream& os, vtkIndent indent) { vtkFilter::PrintSelf(os,indent); os << indent << "Input Data Sets:\n"; this->InputList->PrintSelf(os,indent.GetNextIndent()); os << indent << "T: " << this->T << endl; } <|endoftext|>
<commit_before>//===-- TargetLowering.cpp - Implement the TargetLowering class -----------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This implements the TargetLowering class. // //===----------------------------------------------------------------------===// #include "llvm/Target/TargetLowering.h" #include "llvm/Target/TargetMachine.h" #include "llvm/CodeGen/SelectionDAG.h" using namespace llvm; TargetLowering::TargetLowering(TargetMachine &tm) : TM(tm), TD(TM.getTargetData()), ValueTypeActions(0) { assert(ISD::BUILTIN_OP_END <= 128 && "Fixed size array in TargetLowering is not large enough!"); // All operations default to being supported. memset(OpActions, 0, sizeof(OpActions)); IsLittleEndian = TD.isLittleEndian(); ShiftAmountTy = SetCCResultTy = PointerTy = getValueType(TD.getIntPtrType()); ShiftAmtHandling = Undefined; memset(RegClassForVT, 0,MVT::LAST_VALUETYPE*sizeof(TargetRegisterClass*)); maxStoresPerMemSet = maxStoresPerMemCpy = maxStoresPerMemMove = 8; allowUnalignedMemoryAccesses = false; UseUnderscoreSetJmpLongJmp = false; IntDivIsCheap = false; Pow2DivIsCheap = false; SchedPreferenceInfo = SchedulingForLatency; } TargetLowering::~TargetLowering() {} /// setValueTypeAction - Set the action for a particular value type. This /// assumes an action has not already been set for this value type. static void SetValueTypeAction(MVT::ValueType VT, TargetLowering::LegalizeAction Action, TargetLowering &TLI, MVT::ValueType *TransformToType, unsigned long long &ValueTypeActions) { ValueTypeActions |= (unsigned long long)Action << (VT*2); if (Action == TargetLowering::Promote) { MVT::ValueType PromoteTo; if (VT == MVT::f32) PromoteTo = MVT::f64; else { unsigned LargerReg = VT+1; while (!TLI.isTypeLegal((MVT::ValueType)LargerReg)) { ++LargerReg; assert(MVT::isInteger((MVT::ValueType)LargerReg) && "Nothing to promote to??"); } PromoteTo = (MVT::ValueType)LargerReg; } assert(MVT::isInteger(VT) == MVT::isInteger(PromoteTo) && MVT::isFloatingPoint(VT) == MVT::isFloatingPoint(PromoteTo) && "Can only promote from int->int or fp->fp!"); assert(VT < PromoteTo && "Must promote to a larger type!"); TransformToType[VT] = PromoteTo; } else if (Action == TargetLowering::Expand) { assert((VT == MVT::Vector || MVT::isInteger(VT)) && VT > MVT::i8 && "Cannot expand this type: target must support SOME integer reg!"); // Expand to the next smaller integer type! TransformToType[VT] = (MVT::ValueType)(VT-1); } } /// computeRegisterProperties - Once all of the register classes are added, /// this allows us to compute derived properties we expose. void TargetLowering::computeRegisterProperties() { assert(MVT::LAST_VALUETYPE <= 32 && "Too many value types for ValueTypeActions to hold!"); // Everything defaults to one. for (unsigned i = 0; i != MVT::LAST_VALUETYPE; ++i) NumElementsForVT[i] = 1; // Find the largest integer register class. unsigned LargestIntReg = MVT::i128; for (; RegClassForVT[LargestIntReg] == 0; --LargestIntReg) assert(LargestIntReg != MVT::i1 && "No integer registers defined!"); // Every integer value type larger than this largest register takes twice as // many registers to represent as the previous ValueType. unsigned ExpandedReg = LargestIntReg; ++LargestIntReg; for (++ExpandedReg; MVT::isInteger((MVT::ValueType)ExpandedReg);++ExpandedReg) NumElementsForVT[ExpandedReg] = 2*NumElementsForVT[ExpandedReg-1]; // Inspect all of the ValueType's possible, deciding how to process them. for (unsigned IntReg = MVT::i1; IntReg <= MVT::i128; ++IntReg) // If we are expanding this type, expand it! if (getNumElements((MVT::ValueType)IntReg) != 1) SetValueTypeAction((MVT::ValueType)IntReg, Expand, *this, TransformToType, ValueTypeActions); else if (!isTypeLegal((MVT::ValueType)IntReg)) // Otherwise, if we don't have native support, we must promote to a // larger type. SetValueTypeAction((MVT::ValueType)IntReg, Promote, *this, TransformToType, ValueTypeActions); else TransformToType[(MVT::ValueType)IntReg] = (MVT::ValueType)IntReg; // If the target does not have native support for F32, promote it to F64. if (!isTypeLegal(MVT::f32)) SetValueTypeAction(MVT::f32, Promote, *this, TransformToType, ValueTypeActions); else TransformToType[MVT::f32] = MVT::f32; // Set MVT::Vector to always be Expanded SetValueTypeAction(MVT::Vector, Expand, *this, TransformToType, ValueTypeActions); assert(isTypeLegal(MVT::f64) && "Target does not support FP?"); TransformToType[MVT::f64] = MVT::f64; } const char *TargetLowering::getTargetNodeName(unsigned Opcode) const { return NULL; } bool TargetLowering::isMaskedValueZeroForTargetNode(const SDOperand &Op, uint64_t Mask) const { return false; } <commit_msg>initialize an instance var, apparently I forgot to commit this long ago<commit_after>//===-- TargetLowering.cpp - Implement the TargetLowering class -----------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This implements the TargetLowering class. // //===----------------------------------------------------------------------===// #include "llvm/Target/TargetLowering.h" #include "llvm/Target/TargetMachine.h" #include "llvm/CodeGen/SelectionDAG.h" using namespace llvm; TargetLowering::TargetLowering(TargetMachine &tm) : TM(tm), TD(TM.getTargetData()), ValueTypeActions(0) { assert(ISD::BUILTIN_OP_END <= 128 && "Fixed size array in TargetLowering is not large enough!"); // All operations default to being supported. memset(OpActions, 0, sizeof(OpActions)); IsLittleEndian = TD.isLittleEndian(); ShiftAmountTy = SetCCResultTy = PointerTy = getValueType(TD.getIntPtrType()); ShiftAmtHandling = Undefined; memset(RegClassForVT, 0,MVT::LAST_VALUETYPE*sizeof(TargetRegisterClass*)); maxStoresPerMemSet = maxStoresPerMemCpy = maxStoresPerMemMove = 8; allowUnalignedMemoryAccesses = false; UseUnderscoreSetJmpLongJmp = false; IntDivIsCheap = false; Pow2DivIsCheap = false; StackPointerRegisterToSaveRestore = 0; SchedPreferenceInfo = SchedulingForLatency; } TargetLowering::~TargetLowering() {} /// setValueTypeAction - Set the action for a particular value type. This /// assumes an action has not already been set for this value type. static void SetValueTypeAction(MVT::ValueType VT, TargetLowering::LegalizeAction Action, TargetLowering &TLI, MVT::ValueType *TransformToType, unsigned long long &ValueTypeActions) { ValueTypeActions |= (unsigned long long)Action << (VT*2); if (Action == TargetLowering::Promote) { MVT::ValueType PromoteTo; if (VT == MVT::f32) PromoteTo = MVT::f64; else { unsigned LargerReg = VT+1; while (!TLI.isTypeLegal((MVT::ValueType)LargerReg)) { ++LargerReg; assert(MVT::isInteger((MVT::ValueType)LargerReg) && "Nothing to promote to??"); } PromoteTo = (MVT::ValueType)LargerReg; } assert(MVT::isInteger(VT) == MVT::isInteger(PromoteTo) && MVT::isFloatingPoint(VT) == MVT::isFloatingPoint(PromoteTo) && "Can only promote from int->int or fp->fp!"); assert(VT < PromoteTo && "Must promote to a larger type!"); TransformToType[VT] = PromoteTo; } else if (Action == TargetLowering::Expand) { assert((VT == MVT::Vector || MVT::isInteger(VT)) && VT > MVT::i8 && "Cannot expand this type: target must support SOME integer reg!"); // Expand to the next smaller integer type! TransformToType[VT] = (MVT::ValueType)(VT-1); } } /// computeRegisterProperties - Once all of the register classes are added, /// this allows us to compute derived properties we expose. void TargetLowering::computeRegisterProperties() { assert(MVT::LAST_VALUETYPE <= 32 && "Too many value types for ValueTypeActions to hold!"); // Everything defaults to one. for (unsigned i = 0; i != MVT::LAST_VALUETYPE; ++i) NumElementsForVT[i] = 1; // Find the largest integer register class. unsigned LargestIntReg = MVT::i128; for (; RegClassForVT[LargestIntReg] == 0; --LargestIntReg) assert(LargestIntReg != MVT::i1 && "No integer registers defined!"); // Every integer value type larger than this largest register takes twice as // many registers to represent as the previous ValueType. unsigned ExpandedReg = LargestIntReg; ++LargestIntReg; for (++ExpandedReg; MVT::isInteger((MVT::ValueType)ExpandedReg);++ExpandedReg) NumElementsForVT[ExpandedReg] = 2*NumElementsForVT[ExpandedReg-1]; // Inspect all of the ValueType's possible, deciding how to process them. for (unsigned IntReg = MVT::i1; IntReg <= MVT::i128; ++IntReg) // If we are expanding this type, expand it! if (getNumElements((MVT::ValueType)IntReg) != 1) SetValueTypeAction((MVT::ValueType)IntReg, Expand, *this, TransformToType, ValueTypeActions); else if (!isTypeLegal((MVT::ValueType)IntReg)) // Otherwise, if we don't have native support, we must promote to a // larger type. SetValueTypeAction((MVT::ValueType)IntReg, Promote, *this, TransformToType, ValueTypeActions); else TransformToType[(MVT::ValueType)IntReg] = (MVT::ValueType)IntReg; // If the target does not have native support for F32, promote it to F64. if (!isTypeLegal(MVT::f32)) SetValueTypeAction(MVT::f32, Promote, *this, TransformToType, ValueTypeActions); else TransformToType[MVT::f32] = MVT::f32; // Set MVT::Vector to always be Expanded SetValueTypeAction(MVT::Vector, Expand, *this, TransformToType, ValueTypeActions); assert(isTypeLegal(MVT::f64) && "Target does not support FP?"); TransformToType[MVT::f64] = MVT::f64; } const char *TargetLowering::getTargetNodeName(unsigned Opcode) const { return NULL; } bool TargetLowering::isMaskedValueZeroForTargetNode(const SDOperand &Op, uint64_t Mask) const { return false; } <|endoftext|>
<commit_before>//===- SerializedDiagnosticReader.cpp - Reads diagnostics -----------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "clang/Frontend/SerializedDiagnosticReader.h" #include "clang/Basic/FileManager.h" #include "clang/Basic/FileSystemOptions.h" #include "clang/Frontend/SerializedDiagnostics.h" #include "llvm/ADT/Optional.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringRef.h" #include "llvm/Bitstream/BitCodes.h" #include "llvm/Bitstream/BitstreamReader.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/ErrorOr.h" #include "llvm/Support/ManagedStatic.h" #include <cstdint> #include <system_error> using namespace clang; using namespace serialized_diags; std::error_code SerializedDiagnosticReader::readDiagnostics(StringRef File) { // Open the diagnostics file. FileSystemOptions FO; FileManager FileMgr(FO); auto Buffer = FileMgr.getBufferForFile(File); if (!Buffer) return SDError::CouldNotLoad; llvm::BitstreamCursor Stream(**Buffer); Optional<llvm::BitstreamBlockInfo> BlockInfo; if (Stream.AtEndOfStream()) return SDError::InvalidSignature; // Sniff for the signature. for (unsigned char C : {'D', 'I', 'A', 'G'}) { if (Expected<llvm::SimpleBitstreamCursor::word_t> Res = Stream.Read(8)) { if (Res.get() == C) continue; } else { // FIXME this drops the error on the floor. consumeError(Res.takeError()); } return SDError::InvalidSignature; } // Read the top level blocks. while (!Stream.AtEndOfStream()) { if (Expected<unsigned> Res = Stream.ReadCode()) { if (Res.get() != llvm::bitc::ENTER_SUBBLOCK) return SDError::InvalidDiagnostics; } else { // FIXME this drops the error on the floor. consumeError(Res.takeError()); return SDError::InvalidDiagnostics; } std::error_code EC; Expected<unsigned> MaybeSubBlockID = Stream.ReadSubBlockID(); if (!MaybeSubBlockID) { // FIXME this drops the error on the floor. consumeError(MaybeSubBlockID.takeError()); return SDError::InvalidDiagnostics; } switch (MaybeSubBlockID.get()) { case llvm::bitc::BLOCKINFO_BLOCK_ID: { Expected<Optional<llvm::BitstreamBlockInfo>> MaybeBlockInfo = Stream.ReadBlockInfoBlock(); if (!MaybeBlockInfo) { // FIXME this drops the error on the floor. consumeError(MaybeBlockInfo.takeError()); return SDError::InvalidDiagnostics; } BlockInfo = std::move(MaybeBlockInfo.get()); } if (!BlockInfo) return SDError::MalformedBlockInfoBlock; Stream.setBlockInfo(&*BlockInfo); continue; case BLOCK_META: if ((EC = readMetaBlock(Stream))) return EC; continue; case BLOCK_DIAG: if ((EC = readDiagnosticBlock(Stream))) return EC; continue; default: if (llvm::Error Err = Stream.SkipBlock()) { // FIXME this drops the error on the floor. consumeError(std::move(Err)); return SDError::MalformedTopLevelBlock; } continue; } } return {}; } enum class SerializedDiagnosticReader::Cursor { Record = 1, BlockEnd, BlockBegin }; llvm::ErrorOr<SerializedDiagnosticReader::Cursor> SerializedDiagnosticReader::skipUntilRecordOrBlock( llvm::BitstreamCursor &Stream, unsigned &BlockOrRecordID) { BlockOrRecordID = 0; while (!Stream.AtEndOfStream()) { unsigned Code; if (Expected<unsigned> Res = Stream.ReadCode()) Code = Res.get(); else return llvm::errorToErrorCode(Res.takeError()); switch ((llvm::bitc::FixedAbbrevIDs)Code) { case llvm::bitc::ENTER_SUBBLOCK: if (Expected<unsigned> Res = Stream.ReadSubBlockID()) BlockOrRecordID = Res.get(); else return llvm::errorToErrorCode(Res.takeError()); return Cursor::BlockBegin; case llvm::bitc::END_BLOCK: if (Stream.ReadBlockEnd()) return SDError::InvalidDiagnostics; return Cursor::BlockEnd; case llvm::bitc::DEFINE_ABBREV: if (llvm::Error Err = Stream.ReadAbbrevRecord()) return llvm::errorToErrorCode(std::move(Err)); continue; case llvm::bitc::UNABBREV_RECORD: return SDError::UnsupportedConstruct; default: // We found a record. BlockOrRecordID = Code; return Cursor::Record; } } return SDError::InvalidDiagnostics; } std::error_code SerializedDiagnosticReader::readMetaBlock(llvm::BitstreamCursor &Stream) { if (llvm::Error Err = Stream.EnterSubBlock(clang::serialized_diags::BLOCK_META)) { // FIXME this drops the error on the floor. consumeError(std::move(Err)); return SDError::MalformedMetadataBlock; } bool VersionChecked = false; while (true) { unsigned BlockOrCode = 0; llvm::ErrorOr<Cursor> Res = skipUntilRecordOrBlock(Stream, BlockOrCode); if (!Res) Res.getError(); switch (Res.get()) { case Cursor::Record: break; case Cursor::BlockBegin: if (llvm::Error Err = Stream.SkipBlock()) { // FIXME this drops the error on the floor. consumeError(std::move(Err)); return SDError::MalformedMetadataBlock; } LLVM_FALLTHROUGH; case Cursor::BlockEnd: if (!VersionChecked) return SDError::MissingVersion; return {}; } SmallVector<uint64_t, 1> Record; Expected<unsigned> MaybeRecordID = Stream.readRecord(BlockOrCode, Record); if (!MaybeRecordID) return errorToErrorCode(MaybeRecordID.takeError()); unsigned RecordID = MaybeRecordID.get(); if (RecordID == RECORD_VERSION) { if (Record.size() < 1) return SDError::MissingVersion; if (Record[0] > VersionNumber) return SDError::VersionMismatch; VersionChecked = true; } } } std::error_code SerializedDiagnosticReader::readDiagnosticBlock(llvm::BitstreamCursor &Stream) { if (llvm::Error Err = Stream.EnterSubBlock(clang::serialized_diags::BLOCK_DIAG)) { // FIXME this drops the error on the floor. consumeError(std::move(Err)); return SDError::MalformedDiagnosticBlock; } std::error_code EC; if ((EC = visitStartOfDiagnostic())) return EC; SmallVector<uint64_t, 16> Record; while (true) { unsigned BlockOrCode = 0; llvm::ErrorOr<Cursor> Res = skipUntilRecordOrBlock(Stream, BlockOrCode); if (!Res) Res.getError(); switch (Res.get()) { case Cursor::BlockBegin: // The only blocks we care about are subdiagnostics. if (BlockOrCode == serialized_diags::BLOCK_DIAG) { if ((EC = readDiagnosticBlock(Stream))) return EC; } else if (llvm::Error Err = Stream.SkipBlock()) { // FIXME this drops the error on the floor. consumeError(std::move(Err)); return SDError::MalformedSubBlock; } continue; case Cursor::BlockEnd: if ((EC = visitEndOfDiagnostic())) return EC; return {}; case Cursor::Record: break; } // Read the record. Record.clear(); StringRef Blob; Expected<unsigned> MaybeRecID = Stream.readRecord(BlockOrCode, Record, &Blob); if (!MaybeRecID) return errorToErrorCode(MaybeRecID.takeError()); unsigned RecID = MaybeRecID.get(); if (RecID < serialized_diags::RECORD_FIRST || RecID > serialized_diags::RECORD_LAST) continue; switch ((RecordIDs)RecID) { case RECORD_CATEGORY: // A category has ID and name size. if (Record.size() != 2) return SDError::MalformedDiagnosticRecord; if ((EC = visitCategoryRecord(Record[0], Blob))) return EC; continue; case RECORD_DIAG: // A diagnostic has severity, location (4), category, flag, and message // size. if (Record.size() != 8) return SDError::MalformedDiagnosticRecord; if ((EC = visitDiagnosticRecord( Record[0], Location(Record[1], Record[2], Record[3], Record[4]), Record[5], Record[6], Blob))) return EC; continue; case RECORD_DIAG_FLAG: // A diagnostic flag has ID and name size. if (Record.size() != 2) return SDError::MalformedDiagnosticRecord; if ((EC = visitDiagFlagRecord(Record[0], Blob))) return EC; continue; case RECORD_FILENAME: // A filename has ID, size, timestamp, and name size. The size and // timestamp are legacy fields that are always zero these days. if (Record.size() != 4) return SDError::MalformedDiagnosticRecord; if ((EC = visitFilenameRecord(Record[0], Record[1], Record[2], Blob))) return EC; continue; case RECORD_FIXIT: // A fixit has two locations (4 each) and message size. if (Record.size() != 9) return SDError::MalformedDiagnosticRecord; if ((EC = visitFixitRecord( Location(Record[0], Record[1], Record[2], Record[3]), Location(Record[4], Record[5], Record[6], Record[7]), Blob))) return EC; continue; case RECORD_SOURCE_RANGE: // A source range is two locations (4 each). if (Record.size() != 8) return SDError::MalformedDiagnosticRecord; if ((EC = visitSourceRangeRecord( Location(Record[0], Record[1], Record[2], Record[3]), Location(Record[4], Record[5], Record[6], Record[7])))) return EC; continue; case RECORD_VERSION: // A version is just a number. if (Record.size() != 1) return SDError::MalformedDiagnosticRecord; if ((EC = visitVersionRecord(Record[0]))) return EC; continue; } } } namespace { class SDErrorCategoryType final : public std::error_category { const char *name() const noexcept override { return "clang.serialized_diags"; } std::string message(int IE) const override { auto E = static_cast<SDError>(IE); switch (E) { case SDError::CouldNotLoad: return "Failed to open diagnostics file"; case SDError::InvalidSignature: return "Invalid diagnostics signature"; case SDError::InvalidDiagnostics: return "Parse error reading diagnostics"; case SDError::MalformedTopLevelBlock: return "Malformed block at top-level of diagnostics"; case SDError::MalformedSubBlock: return "Malformed sub-block in a diagnostic"; case SDError::MalformedBlockInfoBlock: return "Malformed BlockInfo block"; case SDError::MalformedMetadataBlock: return "Malformed Metadata block"; case SDError::MalformedDiagnosticBlock: return "Malformed Diagnostic block"; case SDError::MalformedDiagnosticRecord: return "Malformed Diagnostic record"; case SDError::MissingVersion: return "No version provided in diagnostics"; case SDError::VersionMismatch: return "Unsupported diagnostics version"; case SDError::UnsupportedConstruct: return "Bitcode constructs that are not supported in diagnostics appear"; case SDError::HandlerFailed: return "Generic error occurred while handling a record"; } llvm_unreachable("Unknown error type!"); } }; } // namespace static llvm::ManagedStatic<SDErrorCategoryType> ErrorCategory; const std::error_category &clang::serialized_diags::SDErrorCategory() { return *ErrorCategory; } <commit_msg>Bitstream reader: Fix undefined behavior seen after rL364464<commit_after>//===- SerializedDiagnosticReader.cpp - Reads diagnostics -----------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "clang/Frontend/SerializedDiagnosticReader.h" #include "clang/Basic/FileManager.h" #include "clang/Basic/FileSystemOptions.h" #include "clang/Frontend/SerializedDiagnostics.h" #include "llvm/ADT/Optional.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringRef.h" #include "llvm/Bitstream/BitCodes.h" #include "llvm/Bitstream/BitstreamReader.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/ErrorOr.h" #include "llvm/Support/ManagedStatic.h" #include <cstdint> #include <system_error> using namespace clang; using namespace serialized_diags; std::error_code SerializedDiagnosticReader::readDiagnostics(StringRef File) { // Open the diagnostics file. FileSystemOptions FO; FileManager FileMgr(FO); auto Buffer = FileMgr.getBufferForFile(File); if (!Buffer) return SDError::CouldNotLoad; llvm::BitstreamCursor Stream(**Buffer); Optional<llvm::BitstreamBlockInfo> BlockInfo; if (Stream.AtEndOfStream()) return SDError::InvalidSignature; // Sniff for the signature. for (unsigned char C : {'D', 'I', 'A', 'G'}) { if (Expected<llvm::SimpleBitstreamCursor::word_t> Res = Stream.Read(8)) { if (Res.get() == C) continue; } else { // FIXME this drops the error on the floor. consumeError(Res.takeError()); } return SDError::InvalidSignature; } // Read the top level blocks. while (!Stream.AtEndOfStream()) { if (Expected<unsigned> Res = Stream.ReadCode()) { if (Res.get() != llvm::bitc::ENTER_SUBBLOCK) return SDError::InvalidDiagnostics; } else { // FIXME this drops the error on the floor. consumeError(Res.takeError()); return SDError::InvalidDiagnostics; } std::error_code EC; Expected<unsigned> MaybeSubBlockID = Stream.ReadSubBlockID(); if (!MaybeSubBlockID) { // FIXME this drops the error on the floor. consumeError(MaybeSubBlockID.takeError()); return SDError::InvalidDiagnostics; } switch (MaybeSubBlockID.get()) { case llvm::bitc::BLOCKINFO_BLOCK_ID: { Expected<Optional<llvm::BitstreamBlockInfo>> MaybeBlockInfo = Stream.ReadBlockInfoBlock(); if (!MaybeBlockInfo) { // FIXME this drops the error on the floor. consumeError(MaybeBlockInfo.takeError()); return SDError::InvalidDiagnostics; } BlockInfo = std::move(MaybeBlockInfo.get()); } if (!BlockInfo) return SDError::MalformedBlockInfoBlock; Stream.setBlockInfo(&*BlockInfo); continue; case BLOCK_META: if ((EC = readMetaBlock(Stream))) return EC; continue; case BLOCK_DIAG: if ((EC = readDiagnosticBlock(Stream))) return EC; continue; default: if (llvm::Error Err = Stream.SkipBlock()) { // FIXME this drops the error on the floor. consumeError(std::move(Err)); return SDError::MalformedTopLevelBlock; } continue; } } return {}; } enum class SerializedDiagnosticReader::Cursor { Record = 1, BlockEnd, BlockBegin }; llvm::ErrorOr<SerializedDiagnosticReader::Cursor> SerializedDiagnosticReader::skipUntilRecordOrBlock( llvm::BitstreamCursor &Stream, unsigned &BlockOrRecordID) { BlockOrRecordID = 0; while (!Stream.AtEndOfStream()) { unsigned Code; if (Expected<unsigned> Res = Stream.ReadCode()) Code = Res.get(); else return llvm::errorToErrorCode(Res.takeError()); if (Code >= static_cast<unsigned>(llvm::bitc::FIRST_APPLICATION_ABBREV)) { // We found a record. BlockOrRecordID = Code; return Cursor::Record; } switch (static_cast<llvm::bitc::FixedAbbrevIDs>(Code)) { case llvm::bitc::ENTER_SUBBLOCK: if (Expected<unsigned> Res = Stream.ReadSubBlockID()) BlockOrRecordID = Res.get(); else return llvm::errorToErrorCode(Res.takeError()); return Cursor::BlockBegin; case llvm::bitc::END_BLOCK: if (Stream.ReadBlockEnd()) return SDError::InvalidDiagnostics; return Cursor::BlockEnd; case llvm::bitc::DEFINE_ABBREV: if (llvm::Error Err = Stream.ReadAbbrevRecord()) return llvm::errorToErrorCode(std::move(Err)); continue; case llvm::bitc::UNABBREV_RECORD: return SDError::UnsupportedConstruct; case llvm::bitc::FIRST_APPLICATION_ABBREV: llvm_unreachable("Unexpected abbrev id."); } } return SDError::InvalidDiagnostics; } std::error_code SerializedDiagnosticReader::readMetaBlock(llvm::BitstreamCursor &Stream) { if (llvm::Error Err = Stream.EnterSubBlock(clang::serialized_diags::BLOCK_META)) { // FIXME this drops the error on the floor. consumeError(std::move(Err)); return SDError::MalformedMetadataBlock; } bool VersionChecked = false; while (true) { unsigned BlockOrCode = 0; llvm::ErrorOr<Cursor> Res = skipUntilRecordOrBlock(Stream, BlockOrCode); if (!Res) Res.getError(); switch (Res.get()) { case Cursor::Record: break; case Cursor::BlockBegin: if (llvm::Error Err = Stream.SkipBlock()) { // FIXME this drops the error on the floor. consumeError(std::move(Err)); return SDError::MalformedMetadataBlock; } LLVM_FALLTHROUGH; case Cursor::BlockEnd: if (!VersionChecked) return SDError::MissingVersion; return {}; } SmallVector<uint64_t, 1> Record; Expected<unsigned> MaybeRecordID = Stream.readRecord(BlockOrCode, Record); if (!MaybeRecordID) return errorToErrorCode(MaybeRecordID.takeError()); unsigned RecordID = MaybeRecordID.get(); if (RecordID == RECORD_VERSION) { if (Record.size() < 1) return SDError::MissingVersion; if (Record[0] > VersionNumber) return SDError::VersionMismatch; VersionChecked = true; } } } std::error_code SerializedDiagnosticReader::readDiagnosticBlock(llvm::BitstreamCursor &Stream) { if (llvm::Error Err = Stream.EnterSubBlock(clang::serialized_diags::BLOCK_DIAG)) { // FIXME this drops the error on the floor. consumeError(std::move(Err)); return SDError::MalformedDiagnosticBlock; } std::error_code EC; if ((EC = visitStartOfDiagnostic())) return EC; SmallVector<uint64_t, 16> Record; while (true) { unsigned BlockOrCode = 0; llvm::ErrorOr<Cursor> Res = skipUntilRecordOrBlock(Stream, BlockOrCode); if (!Res) Res.getError(); switch (Res.get()) { case Cursor::BlockBegin: // The only blocks we care about are subdiagnostics. if (BlockOrCode == serialized_diags::BLOCK_DIAG) { if ((EC = readDiagnosticBlock(Stream))) return EC; } else if (llvm::Error Err = Stream.SkipBlock()) { // FIXME this drops the error on the floor. consumeError(std::move(Err)); return SDError::MalformedSubBlock; } continue; case Cursor::BlockEnd: if ((EC = visitEndOfDiagnostic())) return EC; return {}; case Cursor::Record: break; } // Read the record. Record.clear(); StringRef Blob; Expected<unsigned> MaybeRecID = Stream.readRecord(BlockOrCode, Record, &Blob); if (!MaybeRecID) return errorToErrorCode(MaybeRecID.takeError()); unsigned RecID = MaybeRecID.get(); if (RecID < serialized_diags::RECORD_FIRST || RecID > serialized_diags::RECORD_LAST) continue; switch ((RecordIDs)RecID) { case RECORD_CATEGORY: // A category has ID and name size. if (Record.size() != 2) return SDError::MalformedDiagnosticRecord; if ((EC = visitCategoryRecord(Record[0], Blob))) return EC; continue; case RECORD_DIAG: // A diagnostic has severity, location (4), category, flag, and message // size. if (Record.size() != 8) return SDError::MalformedDiagnosticRecord; if ((EC = visitDiagnosticRecord( Record[0], Location(Record[1], Record[2], Record[3], Record[4]), Record[5], Record[6], Blob))) return EC; continue; case RECORD_DIAG_FLAG: // A diagnostic flag has ID and name size. if (Record.size() != 2) return SDError::MalformedDiagnosticRecord; if ((EC = visitDiagFlagRecord(Record[0], Blob))) return EC; continue; case RECORD_FILENAME: // A filename has ID, size, timestamp, and name size. The size and // timestamp are legacy fields that are always zero these days. if (Record.size() != 4) return SDError::MalformedDiagnosticRecord; if ((EC = visitFilenameRecord(Record[0], Record[1], Record[2], Blob))) return EC; continue; case RECORD_FIXIT: // A fixit has two locations (4 each) and message size. if (Record.size() != 9) return SDError::MalformedDiagnosticRecord; if ((EC = visitFixitRecord( Location(Record[0], Record[1], Record[2], Record[3]), Location(Record[4], Record[5], Record[6], Record[7]), Blob))) return EC; continue; case RECORD_SOURCE_RANGE: // A source range is two locations (4 each). if (Record.size() != 8) return SDError::MalformedDiagnosticRecord; if ((EC = visitSourceRangeRecord( Location(Record[0], Record[1], Record[2], Record[3]), Location(Record[4], Record[5], Record[6], Record[7])))) return EC; continue; case RECORD_VERSION: // A version is just a number. if (Record.size() != 1) return SDError::MalformedDiagnosticRecord; if ((EC = visitVersionRecord(Record[0]))) return EC; continue; } } } namespace { class SDErrorCategoryType final : public std::error_category { const char *name() const noexcept override { return "clang.serialized_diags"; } std::string message(int IE) const override { auto E = static_cast<SDError>(IE); switch (E) { case SDError::CouldNotLoad: return "Failed to open diagnostics file"; case SDError::InvalidSignature: return "Invalid diagnostics signature"; case SDError::InvalidDiagnostics: return "Parse error reading diagnostics"; case SDError::MalformedTopLevelBlock: return "Malformed block at top-level of diagnostics"; case SDError::MalformedSubBlock: return "Malformed sub-block in a diagnostic"; case SDError::MalformedBlockInfoBlock: return "Malformed BlockInfo block"; case SDError::MalformedMetadataBlock: return "Malformed Metadata block"; case SDError::MalformedDiagnosticBlock: return "Malformed Diagnostic block"; case SDError::MalformedDiagnosticRecord: return "Malformed Diagnostic record"; case SDError::MissingVersion: return "No version provided in diagnostics"; case SDError::VersionMismatch: return "Unsupported diagnostics version"; case SDError::UnsupportedConstruct: return "Bitcode constructs that are not supported in diagnostics appear"; case SDError::HandlerFailed: return "Generic error occurred while handling a record"; } llvm_unreachable("Unknown error type!"); } }; } // namespace static llvm::ManagedStatic<SDErrorCategoryType> ErrorCategory; const std::error_category &clang::serialized_diags::SDErrorCategory() { return *ErrorCategory; } <|endoftext|>
<commit_before>#include <iostream> #include <string> #include "consoleui.h" using namespace std; const char TAB = '\t'; //efsta lagið ConsoleUI::ConsoleUI() { } void ConsoleUI::WelcomeMenu() { cout << endl; cout << endl; cout << TAB << "--------------------------------------------" << endl; cout << TAB << " Welcome! This program will store or show" << endl; cout << TAB << " famous computer scientists. " << endl; cout << TAB << "--------------------------------------------" << endl; cout << endl; } void ConsoleUI::features() { cout << TAB << "----------------------------------------------------------------------------" << endl; cout << TAB << "The list below shows you all possible features on what you can do." << endl; cout << endl; cout << TAB << "press H to show all options" << endl; //eitthvað svona er sniðgt; cout << TAB << "Press 1 to create a new scientist." << endl; cout << TAB << "Press 2 to list all scientists." << endl; cout << TAB << "Press 3 to search for a scientist." << endl; cout << TAB << "Press Q to quit the program." << endl; cout << TAB << "----------------------------------------------------------------------------" << endl; cout << endl; /* vector<Scientist> temp = service.getScientists(); // testing txt file cout << "\t |Name: " << temp[0].getName() << endl; cout << "\t |Gender: " << temp[0].getGender() << endl; cout << "\t |Born: " << temp[0].getDateOfBirth() << endl; cout << "\t |Died: " << temp[0].getDateOfDeath() << endl; // no longer testing txt*/ } void ConsoleUI::readScientists() { Scientist temp; //vector<Scientist> scientists = service.getScientists(); string tempName; cout << TAB << "Please enter a name: "; cin.ignore(64,'\n'); getline(cin, tempName); do { if(tempName.empty()) { getline(cin, tempName); cout << TAB << "You cannot enter a empty name. Please try again: " << endl; cout << "You cannot enter a empty name. Please try again: " << endl; getline(cin, tempName); } } while(tempName.empty()); temp.setName(tempName); bool validGender = false; string tempGender; char gender; cout << TAB << "Please enter the gender(M for male, F for female): "; while(validGender == false) { cin >> gender; if(gender != 'M' && gender != 'm' && gender != 'F' && gender != 'f') { cout << gender << " is not a walid option" << endl; cout << "pleas enter a vaild option" << endl; } if(gender == 'M'||gender=='m') { tempGender = "Male"; temp.setGender(tempGender); validGender = true; } else if(gender == 'F'||gender == 'f') { tempGender = "Female"; temp.setGender(tempGender); validGender = true; } } int tempDateOfBirth; int tempDateOfDeath; cout << TAB << "Please enter date of birth: "; do { cin >> tempDateOfBirth; if(tempDateOfBirth > 2016) { cout << TAB << "Invalid date. Please try again: " << endl; } else if(tempDateOfBirth < 0) { cout << TAB << "A person cannot have a negative date of birth. Please try again: "; } } while(tempDateOfBirth > 2016 || tempDateOfBirth < 0); temp.setDateOfBirth(tempDateOfBirth); cout << endl; cout << TAB << "Please enter date of death(Enter 13337 if the scientist is still alive): "; do { cin >> tempDateOfDeath; if(tempDateOfDeath < tempDateOfBirth) { cout << TAB << "Not possible. A person cannot die before it is born. Please try again: "; } else if(tempDateOfDeath == 13337) { } } while(tempDateOfDeath < tempDateOfBirth); if(tempDateOfDeath > 2016) { cout << "Not possible. A person cannot die beyond the current year." << endl; } while(tempDateOfDeath < tempDateOfBirth); temp.setDateOfDeath(tempDateOfDeath); cout << endl; char cont; cout << TAB << "Do you want to add another scientist? Press Y/y for yes or N/n for no: "; cin >> cont; if(cont == 'y' || cont == 'Y') { readScientists(); } else { features(); } //scientists.push_back(temp); //flytur upplýsingar inn í ScientistService service.create(temp); } void ConsoleUI::display(vector<Scientist> scientists) // hjálp { cout << "\t information about all listed scientist" << endl; cout << "\t___________________________________________________________________________" << endl; for(size_t i = 0; i < scientists.size(); i++) { cout << "\t |Name: " << scientists[i].getName() << endl; cout << "\t |Gender: " << scientists[i].getGender() << endl; cout << "\t |Born: " << scientists[i].getDateOfBirth() << endl; cout << "\t |Died: " << scientists[i].getDateOfDeath() << endl; cout << TAB << "----------------------------------------------------------------------------" << endl; } } void ConsoleUI::displayListOfScientistsAlpha() { vector<Scientist> scientists = service.getScientists(); display(scientists); } void ConsoleUI::displayListOfScientistsYoung() { vector<Scientist> scientists = service.getScientistsYoung(); display(scientists); } void ConsoleUI::displayListOfScientistsOld() { vector<Scientist> scientists = service.getScientistsOld(); display(scientists); } void ConsoleUI::searchName() { string name; cout << "Enter name of scientists you want to find: "; cin.ignore(); getline(cin, name); vector<Scientist> temp = service.searchName(name); if(temp.size() == 0) { cout << "No scientist name " << name << " in our data, try again" << endl; } else { display(temp); } } void ConsoleUI::searchDateOfBirth() { int year = 0; cout << "Enter the the year of birth of the Scientist: "; cin >> year; vector<Scientist> temp = service.searchDateOfBirth(year); if(temp.size() == 0) { cout << "No scientist in our data born that year, try again" << endl; } else { display(temp); } } void ConsoleUI::searchGender() { //vector<Scientist> temp = service.getScientists(); char gender; cout << "Please enter the gender(M for male, F for female): " << endl; cin >> gender; vector<Scientist> temp = service.searchGender(gender); if(temp.size() == 0) { if(gender == 'M' || gender == 'm') { cout << TAB << "There are no male scientist, try again" << endl; } if(gender == 'F' || gender == 'f') { cout << TAB<< "There are no male scientist, try again" << endl; } } else { display(temp); } } void ConsoleUI::listOrSortScientist() { char choice; while(choice != 'q' && choice != 'Q') { vector<Scientist> temp = service.getScientists(); cout << TAB << "Please choose a feature: "; cin >> choice; cout << endl; if(choice == 'h' || choice == 'H') { features(); } else if(choice == '1') { cout << TAB << ">>> Reading Scientists <<<" << endl << endl; readScientists(); } else if(choice == '2') { char sort; cout << TAB << "How should the list be sorted?" << endl; cout << TAB << "Press 1 for alphabetical order." << endl; cout << TAB << "Press 2 to sort from youngest to oldest." << endl; cout << TAB << "Press 3 to sort from oldest to youngest." << endl; cout << TAB << "" << endl; cout << TAB << "----------------------------------------------------------------------------" << endl; cin >> sort; if(sort == '1') { displayListOfScientistsAlpha(); } if(sort == '2') { displayListOfScientistsYoung(); } if(sort == '3') { displayListOfScientistsOld(); } } else if(choice == '3') { int searchOptions = 0; cout << TAB << "What do you want to search by?" << endl; cout << TAB << "Press 1 to search for a scientist witch a specific name" << endl; cout << TAB << "Press 2 to search for all scientists born a specific year" << endl; cout << TAB << "Press 3 to search for all scientists with a specific gender" << endl; cin >> searchOptions; if(searchOptions == 1) { searchName(); } else if(searchOptions == 2) { searchDateOfBirth(); } else if(searchOptions == 3) { searchGender(); } } } } <commit_msg>baetti vid alive<commit_after>#include <iostream> #include <string> #include "consoleui.h" using namespace std; const char TAB = '\t'; //efsta lagið ConsoleUI::ConsoleUI() { } void ConsoleUI::WelcomeMenu() { cout << endl; cout << endl; cout << TAB << "--------------------------------------------" << endl; cout << TAB << " Welcome! This program will store or show" << endl; cout << TAB << " famous computer scientists. " << endl; cout << TAB << "--------------------------------------------" << endl; cout << endl; } void ConsoleUI::features() { cout << TAB << "----------------------------------------------------------------------------" << endl; cout << TAB << "The list below shows you all possible features on what you can do." << endl; cout << endl; cout << TAB << "press H to show all options" << endl; //eitthvað svona er sniðgt; cout << TAB << "Press 1 to create a new scientist." << endl; cout << TAB << "Press 2 to list all scientists." << endl; cout << TAB << "Press 3 to search for a scientist." << endl; cout << TAB << "Press Q to quit the program." << endl; cout << TAB << "----------------------------------------------------------------------------" << endl; cout << endl; /* vector<Scientist> temp = service.getScientists(); // testing txt file cout << "\t |Name: " << temp[0].getName() << endl; cout << "\t |Gender: " << temp[0].getGender() << endl; cout << "\t |Born: " << temp[0].getDateOfBirth() << endl; cout << "\t |Died: " << temp[0].getDateOfDeath() << endl; // no longer testing txt*/ } void ConsoleUI::readScientists() { Scientist temp; //vector<Scientist> scientists = service.getScientists(); string tempName; cout << TAB << "Please enter a name: "; cin.ignore(64,'\n'); getline(cin, tempName); do { if(tempName.empty()) { getline(cin, tempName); cout << TAB << "You cannot enter a empty name. Please try again: " << endl; getline(cin, tempName); } } while(tempName.empty()); temp.setName(tempName); bool validGender = false; string tempGender; char gender; cout << TAB << "Please enter the gender(M for male, F for female): "; while(validGender == false) { cin >> gender; if(gender != 'M' && gender != 'm' && gender != 'F' && gender != 'f') { cout << gender << " is not a walid option" << endl; cout << "pleas enter a vaild option" << endl; } if(gender == 'M'||gender=='m') { tempGender = "Male"; temp.setGender(tempGender); validGender = true; } else if(gender == 'F'||gender == 'f') { tempGender = "Female"; temp.setGender(tempGender); validGender = true; } } int tempDateOfBirth; int tempDateOfDeath; cout << TAB << "Please enter date of birth: "; do { cin >> tempDateOfBirth; if(tempDateOfBirth > 2016) { cout << TAB << "Invalid date. Please try again: " << endl; } else if(tempDateOfBirth < 0) { cout << TAB << "A person cannot have a negative date of birth. Please try again: "; } } while(tempDateOfBirth > 2016 || tempDateOfBirth < 0); temp.setDateOfBirth(tempDateOfBirth); cout << TAB << "Please enter date of death(Enter 13337 if the scientist is still alive): "; do { cin >> tempDateOfDeath; if(tempDateOfDeath < tempDateOfBirth) { cout << TAB << "Not possible. A person cannot die before it is born. Please try again: "; } else if(tempDateOfDeath == 13337) { } } while(tempDateOfDeath < tempDateOfBirth); if(tempDateOfDeath > 2016 && tempDateOfDeath !=13337) { cout << "Not possible. A person cannot die beyond the current year." << endl; } while(tempDateOfDeath < tempDateOfBirth); temp.setDateOfDeath(tempDateOfDeath); cout << endl; char cont; cout << TAB << "Do you want to add another scientist? Press Y/y for yes or N/n for no: "; cin >> cont; if(cont == 'y' || cont == 'Y') { readScientists(); } else { features(); } //scientists.push_back(temp); //flytur upplýsingar inn í ScientistService service.create(temp); } void ConsoleUI::display(vector<Scientist> scientists) // hjálp { cout << "\t information about all listed scientist" << endl; cout << "\t___________________________________________________________________________" << endl; for(size_t i = 0; i < scientists.size(); i++) { cout << "\t |Gender: " << scientists[i].getGender() << endl; cout << "\t |Born: " << scientists[i].getDateOfBirth() << endl; if(scientists[i].getDateOfDeath() == 13337) cout << "\t |Still alive " << endl; else cout << "\t |Died: " << scientists[i].getDateOfDeath() << endl; cout << TAB << "----------------------------------------------------------------------------" << endl; } } void ConsoleUI::displayListOfScientistsAlpha() { vector<Scientist> scientists = service.getScientists(); display(scientists); } void ConsoleUI::displayListOfScientistsYoung() { vector<Scientist> scientists = service.getScientistsYoung(); display(scientists); } void ConsoleUI::displayListOfScientistsOld() { vector<Scientist> scientists = service.getScientistsOld(); display(scientists); } void ConsoleUI::searchName() { string name; cout << "Enter name of scientists you want to find: "; cin.ignore(); getline(cin, name); vector<Scientist> temp = service.searchName(name); if(temp.size() == 0) { cout << "No scientist name " << name << " in our data, try again" << endl; } else { display(temp); } } void ConsoleUI::searchDateOfBirth() { int year = 0; cout << "Enter the the year of birth of the Scientist: "; cin >> year; vector<Scientist> temp = service.searchDateOfBirth(year); if(temp.size() == 0) { cout << "No scientist in our data born that year, try again" << endl; } else { display(temp); } } void ConsoleUI::searchGender() { //vector<Scientist> temp = service.getScientists(); char gender; cout << "Please enter the gender(M for male, F for female): " << endl; cin >> gender; vector<Scientist> temp = service.searchGender(gender); if(temp.size() == 0) { if(gender == 'M' || gender == 'm') { cout << TAB << "There are no male scientist, try again" << endl; } if(gender == 'F' || gender == 'f') { cout << TAB<< "There are no male scientist, try again" << endl; } } else { display(temp); } } void ConsoleUI::listOrSortScientist() { char choice; while(choice != 'q' && choice != 'Q') { vector<Scientist> temp = service.getScientists(); cout << TAB << "Please choose a feature: "; cin >> choice; cout << endl; if(choice == 'h' || choice == 'H') { features(); } else if(choice == '1') { cout << TAB << ">>> Reading Scientists <<<" << endl << endl; readScientists(); } else if(choice == '2') { char sort; cout << TAB << "How should the list be sorted?" << endl; cout << TAB << "Press 1 for alphabetical order." << endl; cout << TAB << "Press 2 to sort from youngest to oldest." << endl; cout << TAB << "Press 3 to sort from oldest to youngest." << endl; cout << TAB << "" << endl; cout << TAB << "----------------------------------------------------------------------------" << endl; cin >> sort; if(sort == '1') { displayListOfScientistsAlpha(); } if(sort == '2') { displayListOfScientistsYoung(); } if(sort == '3') { displayListOfScientistsOld(); } } else if(choice == '3') { int searchOptions = 0; cout << TAB << "What do you want to search by?" << endl; cout << TAB << "Press 1 to search for a scientist witch a specific name" << endl; cout << TAB << "Press 2 to search for all scientists born a specific year" << endl; cout << TAB << "Press 3 to search for all scientists with a specific gender" << endl; cin >> searchOptions; if(searchOptions == 1) { searchName(); } else if(searchOptions == 2) { searchDateOfBirth(); } else if(searchOptions == 3) { searchGender(); } } } } <|endoftext|>
<commit_before>#include "mainwindow.h" #include "ui_mainwindow.h" #include <QMessageBox> #include <iostream> #include <QCloseEvent> #include <QColorDialog> #include <chrono> #include <thread> #include "icononbuttonhandler.h" #include "inputwindow.h" #include "Video/shapes/shape.h" using namespace std; using namespace cv; /** * @brief MainWindow::MainWindow * Constructor * @param parent a QWidget variable */ MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow){ ui->setupUi(this); selectedProject = nullptr; video_slider = findChild<QSlider*>("videoSlider"); iconOnButtonHandler = new IconOnButtonHandler(); iconOnButtonHandler->set_pictures_to_buttons(ui); fileHandler = new FileHandler(); set_shortcuts(); // Add this object as a listener to videoFrame. ui->videoFrame->installEventFilter(this); ui->ProjectTree->setContextMenuPolicy(Qt::CustomContextMenu); connect(ui->ProjectTree, &QTreeWidget::customContextMenuRequested, this, &MainWindow::prepare_menu); mvideo_player = new video_player(); QObject::connect(mvideo_player, SIGNAL(processedImage(QImage)), this, SLOT(update_video(QImage))); QObject::connect(mvideo_player, SIGNAL(currentFrame(int)), this, SLOT(set_video_slider_pos(int))); //Used for rescaling the source image for video playback mvideo_player->set_frame_height(ui->videoFrame->height()); mvideo_player->set_frame_width(ui->videoFrame->width()); } /** * @brief MainWindow::~MainWindow * Destructor */ MainWindow::~MainWindow() { delete iconOnButtonHandler; delete fileHandler; delete mvideo_player; delete ui; } /** * @brief MainWindow::set_shortcuts * Function to set shortcuts on actions */ void MainWindow::set_shortcuts(){ ui->actionExit->setShortcut(tr("Ctrl+e")); } /** * @brief MainWindow::set_status_bar * @param status text to show in the statusbar * @param timer time to show it in the bar in ms, 750ms is standard */ void MainWindow::set_status_bar(string status, int timer){ ui->statusBar->showMessage(QString::fromStdString(status), timer); } /** * @brief MainWindow::on_fastBackwardButton_clicked * The button supposed to play the video slower * */ void MainWindow::on_fastBackwardButton_clicked(){ } /** * @brief MainWindow::on_playPauseButton_clicked * The button supposed to play and pause the video */ void MainWindow::on_playPauseButton_clicked() { if (mvideo_player->is_paused() || mvideo_player->is_stopped()) { set_status_bar("Playing"); iconOnButtonHandler->set_icon("pause", ui->playPauseButton);//changes the icon on the play button to a pause-icon mvideo_player->start(); } else { set_status_bar("Paused"); iconOnButtonHandler->set_icon("play", ui->playPauseButton); mvideo_player->play_pause(); mvideo_player->wait(); } } /** * @brief MainWindow::on_fastForwardButton_clicked * The button supposed to play the video faster */ void MainWindow::on_fastForwardButton_clicked(){ } /** * @brief MainWindow::on_stopButton_clicked * The button supposed to stop the video */ void MainWindow::on_stopButton_clicked() { set_status_bar("Stopped"); if (!mvideo_player->is_paused()) { iconOnButtonHandler->set_icon("play", ui->playPauseButton); } mvideo_player->stop_video(); } /** * @brief MainWindow::on_nextFrameButton_clicked * The button supposed to play the next frame of the video */ void MainWindow::on_nextFrameButton_clicked() { if (mvideo_player->is_paused()) { set_status_bar("Went forward a frame"); mvideo_player->next_frame(); } else { set_status_bar("Needs to be paused"); } } /** * @brief MainWindow::on_previousFrameButton_clicked * The button supposed to play the previous frame of the video */ void MainWindow::on_previousFrameButton_clicked() { if (mvideo_player->is_paused()) { set_status_bar("Went back a frame"); mvideo_player->previous_frame(); } else { set_status_bar("Needs to be paused"); } } /** * @brief MainWindow::update_video * Sets the videoFrame pixmap to the current frame from video * @param frame */ void MainWindow::update_video(QImage frame) { ui->videoFrame->setPixmap(QPixmap::fromImage(frame)); } /** * @brief MainWindow::set_video_slider_pos * Sets the position of slider in video to position pos * @param pos */ void MainWindow::set_video_slider_pos(int pos) { if (pos <= video_slider->maximum()) { video_slider->setSliderPosition(pos); } } /** * @brief MainWindow::resizeEvent * Used for rescaling the source image for video playback * @param event */ void MainWindow::resizeEvent(QResizeEvent* event) { QMainWindow::resizeEvent(event); mvideo_player->set_frame_height(ui->videoFrame->height()); mvideo_player->set_frame_width(ui->videoFrame->width()); } /** * @brief MainWindow::on_videoSlider_valueChanged * Update the slider to where the mouse is * @param newPos current position of the slider */ void MainWindow::on_videoSlider_valueChanged(int newPos){ // Make slider to follow the mouse directly and not by pageStep steps Qt::MouseButtons btns = QApplication::mouseButtons(); QPoint localMousePos = ui->videoSlider->mapFromGlobal(QCursor::pos()); bool clickOnSlider = (btns & Qt::LeftButton) && (localMousePos.x() >= 0 && localMousePos.y() >= 0 && localMousePos.x() < ui->videoSlider->size().width() && localMousePos.y() < ui->videoSlider->size().height()); if (clickOnSlider) { // Attention! The following works only for Horizontal, Left-to-right sliders float posRatio = localMousePos.x() / (float )ui->videoSlider->size().width(); int sliderRange = ui->videoSlider->maximum() - ui->videoSlider->minimum(); int sliderPosUnderMouse = ui->videoSlider->minimum() + sliderRange * posRatio; if (sliderPosUnderMouse != newPos) { ui->videoSlider->setValue(sliderPosUnderMouse); return; } } } /** * @brief MainWindow::closeEvent * asks if you are sure you want to quit. * @param event closing */ void MainWindow::closeEvent (QCloseEvent *event){ set_status_bar("Closing"); QMessageBox::StandardButton resBtn = QMessageBox::question( this, "Exit", tr("Are you sure you want to quit?\n"), QMessageBox::No | QMessageBox::Yes, QMessageBox::No); if (resBtn != QMessageBox::Yes) { event->ignore(); } else { event->accept(); } } /** * @brief MainWindow::on_actionExit_triggered * sends a closeEvent when you press exit */ void MainWindow::on_actionExit_triggered(){ this->close(); } /** * @brief MainWindow::on_bookmarkButton_clicked * the button supposed to add a bookmark */ void MainWindow::on_bookmarkButton_clicked(){ } /** * @brief MainWindow::on_actionAddProject_triggered */ void MainWindow::on_actionAddProject_triggered() { ACTION action = ADD_PROJECT; inputWindow = new inputwindow(this, action, "Project name:"); inputWindow->show(); set_status_bar("Adding project, need name"); } /** * @brief MainWindow::inputSwitchCase * @param input the input from the user * @param action the action that was triggered earlier */ void MainWindow::input_switch_case(ACTION action, QString qInput) { std::string input = qInput.toStdString(); switch(action){ case ADD_PROJECT: { int id = fileHandler->create_project(input)->m_id; MyQTreeWidgetItem *projectInTree = new MyQTreeWidgetItem(TYPE::PROJECT, qInput, id); projectInTree->setText(0, qInput); set_selected_project(projectInTree); ui->ProjectTree->addTopLevelItem(projectInTree); set_status_bar("Project " + input + " created."); delete inputWindow; break; } case CANCEL: { set_status_bar("Cancel"); break; } case ADD_VIDEO: { fileHandler->add_video(fileHandler->get_project(selectedProject->id), input); MyQTreeWidgetItem *videoInTree = new MyQTreeWidgetItem(TYPE::VIDEO, qInput); videoInTree->setText(0, qInput); selectedProject->addChild(videoInTree); set_status_bar("Video " + input + " added."); break; } default: break; } } /** * @brief MainWindow::on_ProjectTree_itemClicked * @param item the item in the projectTree that was clicked * @param column the column in the tree */ void MainWindow::on_ProjectTree_itemClicked(QTreeWidgetItem *item, int column) { MyQTreeWidgetItem *newItem = (MyQTreeWidgetItem*)item; if (newItem->type == TYPE::PROJECT) set_selected_project(newItem); } /** @brief MainWindow::on_actionShow_hide_overview_triggered * Toggles the showing/hiding of the overlay. * Invoked by menu item. */ void MainWindow::on_actionShow_hide_overview_triggered() { mvideo_player->toggle_overlay(); if (mvideo_player->is_showing_overlay()) { set_status_bar("Overlay: On."); } else { set_status_bar("Overlay: Off."); } } /** * @brief MainWindow::on_actionColour_triggered * Selects a colour for the overlay drawing tool. */ void MainWindow::on_actionColour_triggered() { QColor col = QColorDialog::getColor(); mvideo_player->set_overlay_colour(col); string msg = "Color: "; msg.append(col.name().toStdString()); set_status_bar(msg); } /** * @brief MainWindow::on_actionRectangle_triggered * Selects the rectangle shape for the overlay drawing tool. */ void MainWindow::on_actionRectangle_triggered() { mvideo_player->set_overlay_tool(RECTANGLE); set_status_bar("Tool: rectangle."); } /** * @brief MainWindow::on_actionCircle_triggered * Selects the circle shape for the overlay drawing tool. */ void MainWindow::on_actionCircle_triggered() { mvideo_player->set_overlay_tool(CIRCLE); set_status_bar("Tool: circle."); } /** * @brief MainWindow::on_actionLine_triggered * Selects the line shape for the overlay drawing tool. */ void MainWindow::on_actionLine_triggered() { mvideo_player->set_overlay_tool(LINE); set_status_bar("Tool: line."); } /** * @brief MainWindow::on_actionArrow_triggered * Selects the arrow shape for the overlay drawing tool. */ void MainWindow::on_actionArrow_triggered() { mvideo_player->set_overlay_tool(ARROW); set_status_bar("Tool: arrow."); } /** * @brief MainWindow::on_actionPen_triggered * Selects the pen for the overlay drawing tool. */ void MainWindow::on_actionPen_triggered() { mvideo_player->set_overlay_tool(PEN); set_status_bar("Tool: pen."); } /** * @brief MainWindow::eventFilter * Listener function for all eventFilters MainWindow has installed. * @param obj the object invoking the event * @param event the invooked event * @return Returns true if the event matched any of the overlay's * functionality, else false. * (Returning false means that the event is sent to the * target object instead, but not if true is returned.) */ bool MainWindow::eventFilter(QObject *obj, QEvent *event) { // Check who invoked the event. if (qobject_cast<QLabel*>(obj)==ui->videoFrame) { // Cast to a mouse event to get the mouse position. QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event); QPoint pos = mouseEvent->pos(); // Check what kind of event. if (event->type() == QEvent::MouseButtonPress) { mvideo_player->video_mouse_pressed(pos); return true; } else if (event->type() == QEvent::MouseButtonRelease) { mvideo_player->video_mouse_released(pos); return true; } else if (event->type() == QEvent::MouseMove) { mvideo_player->video_mouse_moved(pos); return true; } } return false; } /** * @brief MainWindow::prepare_menu * @param pos * Creates context menu on right-click in tree view */ void MainWindow::prepare_menu(const QPoint & pos) { QTreeWidget *tree = ui->ProjectTree; MyQTreeWidgetItem *item = (MyQTreeWidgetItem*)tree->itemAt( pos ); QMenu menu(this); if(item == nullptr) { } else if(item->type == TYPE::PROJECT) { set_selected_project(item); QAction *addVideo = new QAction(QIcon(""), tr("&Add video"), this); addVideo->setStatusTip(tr("Add video")); menu.addAction(addVideo); connect(addVideo, SIGNAL(triggered()), this, SLOT(add_video())); } else if(item->type == TYPE::VIDEO) { selectedVideo = item; QAction *loadVideo = new QAction(QIcon(""), tr("&Play video"), this); loadVideo->setStatusTip(tr("Play video")); menu.addAction(loadVideo); connect(loadVideo, SIGNAL(triggered()), this, SLOT(play_video())); } QPoint pt(pos); menu.exec( tree->mapToGlobal(pos) ); } /** * @brief MainWindow::add_video * Prompts user with file browser to add video * to selected project */ void MainWindow::add_video() { QString dir = QFileDialog::getOpenFileName(this, tr("Choose video"),WORKSPACE,tr("*.avi;*.mkv;*.mov;*.mp4;*.3gp;*.flv;*.webm;*.ogv")); input_switch_case(ACTION::ADD_VIDEO, dir); } /** * @brief MainWindow::play_video * Loads selected video, flips playbutton to pause * plays video from beginning * */ void MainWindow::play_video() { mvideo_player->load_video(selectedVideo->name.toStdString()); iconOnButtonHandler->set_icon("pause", ui->playPauseButton); video_slider->setMaximum(mvideo_player->get_num_frames()); mvideo_player->set_playback_frame(0); } /** * @todo To be implemented * @brief MainWindow::set_selected_project * @param newSelectedProject */ void MainWindow::set_selected_project(MyQTreeWidgetItem *newSelectedProject){ if(selectedProject == nullptr) { selectedProject = newSelectedProject; QString string = selectedProject->text(0); string.append(" <--"); selectedProject->setText(0, string); } else if (selectedProject != newSelectedProject) { QString string = selectedProject->text(0); string.chop(4); selectedProject->setText(0, string); selectedProject = newSelectedProject; string = selectedProject->text(0); string.append(" <--"); selectedProject->setText(0, string); } } /** * @brief MainWindow::on_actionSave_triggered */ void MainWindow::on_actionSave_triggered() { } <commit_msg>added m4v fileformat for videos<commit_after>#include "mainwindow.h" #include "ui_mainwindow.h" #include <QMessageBox> #include <iostream> #include <QCloseEvent> #include <QColorDialog> #include <chrono> #include <thread> #include "icononbuttonhandler.h" #include "inputwindow.h" #include "Video/shapes/shape.h" using namespace std; using namespace cv; /** * @brief MainWindow::MainWindow * Constructor * @param parent a QWidget variable */ MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow){ ui->setupUi(this); selectedProject = nullptr; video_slider = findChild<QSlider*>("videoSlider"); iconOnButtonHandler = new IconOnButtonHandler(); iconOnButtonHandler->set_pictures_to_buttons(ui); fileHandler = new FileHandler(); set_shortcuts(); // Add this object as a listener to videoFrame. ui->videoFrame->installEventFilter(this); ui->ProjectTree->setContextMenuPolicy(Qt::CustomContextMenu); connect(ui->ProjectTree, &QTreeWidget::customContextMenuRequested, this, &MainWindow::prepare_menu); mvideo_player = new video_player(); QObject::connect(mvideo_player, SIGNAL(processedImage(QImage)), this, SLOT(update_video(QImage))); QObject::connect(mvideo_player, SIGNAL(currentFrame(int)), this, SLOT(set_video_slider_pos(int))); //Used for rescaling the source image for video playback mvideo_player->set_frame_height(ui->videoFrame->height()); mvideo_player->set_frame_width(ui->videoFrame->width()); } /** * @brief MainWindow::~MainWindow * Destructor */ MainWindow::~MainWindow() { delete iconOnButtonHandler; delete fileHandler; delete mvideo_player; delete ui; } /** * @brief MainWindow::set_shortcuts * Function to set shortcuts on actions */ void MainWindow::set_shortcuts(){ ui->actionExit->setShortcut(tr("Ctrl+e")); } /** * @brief MainWindow::set_status_bar * @param status text to show in the statusbar * @param timer time to show it in the bar in ms, 750ms is standard */ void MainWindow::set_status_bar(string status, int timer){ ui->statusBar->showMessage(QString::fromStdString(status), timer); } /** * @brief MainWindow::on_fastBackwardButton_clicked * The button supposed to play the video slower * */ void MainWindow::on_fastBackwardButton_clicked(){ } /** * @brief MainWindow::on_playPauseButton_clicked * The button supposed to play and pause the video */ void MainWindow::on_playPauseButton_clicked() { if (mvideo_player->is_paused() || mvideo_player->is_stopped()) { set_status_bar("Playing"); iconOnButtonHandler->set_icon("pause", ui->playPauseButton);//changes the icon on the play button to a pause-icon mvideo_player->start(); } else { set_status_bar("Paused"); iconOnButtonHandler->set_icon("play", ui->playPauseButton); mvideo_player->play_pause(); mvideo_player->wait(); } } /** * @brief MainWindow::on_fastForwardButton_clicked * The button supposed to play the video faster */ void MainWindow::on_fastForwardButton_clicked(){ } /** * @brief MainWindow::on_stopButton_clicked * The button supposed to stop the video */ void MainWindow::on_stopButton_clicked() { set_status_bar("Stopped"); if (!mvideo_player->is_paused()) { iconOnButtonHandler->set_icon("play", ui->playPauseButton); } mvideo_player->stop_video(); } /** * @brief MainWindow::on_nextFrameButton_clicked * The button supposed to play the next frame of the video */ void MainWindow::on_nextFrameButton_clicked() { if (mvideo_player->is_paused()) { set_status_bar("Went forward a frame"); mvideo_player->next_frame(); } else { set_status_bar("Needs to be paused"); } } /** * @brief MainWindow::on_previousFrameButton_clicked * The button supposed to play the previous frame of the video */ void MainWindow::on_previousFrameButton_clicked() { if (mvideo_player->is_paused()) { set_status_bar("Went back a frame"); mvideo_player->previous_frame(); } else { set_status_bar("Needs to be paused"); } } /** * @brief MainWindow::update_video * Sets the videoFrame pixmap to the current frame from video * @param frame */ void MainWindow::update_video(QImage frame) { ui->videoFrame->setPixmap(QPixmap::fromImage(frame)); } /** * @brief MainWindow::set_video_slider_pos * Sets the position of slider in video to position pos * @param pos */ void MainWindow::set_video_slider_pos(int pos) { if (pos <= video_slider->maximum()) { video_slider->setSliderPosition(pos); } } /** * @brief MainWindow::resizeEvent * Used for rescaling the source image for video playback * @param event */ void MainWindow::resizeEvent(QResizeEvent* event) { QMainWindow::resizeEvent(event); mvideo_player->set_frame_height(ui->videoFrame->height()); mvideo_player->set_frame_width(ui->videoFrame->width()); } /** * @brief MainWindow::on_videoSlider_valueChanged * Update the slider to where the mouse is * @param newPos current position of the slider */ void MainWindow::on_videoSlider_valueChanged(int newPos){ // Make slider to follow the mouse directly and not by pageStep steps Qt::MouseButtons btns = QApplication::mouseButtons(); QPoint localMousePos = ui->videoSlider->mapFromGlobal(QCursor::pos()); bool clickOnSlider = (btns & Qt::LeftButton) && (localMousePos.x() >= 0 && localMousePos.y() >= 0 && localMousePos.x() < ui->videoSlider->size().width() && localMousePos.y() < ui->videoSlider->size().height()); if (clickOnSlider) { // Attention! The following works only for Horizontal, Left-to-right sliders float posRatio = localMousePos.x() / (float )ui->videoSlider->size().width(); int sliderRange = ui->videoSlider->maximum() - ui->videoSlider->minimum(); int sliderPosUnderMouse = ui->videoSlider->minimum() + sliderRange * posRatio; if (sliderPosUnderMouse != newPos) { ui->videoSlider->setValue(sliderPosUnderMouse); return; } } } /** * @brief MainWindow::closeEvent * asks if you are sure you want to quit. * @param event closing */ void MainWindow::closeEvent (QCloseEvent *event){ set_status_bar("Closing"); QMessageBox::StandardButton resBtn = QMessageBox::question( this, "Exit", tr("Are you sure you want to quit?\n"), QMessageBox::No | QMessageBox::Yes, QMessageBox::No); if (resBtn != QMessageBox::Yes) { event->ignore(); } else { event->accept(); } } /** * @brief MainWindow::on_actionExit_triggered * sends a closeEvent when you press exit */ void MainWindow::on_actionExit_triggered(){ this->close(); } /** * @brief MainWindow::on_bookmarkButton_clicked * the button supposed to add a bookmark */ void MainWindow::on_bookmarkButton_clicked(){ } /** * @brief MainWindow::on_actionAddProject_triggered */ void MainWindow::on_actionAddProject_triggered() { ACTION action = ADD_PROJECT; inputWindow = new inputwindow(this, action, "Project name:"); inputWindow->show(); set_status_bar("Adding project, need name"); } /** * @brief MainWindow::inputSwitchCase * @param input the input from the user * @param action the action that was triggered earlier */ void MainWindow::input_switch_case(ACTION action, QString qInput) { std::string input = qInput.toStdString(); switch(action){ case ADD_PROJECT: { int id = fileHandler->create_project(input)->m_id; MyQTreeWidgetItem *projectInTree = new MyQTreeWidgetItem(TYPE::PROJECT, qInput, id); projectInTree->setText(0, qInput); set_selected_project(projectInTree); ui->ProjectTree->addTopLevelItem(projectInTree); set_status_bar("Project " + input + " created."); delete inputWindow; break; } case CANCEL: { set_status_bar("Cancel"); break; } case ADD_VIDEO: { fileHandler->add_video(fileHandler->get_project(selectedProject->id), input); MyQTreeWidgetItem *videoInTree = new MyQTreeWidgetItem(TYPE::VIDEO, qInput); videoInTree->setText(0, qInput); selectedProject->addChild(videoInTree); set_status_bar("Video " + input + " added."); break; } default: break; } } /** * @brief MainWindow::on_ProjectTree_itemClicked * @param item the item in the projectTree that was clicked * @param column the column in the tree */ void MainWindow::on_ProjectTree_itemClicked(QTreeWidgetItem *item, int column) { MyQTreeWidgetItem *newItem = (MyQTreeWidgetItem*)item; if (newItem->type == TYPE::PROJECT) set_selected_project(newItem); } /** @brief MainWindow::on_actionShow_hide_overview_triggered * Toggles the showing/hiding of the overlay. * Invoked by menu item. */ void MainWindow::on_actionShow_hide_overview_triggered() { mvideo_player->toggle_overlay(); if (mvideo_player->is_showing_overlay()) { set_status_bar("Overlay: On."); } else { set_status_bar("Overlay: Off."); } } /** * @brief MainWindow::on_actionColour_triggered * Selects a colour for the overlay drawing tool. */ void MainWindow::on_actionColour_triggered() { QColor col = QColorDialog::getColor(); mvideo_player->set_overlay_colour(col); string msg = "Color: "; msg.append(col.name().toStdString()); set_status_bar(msg); } /** * @brief MainWindow::on_actionRectangle_triggered * Selects the rectangle shape for the overlay drawing tool. */ void MainWindow::on_actionRectangle_triggered() { mvideo_player->set_overlay_tool(RECTANGLE); set_status_bar("Tool: rectangle."); } /** * @brief MainWindow::on_actionCircle_triggered * Selects the circle shape for the overlay drawing tool. */ void MainWindow::on_actionCircle_triggered() { mvideo_player->set_overlay_tool(CIRCLE); set_status_bar("Tool: circle."); } /** * @brief MainWindow::on_actionLine_triggered * Selects the line shape for the overlay drawing tool. */ void MainWindow::on_actionLine_triggered() { mvideo_player->set_overlay_tool(LINE); set_status_bar("Tool: line."); } /** * @brief MainWindow::on_actionArrow_triggered * Selects the arrow shape for the overlay drawing tool. */ void MainWindow::on_actionArrow_triggered() { mvideo_player->set_overlay_tool(ARROW); set_status_bar("Tool: arrow."); } /** * @brief MainWindow::on_actionPen_triggered * Selects the pen for the overlay drawing tool. */ void MainWindow::on_actionPen_triggered() { mvideo_player->set_overlay_tool(PEN); set_status_bar("Tool: pen."); } /** * @brief MainWindow::eventFilter * Listener function for all eventFilters MainWindow has installed. * @param obj the object invoking the event * @param event the invooked event * @return Returns true if the event matched any of the overlay's * functionality, else false. * (Returning false means that the event is sent to the * target object instead, but not if true is returned.) */ bool MainWindow::eventFilter(QObject *obj, QEvent *event) { // Check who invoked the event. if (qobject_cast<QLabel*>(obj)==ui->videoFrame) { // Cast to a mouse event to get the mouse position. QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event); QPoint pos = mouseEvent->pos(); // Check what kind of event. if (event->type() == QEvent::MouseButtonPress) { mvideo_player->video_mouse_pressed(pos); return true; } else if (event->type() == QEvent::MouseButtonRelease) { mvideo_player->video_mouse_released(pos); return true; } else if (event->type() == QEvent::MouseMove) { mvideo_player->video_mouse_moved(pos); return true; } } return false; } /** * @brief MainWindow::prepare_menu * @param pos * Creates context menu on right-click in tree view */ void MainWindow::prepare_menu(const QPoint & pos) { QTreeWidget *tree = ui->ProjectTree; MyQTreeWidgetItem *item = (MyQTreeWidgetItem*)tree->itemAt( pos ); QMenu menu(this); if(item == nullptr) { } else if(item->type == TYPE::PROJECT) { set_selected_project(item); QAction *addVideo = new QAction(QIcon(""), tr("&Add video"), this); addVideo->setStatusTip(tr("Add video")); menu.addAction(addVideo); connect(addVideo, SIGNAL(triggered()), this, SLOT(add_video())); } else if(item->type == TYPE::VIDEO) { selectedVideo = item; QAction *loadVideo = new QAction(QIcon(""), tr("&Play video"), this); loadVideo->setStatusTip(tr("Play video")); menu.addAction(loadVideo); connect(loadVideo, SIGNAL(triggered()), this, SLOT(play_video())); } QPoint pt(pos); menu.exec( tree->mapToGlobal(pos) ); } /** * @brief MainWindow::add_video * Prompts user with file browser to add video * to selected project */ void MainWindow::add_video() { QString dir = QFileDialog::getOpenFileName(this, tr("Choose video"),WORKSPACE,tr("*.avi;*.mkv;*.mov;*.mp4;*.3gp;*.flv;*.webm;*.ogv;*.m4v")); input_switch_case(ACTION::ADD_VIDEO, dir); } /** * @brief MainWindow::play_video * Loads selected video, flips playbutton to pause * plays video from beginning * */ void MainWindow::play_video() { mvideo_player->load_video(selectedVideo->name.toStdString()); iconOnButtonHandler->set_icon("pause", ui->playPauseButton); video_slider->setMaximum(mvideo_player->get_num_frames()); mvideo_player->set_playback_frame(0); } /** * @todo To be implemented * @brief MainWindow::set_selected_project * @param newSelectedProject */ void MainWindow::set_selected_project(MyQTreeWidgetItem *newSelectedProject){ if(selectedProject == nullptr) { selectedProject = newSelectedProject; QString string = selectedProject->text(0); string.append(" <--"); selectedProject->setText(0, string); } else if (selectedProject != newSelectedProject) { QString string = selectedProject->text(0); string.chop(4); selectedProject->setText(0, string); selectedProject = newSelectedProject; string = selectedProject->text(0); string.append(" <--"); selectedProject->setText(0, string); } } /** * @brief MainWindow::on_actionSave_triggered */ void MainWindow::on_actionSave_triggered() { } <|endoftext|>
<commit_before>#include "Chunk.h" Chunk::Chunk(int size, glm::vec3 pos) { this->size = size; voxels = std::vector<std::vector<std::vector<Voxel>>>(); for (int x = 0; x < size; x++) { voxels.push_back(std::vector<std::vector<Voxel>>()); for (int y = 0; y < size; y++) { voxels[x].push_back(std::vector<Voxel>()); for (int z = 0; z < size; z++) { voxels[x][y].push_back(Voxel()); voxels[x][y][z].SetPosition(glm::vec3(x + pos.x, y + pos.y, z + pos.z)); } } } } Chunk::~Chunk() { } void Chunk::setVisiblity(bool visibility) { visible = false; } std::vector<glm::vec3> Chunk::getVertices() { std::vector<glm::vec3> returnedVertices; for (int x = 0; x < size; x++) { for (int y = 0; y < size; y++) { for (int z = 0; z < size; z++) { if (voxels[x][y][z].visible) { std::vector<glm::vec3> v = voxels[x][y][z].getPoints(); returnedVertices.insert(returnedVertices.end(), v.begin(), v.end()); // voxels[x][y][z] } } } } return returnedVertices; } std::vector<glm::vec3> Chunk::getNormals() { std::vector<glm::vec3> returnedNormals; for (int x = 0; x < size; x++) { for (int y = 0; y < size; y++) { for (int z = 0; z < size; z++) { if (voxels[x][y][z].visible) { std::vector<glm::vec3> v = voxels[x][y][z].getNormals(); returnedNormals.insert(returnedNormals.end(), v.begin(), v.end()); // voxels[x][y][z] } } } } return returnedNormals; } void Chunk::deleteRandomVoxels(float probability) { } <commit_msg>almost random destroy<commit_after>#include "Chunk.h" Chunk::Chunk(int size, glm::vec3 pos) { this->size = size; voxels = std::vector<std::vector<std::vector<Voxel>>>(); for (int x = 0; x < size; x++) { voxels.push_back(std::vector<std::vector<Voxel>>()); for (int y = 0; y < size; y++) { voxels[x].push_back(std::vector<Voxel>()); for (int z = 0; z < size; z++) { voxels[x][y].push_back(Voxel()); voxels[x][y][z].SetPosition(glm::vec3(x + pos.x, y + pos.y, z + pos.z)); } } } } Chunk::~Chunk() { } void Chunk::setVisiblity(bool visibility) { visible = false; } std::vector<glm::vec3> Chunk::getVertices() { std::vector<glm::vec3> returnedVertices; for (int x = 0; x < size; x++) { for (int y = 0; y < size; y++) { for (int z = 0; z < size; z++) { if (voxels[x][y][z].visible) { std::vector<glm::vec3> v = voxels[x][y][z].getPoints(); returnedVertices.insert(returnedVertices.end(), v.begin(), v.end()); // voxels[x][y][z] } } } } return returnedVertices; } std::vector<glm::vec3> Chunk::getNormals() { std::vector<glm::vec3> returnedNormals; for (int x = 0; x < size; x++) { for (int y = 0; y < size; y++) { for (int z = 0; z < size; z++) { if (voxels[x][y][z].visible) { std::vector<glm::vec3> v = voxels[x][y][z].getNormals(); returnedNormals.insert(returnedNormals.end(), v.begin(), v.end()); // voxels[x][y][z] } } } } return returnedNormals; } void Chunk::deleteRandomVoxels(float probability) { for (int x = 0; x < size; x++) { for (int y = 0; y < size; y++) { for (int z = 0; z < size; z++) { if (rand() > 0.5f) { voxels[x][y][z].visible=false; } } } } } <|endoftext|>
<commit_before><commit_msg>dirent.h doesn't exist on windows<commit_after><|endoftext|>
<commit_before>#include <SmurffCpp/Utils/StepFile.h> #include <iostream> #include <SmurffCpp/Model.h> #include <SmurffCpp/result.h> #include <SmurffCpp/Priors/ILatentPrior.h> #include <SmurffCpp/Utils/Error.h> #include <SmurffCpp/Utils/StringUtils.h> #include <SmurffCpp/IO/GenericIO.h> #include <SmurffCpp/IO/MatrixIO.h> #define NONE_TAG "none" #define STEP_SAMPLE_PREFIX "sample-" #define STEP_CHECKPOINT_PREFIX "checkpoint-" #define STEP_INI_SUFFIX "-step.ini" #define LATENTS_PREFIX "latents_" #define LINK_MATRIX_PREFIX "link_matrix_" #define GLOBAL_SEC_TAG "global" #define LATENTS_SEC_TAG "latents" #define PRED_SEC_TAG "predictions" #define LINK_MATRICES_SEC_TAG "link_matrices" #define IS_CHECKPOINT_TAG "is_checkpoint" #define NUMBER_TAG "number" #define NUM_MODES_TAG "num_modes" #define PRED_TAG "pred" #define PRED_STATE_TAG "pred_state" using namespace smurff; StepFile::StepFile(std::int32_t isample, std::string prefix, std::string extension, bool create, bool checkpoint) : m_isample(isample), m_prefix(prefix), m_extension(extension), m_checkpoint(checkpoint) { if (create) { THROWERROR_ASSERT(!m_extension.empty()); m_iniReader = std::make_shared<INIFile>(); m_iniReader->create(getStepFileName()); } else { //load all entries in ini file to be able to go through step file internals m_iniReader = std::make_shared<INIFile>(); m_iniReader->open(getStepFileName()); } } StepFile::StepFile(const std::string& path, std::string prefix, std::string extension) : m_prefix(prefix), m_extension(extension) { //load all entries in ini file to be able to go through step file internals m_iniReader = std::make_shared<INIFile>(); m_iniReader->open(path); m_checkpoint = std::stoi(getIniValueBase(GLOBAL_SEC_TAG, IS_CHECKPOINT_TAG)); m_isample = std::stoi(getIniValueBase(GLOBAL_SEC_TAG, NUMBER_TAG)); } //name methods std::pair<bool, std::string> StepFile::tryGetIniValueFullPath(const std::string &section, const std::string &tag) const { auto pair = tryGetIniValueBase(section, tag); if (pair.first && !startsWith(pair.second, m_prefix)) pair.second = m_prefix + pair.second; return pair; } std::string StepFile::getStepFileName() const { std::string prefix = getStepPrefix(); return prefix + STEP_INI_SUFFIX; } bool StepFile::isBinary() const { THROWERROR_ASSERT(!m_extension.empty()); if (m_extension == ".ddm") { return true; } else { THROWERROR_ASSERT_MSG(m_extension == ".csv", "Invalid save_extension: " + m_extension); } return false; } std::string StepFile::getStepPrefix() const { std::string prefix = m_checkpoint ? STEP_CHECKPOINT_PREFIX : STEP_SAMPLE_PREFIX; return m_prefix + prefix + std::to_string(m_isample); } bool StepFile::hasModel(std::uint64_t index) const { auto modelIt = tryGetIniValueFullPath(LATENTS_SEC_TAG, LATENTS_PREFIX + std::to_string(index)); return modelIt.first; } std::string StepFile::getModelFileName(std::uint64_t index) const { auto modelIt = tryGetIniValueFullPath(LATENTS_SEC_TAG, LATENTS_PREFIX + std::to_string(index)); if (modelIt.first) return modelIt.second; THROWERROR_ASSERT(!m_extension.empty()); std::string prefix = getStepPrefix(); return prefix + "-U" + std::to_string(index) + "-latents" + m_extension; } bool StepFile::hasLinkMatrix(std::uint32_t mode) const { auto linkMatrixIt = tryGetIniValueFullPath(LINK_MATRICES_SEC_TAG, LINK_MATRIX_PREFIX + std::to_string(mode)); return linkMatrixIt.first; } std::string StepFile::getLinkMatrixFileName(std::uint32_t mode) const { auto linkMatrixIt = tryGetIniValueFullPath(LINK_MATRICES_SEC_TAG, LINK_MATRIX_PREFIX + std::to_string(mode)); if (linkMatrixIt.first) return linkMatrixIt.second; THROWERROR_ASSERT(!m_extension.empty()); std::string prefix = getStepPrefix(); return prefix + "-F" + std::to_string(mode) + "-link" + m_extension; } bool StepFile::hasPred() const { auto predIt = tryGetIniValueFullPath(PRED_SEC_TAG, PRED_TAG); return predIt.first; } std::string StepFile::getPredFileName() const { auto predIt = tryGetIniValueFullPath(PRED_SEC_TAG, PRED_TAG); if (predIt.first) return predIt.second; std::string prefix = getStepPrefix(); std::string extension = isBinary() ? ".bin" : ".csv"; return prefix + "-predictions" + extension; } std::string StepFile::getPredStateFileName() const { auto predStateIt = tryGetIniValueFullPath(PRED_SEC_TAG, PRED_STATE_TAG); if (predStateIt.first) return predStateIt.second; std::string prefix = getStepPrefix(); return prefix + "-predictions-state.ini"; } //save methods void StepFile::saveModel(std::shared_ptr<const Model> model) const { model->save(shared_from_this()); //save models for (std::uint64_t mIndex = 0; mIndex < model->nmodes(); mIndex++) { std::string path = getModelFileName(mIndex); appendToStepFile(LATENTS_SEC_TAG, LATENTS_PREFIX + std::to_string(mIndex), path); } } void StepFile::savePred(std::shared_ptr<const Result> m_pred) const { if (m_pred->isEmpty()) return; m_pred->save(shared_from_this()); //save predictions appendToStepFile(PRED_SEC_TAG, PRED_TAG, getPredFileName()); appendToStepFile(PRED_SEC_TAG, PRED_STATE_TAG, getPredStateFileName()); } void StepFile::savePriors(const std::vector<std::shared_ptr<ILatentPrior> >& priors) const { std::uint64_t pIndex = 0; for (auto &p : priors) { if (p->save(shared_from_this())) { std::string priorPath = getLinkMatrixFileName(priors.at(pIndex)->getMode()); appendToStepFile(LINK_MATRICES_SEC_TAG, LINK_MATRIX_PREFIX + std::to_string(pIndex), priorPath); } else { appendToStepFile(LINK_MATRICES_SEC_TAG, LINK_MATRIX_PREFIX + std::to_string(pIndex), NONE_TAG); } pIndex++; } } void StepFile::save(std::shared_ptr<const Model> model, std::shared_ptr<const Result> pred, const std::vector<std::shared_ptr<ILatentPrior> >& priors) const { appendToStepFile(GLOBAL_SEC_TAG, IS_CHECKPOINT_TAG, std::to_string(m_checkpoint)); appendToStepFile(GLOBAL_SEC_TAG, NUMBER_TAG, std::to_string(m_isample)); appendToStepFile(GLOBAL_SEC_TAG, NUM_MODES_TAG, std::to_string(model->nmodes())); saveModel(model); savePred(pred); savePriors(priors); } //restore methods void StepFile::restoreModel(std::shared_ptr<Model> model) const { //it is enough to check presence of num tag if (!hasIniValueBase(GLOBAL_SEC_TAG, NUM_MODES_TAG)) return; model->restore(shared_from_this()); int nmodes = model->nmodes(); for(int i=0; i<nmodes; ++i) { auto linkMatrixIt = tryGetIniValueBase(LINK_MATRICES_SEC_TAG, LINK_MATRIX_PREFIX + std::to_string(i)); if (!linkMatrixIt.first || linkMatrixIt.second == "none") continue; std::string path = tryGetIniValueFullPath(LINK_MATRICES_SEC_TAG, LINK_MATRIX_PREFIX + std::to_string(i)).second; THROWERROR_FILE_NOT_EXIST(path); auto beta = std::make_shared<Eigen::MatrixXd>(); matrix_io::eigen::read_matrix(path, *beta); model->setLinkMatrix(i, beta); } } //-- used in PredictSession std::shared_ptr<Model> StepFile::restoreModel() const { auto model = std::make_shared<Model>(); restoreModel(model); return model; } void StepFile::restorePred(std::shared_ptr<Result> m_pred) const { if (!hasIniValueBase(PRED_SEC_TAG, PRED_TAG)) return; if (!hasIniValueBase(PRED_SEC_TAG, PRED_STATE_TAG)) return; m_pred->restore(shared_from_this()); } void StepFile::restorePriors(std::vector<std::shared_ptr<ILatentPrior> >& priors) const { for (auto &p : priors) { p->restore(shared_from_this()); } } void StepFile::restore(std::shared_ptr<Model> model, std::shared_ptr<Result> pred, std::vector<std::shared_ptr<ILatentPrior> >& priors) const { restoreModel(model); restorePred(pred); restorePriors(priors); } //remove methods void StepFile::removeModel() const { std::uint64_t index = 0; while (true) { std::string path = getModelFileName(index++); if (!generic_io::file_exists(path)) break; std::remove(path.c_str()); } std::int32_t nModels = getNModes(); for(std::int32_t i = 0; i < nModels; i++) removeFromStepFile(LATENTS_SEC_TAG, LATENTS_PREFIX + std::to_string(i)); } void StepFile::removePred() const { std::remove(getPredFileName().c_str()); removeFromStepFile(PRED_SEC_TAG, PRED_TAG); std::remove(getPredStateFileName().c_str()); removeFromStepFile(PRED_SEC_TAG, PRED_STATE_TAG); } void StepFile::removePriors() const { std::uint32_t mode = 0; while (true) { std::string path = getLinkMatrixFileName(mode++); if (path == NONE_TAG) break; std::remove(path.c_str()); } for (std::int32_t i = 0; i < getNModes(); i++) removeFromStepFile(LINK_MATRICES_SEC_TAG, LINK_MATRIX_PREFIX + std::to_string(i)); } void StepFile::remove(bool model, bool pred, bool priors) const { if (m_iniReader->empty()) return; //remove all model files if(model) removeModel(); //remove all pred files if(pred) removePred(); //remove all prior files if(priors) removePriors(); // remove [global] header removeFromStepFile(GLOBAL_SEC_TAG, IS_CHECKPOINT_TAG); removeFromStepFile(GLOBAL_SEC_TAG, NUMBER_TAG); removeFromStepFile(GLOBAL_SEC_TAG, NUM_MODES_TAG); //remove step file itself std::remove(getStepFileName().c_str()); THROWERROR_ASSERT_MSG(m_iniReader->empty(), "Unexpected data in step file"); //nullify reader m_iniReader = std::shared_ptr<INIFile>(); } //getters std::int32_t StepFile::getIsample() const { return m_isample; } bool StepFile::isCheckpoint() const { return m_checkpoint; } std::int32_t StepFile::getNModes() const { return std::stoi(getIniValueBase(GLOBAL_SEC_TAG, NUM_MODES_TAG)); } //ini methods std::string StepFile::getIniValueBase(const std::string& section, const std::string& tag) const { THROWERROR_ASSERT_MSG(m_iniReader, "Step ini file is not loaded"); return m_iniReader->get(section, tag); } bool StepFile::hasIniValueBase(const std::string& section, const std::string& tag) const { return tryGetIniValueBase(section, tag).first; } std::pair<bool, std::string> StepFile::tryGetIniValueBase(const std::string& section, const std::string& tag) const { if (m_iniReader) return m_iniReader->tryGet(section, tag); return std::make_pair(false, std::string()); } void StepFile::appendToStepFile(std::string section, std::string tag, std::string value) const { if (m_cur_section != section) { m_iniReader->startSection(section); m_cur_section = section; } value = stripPrefix(value, m_prefix); m_iniReader->appendItem(section, tag, value); flushLast(); } void StepFile::appendCommentToStepFile(std::string comment) const { m_iniReader->appendComment(comment); } void StepFile::removeFromStepFile(std::string section, std::string tag) const { m_iniReader->removeItem(section, tag); } void StepFile::flushLast() const { m_iniReader->flush(); } <commit_msg>FIX: avoid while(true) and correctly check if .ini file has entry<commit_after>#include <SmurffCpp/Utils/StepFile.h> #include <iostream> #include <SmurffCpp/Model.h> #include <SmurffCpp/result.h> #include <SmurffCpp/Priors/ILatentPrior.h> #include <SmurffCpp/Utils/Error.h> #include <SmurffCpp/Utils/StringUtils.h> #include <SmurffCpp/IO/GenericIO.h> #include <SmurffCpp/IO/MatrixIO.h> #define NONE_TAG "none" #define STEP_SAMPLE_PREFIX "sample-" #define STEP_CHECKPOINT_PREFIX "checkpoint-" #define STEP_INI_SUFFIX "-step.ini" #define LATENTS_PREFIX "latents_" #define LINK_MATRIX_PREFIX "link_matrix_" #define GLOBAL_SEC_TAG "global" #define LATENTS_SEC_TAG "latents" #define PRED_SEC_TAG "predictions" #define LINK_MATRICES_SEC_TAG "link_matrices" #define IS_CHECKPOINT_TAG "is_checkpoint" #define NUMBER_TAG "number" #define NUM_MODES_TAG "num_modes" #define PRED_TAG "pred" #define PRED_STATE_TAG "pred_state" using namespace smurff; StepFile::StepFile(std::int32_t isample, std::string prefix, std::string extension, bool create, bool checkpoint) : m_isample(isample), m_prefix(prefix), m_extension(extension), m_checkpoint(checkpoint) { if (create) { THROWERROR_ASSERT(!m_extension.empty()); m_iniReader = std::make_shared<INIFile>(); m_iniReader->create(getStepFileName()); } else { //load all entries in ini file to be able to go through step file internals m_iniReader = std::make_shared<INIFile>(); m_iniReader->open(getStepFileName()); } } StepFile::StepFile(const std::string& path, std::string prefix, std::string extension) : m_prefix(prefix), m_extension(extension) { //load all entries in ini file to be able to go through step file internals m_iniReader = std::make_shared<INIFile>(); m_iniReader->open(path); m_checkpoint = std::stoi(getIniValueBase(GLOBAL_SEC_TAG, IS_CHECKPOINT_TAG)); m_isample = std::stoi(getIniValueBase(GLOBAL_SEC_TAG, NUMBER_TAG)); } //name methods std::pair<bool, std::string> StepFile::tryGetIniValueFullPath(const std::string &section, const std::string &tag) const { auto pair = tryGetIniValueBase(section, tag); if (pair.first && !startsWith(pair.second, m_prefix)) pair.second = m_prefix + pair.second; return pair; } std::string StepFile::getStepFileName() const { std::string prefix = getStepPrefix(); return prefix + STEP_INI_SUFFIX; } bool StepFile::isBinary() const { THROWERROR_ASSERT(!m_extension.empty()); if (m_extension == ".ddm") { return true; } else { THROWERROR_ASSERT_MSG(m_extension == ".csv", "Invalid save_extension: " + m_extension); } return false; } std::string StepFile::getStepPrefix() const { std::string prefix = m_checkpoint ? STEP_CHECKPOINT_PREFIX : STEP_SAMPLE_PREFIX; return m_prefix + prefix + std::to_string(m_isample); } bool StepFile::hasModel(std::uint64_t index) const { auto modelIt = tryGetIniValueFullPath(LATENTS_SEC_TAG, LATENTS_PREFIX + std::to_string(index)); return modelIt.first; } std::string StepFile::getModelFileName(std::uint64_t index) const { auto modelIt = tryGetIniValueFullPath(LATENTS_SEC_TAG, LATENTS_PREFIX + std::to_string(index)); if (modelIt.first) return modelIt.second; THROWERROR_ASSERT(!m_extension.empty()); std::string prefix = getStepPrefix(); return prefix + "-U" + std::to_string(index) + "-latents" + m_extension; } bool StepFile::hasLinkMatrix(std::uint32_t mode) const { auto linkMatrixIt = tryGetIniValueFullPath(LINK_MATRICES_SEC_TAG, LINK_MATRIX_PREFIX + std::to_string(mode)); return linkMatrixIt.first; } std::string StepFile::getLinkMatrixFileName(std::uint32_t mode) const { auto linkMatrixIt = tryGetIniValueFullPath(LINK_MATRICES_SEC_TAG, LINK_MATRIX_PREFIX + std::to_string(mode)); if (linkMatrixIt.first) return linkMatrixIt.second; THROWERROR_ASSERT(!m_extension.empty()); std::string prefix = getStepPrefix(); return prefix + "-F" + std::to_string(mode) + "-link" + m_extension; } bool StepFile::hasPred() const { auto predIt = tryGetIniValueFullPath(PRED_SEC_TAG, PRED_TAG); return predIt.first; } std::string StepFile::getPredFileName() const { auto predIt = tryGetIniValueFullPath(PRED_SEC_TAG, PRED_TAG); if (predIt.first) return predIt.second; std::string prefix = getStepPrefix(); std::string extension = isBinary() ? ".bin" : ".csv"; return prefix + "-predictions" + extension; } std::string StepFile::getPredStateFileName() const { auto predStateIt = tryGetIniValueFullPath(PRED_SEC_TAG, PRED_STATE_TAG); if (predStateIt.first) return predStateIt.second; std::string prefix = getStepPrefix(); return prefix + "-predictions-state.ini"; } //save methods void StepFile::saveModel(std::shared_ptr<const Model> model) const { model->save(shared_from_this()); //save models for (std::uint64_t mIndex = 0; mIndex < model->nmodes(); mIndex++) { std::string path = getModelFileName(mIndex); appendToStepFile(LATENTS_SEC_TAG, LATENTS_PREFIX + std::to_string(mIndex), path); } } void StepFile::savePred(std::shared_ptr<const Result> m_pred) const { if (m_pred->isEmpty()) return; m_pred->save(shared_from_this()); //save predictions appendToStepFile(PRED_SEC_TAG, PRED_TAG, getPredFileName()); appendToStepFile(PRED_SEC_TAG, PRED_STATE_TAG, getPredStateFileName()); } void StepFile::savePriors(const std::vector<std::shared_ptr<ILatentPrior> >& priors) const { std::uint64_t pIndex = 0; for (auto &p : priors) { if (p->save(shared_from_this())) { std::string priorPath = getLinkMatrixFileName(priors.at(pIndex)->getMode()); appendToStepFile(LINK_MATRICES_SEC_TAG, LINK_MATRIX_PREFIX + std::to_string(pIndex), priorPath); } else { appendToStepFile(LINK_MATRICES_SEC_TAG, LINK_MATRIX_PREFIX + std::to_string(pIndex), NONE_TAG); } pIndex++; } } void StepFile::save(std::shared_ptr<const Model> model, std::shared_ptr<const Result> pred, const std::vector<std::shared_ptr<ILatentPrior> >& priors) const { appendToStepFile(GLOBAL_SEC_TAG, IS_CHECKPOINT_TAG, std::to_string(m_checkpoint)); appendToStepFile(GLOBAL_SEC_TAG, NUMBER_TAG, std::to_string(m_isample)); appendToStepFile(GLOBAL_SEC_TAG, NUM_MODES_TAG, std::to_string(model->nmodes())); saveModel(model); savePred(pred); savePriors(priors); } //restore methods void StepFile::restoreModel(std::shared_ptr<Model> model) const { //it is enough to check presence of num tag if (!hasIniValueBase(GLOBAL_SEC_TAG, NUM_MODES_TAG)) return; model->restore(shared_from_this()); int nmodes = model->nmodes(); for(int i=0; i<nmodes; ++i) { auto linkMatrixIt = tryGetIniValueBase(LINK_MATRICES_SEC_TAG, LINK_MATRIX_PREFIX + std::to_string(i)); if (!linkMatrixIt.first || linkMatrixIt.second == "none") continue; std::string path = tryGetIniValueFullPath(LINK_MATRICES_SEC_TAG, LINK_MATRIX_PREFIX + std::to_string(i)).second; THROWERROR_FILE_NOT_EXIST(path); auto beta = std::make_shared<Eigen::MatrixXd>(); matrix_io::eigen::read_matrix(path, *beta); model->setLinkMatrix(i, beta); } } //-- used in PredictSession std::shared_ptr<Model> StepFile::restoreModel() const { auto model = std::make_shared<Model>(); restoreModel(model); return model; } void StepFile::restorePred(std::shared_ptr<Result> m_pred) const { if (!hasIniValueBase(PRED_SEC_TAG, PRED_TAG)) return; if (!hasIniValueBase(PRED_SEC_TAG, PRED_STATE_TAG)) return; m_pred->restore(shared_from_this()); } void StepFile::restorePriors(std::vector<std::shared_ptr<ILatentPrior> >& priors) const { for (auto &p : priors) { p->restore(shared_from_this()); } } void StepFile::restore(std::shared_ptr<Model> model, std::shared_ptr<Result> pred, std::vector<std::shared_ptr<ILatentPrior> >& priors) const { restoreModel(model); restorePred(pred); restorePriors(priors); } //remove methods void StepFile::removeModel() const { for (std::uint32_t mode = 0; mode < getNModes(); ++mode) { if (!hasModel(mode)) continue; std::string path = getModelFileName(mode); std::remove(path.c_str()); } std::int32_t nModels = getNModes(); for (std::int32_t i = 0; i < nModels; i++) removeFromStepFile(LATENTS_SEC_TAG, LATENTS_PREFIX + std::to_string(i)); } void StepFile::removePred() const { std::remove(getPredFileName().c_str()); removeFromStepFile(PRED_SEC_TAG, PRED_TAG); std::remove(getPredStateFileName().c_str()); removeFromStepFile(PRED_SEC_TAG, PRED_STATE_TAG); } void StepFile::removePriors() const { for (std::uint32_t mode = 0; mode < getNModes(); ++mode) { if (!hasLinkMatrix(mode)) continue; std::string path = getLinkMatrixFileName(mode++); std::remove(path.c_str()); } for (std::int32_t i = 0; i < getNModes(); i++) removeFromStepFile(LINK_MATRICES_SEC_TAG, LINK_MATRIX_PREFIX + std::to_string(i)); } void StepFile::remove(bool model, bool pred, bool priors) const { if (m_iniReader->empty()) return; std::cout << "remove " << getStepFileName() << std::endl; //remove all model files if(model) removeModel(); //remove all pred files if(pred) removePred(); //remove all prior files if(priors) removePriors(); // remove [global] header removeFromStepFile(GLOBAL_SEC_TAG, IS_CHECKPOINT_TAG); removeFromStepFile(GLOBAL_SEC_TAG, NUMBER_TAG); removeFromStepFile(GLOBAL_SEC_TAG, NUM_MODES_TAG); //remove step file itself std::remove(getStepFileName().c_str()); THROWERROR_ASSERT_MSG(m_iniReader->empty(), "Unexpected data in step file"); //nullify reader m_iniReader = std::shared_ptr<INIFile>(); } //getters std::int32_t StepFile::getIsample() const { return m_isample; } bool StepFile::isCheckpoint() const { return m_checkpoint; } std::int32_t StepFile::getNModes() const { return std::stoi(getIniValueBase(GLOBAL_SEC_TAG, NUM_MODES_TAG)); } //ini methods std::string StepFile::getIniValueBase(const std::string& section, const std::string& tag) const { THROWERROR_ASSERT_MSG(m_iniReader, "Step ini file is not loaded"); return m_iniReader->get(section, tag); } bool StepFile::hasIniValueBase(const std::string& section, const std::string& tag) const { return tryGetIniValueBase(section, tag).first; } std::pair<bool, std::string> StepFile::tryGetIniValueBase(const std::string& section, const std::string& tag) const { if (m_iniReader) return m_iniReader->tryGet(section, tag); return std::make_pair(false, std::string()); } void StepFile::appendToStepFile(std::string section, std::string tag, std::string value) const { if (m_cur_section != section) { m_iniReader->startSection(section); m_cur_section = section; } value = stripPrefix(value, m_prefix); m_iniReader->appendItem(section, tag, value); flushLast(); } void StepFile::appendCommentToStepFile(std::string comment) const { m_iniReader->appendComment(comment); } void StepFile::removeFromStepFile(std::string section, std::string tag) const { m_iniReader->removeItem(section, tag); } void StepFile::flushLast() const { m_iniReader->flush(); } <|endoftext|>
<commit_before>/* This file is part of python_mapnik (c++/python mapping toolkit) * Copyright (C) 2005 Artem Pavlenko, Jean-Francois Doyon * * Mapnik is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or any later version. * * This program 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 this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ //$Id: mapnik_layer.cc 17 2005-03-08 23:58:43Z pavlenko $ #include <boost/python.hpp> #include <boost/python/detail/api_placeholder.hpp> #include <boost/python/suite/indexing/vector_indexing_suite.hpp> #include <mapnik.hpp> using mapnik::Layer; using mapnik::parameters; struct layer_pickle_suite : boost::python::pickle_suite { static boost::python::tuple getinitargs(const Layer& l) { using namespace boost::python; return boost::python::make_tuple(l.params()); } static boost::python::tuple getstate(const Layer& l) { using namespace boost::python; std::vector<std::string> const& styles=l.styles(); std::vector<std::string>::const_iterator itr=styles.begin(); boost::python::list py_styles; while (itr!=styles.end()) { py_styles.append(*itr++); } return boost::python::make_tuple(l.getMinZoom(), l.getMaxZoom(), py_styles); } static void setstate (Layer& l, boost::python::tuple state) { using namespace boost::python; if (len(state) != 3) { PyErr_SetObject(PyExc_ValueError, ("expected 3-item tuple in call to __setstate__; got %s" % state).ptr() ); throw_error_already_set(); } l.setMinZoom(extract<double>(state[0])); l.setMaxZoom(extract<double>(state[1])); boost::python::list styles=extract<boost::python::list>(state[2]); for (int i=0;i<len(styles);++i) { l.add_style(extract<std::string>(styles[i])); } } }; namespace { //user-friendly wrapper that uses Python dictionary using namespace boost::python; Layer create_layer(const dict& d) { parameters params; boost::python::list keys=d.keys(); for (int i=0;i<len(keys);++i) { std::string key=extract<std::string>(keys[i]); std::string value=extract<std::string>(d[key]); params[key] = value; } return Layer(params); } } void export_layer() { using namespace boost::python; class_<std::vector<std::string> >("Styles") .def(vector_indexing_suite<std::vector<std::string>,true >()) ; class_<Layer>("Layer","A map layer.",no_init) .def("name",&Layer::name,return_value_policy<copy_const_reference>()) .def("params",&Layer::params,return_value_policy<reference_existing_object>()) .def("envelope",&Layer::envelope) .add_property("minzoom",&Layer::getMinZoom,&Layer::setMinZoom) .add_property("maxzoom",&Layer::getMaxZoom,&Layer::setMaxZoom) .add_property("styles",make_function (&Layer::styles,return_value_policy<reference_existing_object>())) .def_pickle(layer_pickle_suite()) ; def("Layer",&create_layer); } <commit_msg>Changed the layer constructor to use a more pythonic:<commit_after>/* This file is part of python_mapnik (c++/python mapping toolkit) * Copyright (C) 2005 Artem Pavlenko, Jean-Francois Doyon * * Mapnik is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or any later version. * * This program 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 this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ //$Id: mapnik_layer.cc 17 2005-03-08 23:58:43Z pavlenko $ #include <boost/python.hpp> #include <boost/python/detail/api_placeholder.hpp> #include <boost/python/suite/indexing/vector_indexing_suite.hpp> #include <mapnik.hpp> using mapnik::Layer; using mapnik::parameters; struct layer_pickle_suite : boost::python::pickle_suite { static boost::python::tuple getinitargs(const Layer& l) { using namespace boost::python; return boost::python::make_tuple(l.params()); } static boost::python::tuple getstate(const Layer& l) { using namespace boost::python; std::vector<std::string> const& styles=l.styles(); std::vector<std::string>::const_iterator itr=styles.begin(); boost::python::list py_styles; while (itr!=styles.end()) { py_styles.append(*itr++); } return boost::python::make_tuple(l.getMinZoom(), l.getMaxZoom(), py_styles); } static void setstate (Layer& l, boost::python::tuple state) { using namespace boost::python; if (len(state) != 3) { PyErr_SetObject(PyExc_ValueError, ("expected 3-item tuple in call to __setstate__; got %s" % state).ptr() ); throw_error_already_set(); } l.setMinZoom(extract<double>(state[0])); l.setMaxZoom(extract<double>(state[1])); boost::python::list styles=extract<boost::python::list>(state[2]); for (int i=0;i<len(styles);++i) { l.add_style(extract<std::string>(styles[i])); } } }; namespace { using namespace boost::python; Layer create_layer(const char* name, const char* type, const char* file) { parameters params; params["name"] = name; params["type"] = type; params["file"] = file; return Layer(params); } } void export_layer() { using namespace boost::python; class_<std::vector<std::string> >("Styles") .def(vector_indexing_suite<std::vector<std::string>,true >()) ; class_<Layer>("Layer","A map layer.",no_init) .def("name",&Layer::name,return_value_policy<copy_const_reference>()) .def("params",&Layer::params,return_value_policy<reference_existing_object>()) .def("envelope",&Layer::envelope) .add_property("minzoom",&Layer::getMinZoom,&Layer::setMinZoom) .add_property("maxzoom",&Layer::getMaxZoom,&Layer::setMaxZoom) .add_property("styles",make_function (&Layer::styles,return_value_policy<reference_existing_object>())) .def_pickle(layer_pickle_suite()) ; def("Layer",&create_layer); } <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko, Jean-Francois Doyon * * 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 St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id$ #include <boost/python.hpp> #include <boost/python/suite/indexing/vector_indexing_suite.hpp> #include <mapnik/feature_type_style.hpp> using mapnik::feature_type_style; using mapnik::rules; struct style_pickle_suite : boost::python::pickle_suite { static boost::python::tuple getinitargs(const feature_type_style& s) { boost::python::list r; rules::const_iterator it = s.get_rules().begin(); rules::const_iterator end = s.get_rules().end(); for (; it != end; ++it) { r.append( *it ); } return boost::python::make_tuple(r); } }; void export_style() { using namespace boost::python; class_<rules>("Rules",init<>("default ctor")) .def(vector_indexing_suite<rules>()) ; class_<feature_type_style>("Style",init<>("default style constructor")) .def_pickle(style_pickle_suite() ) .add_property("rules",make_function (&feature_type_style::get_rules, return_value_policy<reference_existing_object>())) ; } <commit_msg>fix pickling for styles since they have state and no initial args<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko, Jean-Francois Doyon * * 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 St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id$ #include <boost/python.hpp> #include <boost/python/suite/indexing/vector_indexing_suite.hpp> #include <mapnik/feature_type_style.hpp> using mapnik::feature_type_style; using mapnik::rules; using mapnik::rule_type; struct style_pickle_suite : boost::python::pickle_suite { static boost::python::tuple getstate(const feature_type_style& s) { boost::python::list rule_list; rules::const_iterator it = s.get_rules().begin(); rules::const_iterator end = s.get_rules().end(); for (; it != end; ++it) { rule_list.append( *it ); } return boost::python::make_tuple(rule_list); } static void setstate (feature_type_style& s, boost::python::tuple state) { using namespace boost::python; if (len(state) != 1) { PyErr_SetObject(PyExc_ValueError, ("expected 1-item tuple in call to __setstate__; got %s" % state).ptr() ); throw_error_already_set(); } boost::python::list rules = extract<boost::python::list>(state[0]); for (int i=0; i<len(rules); ++i) { s.add_rule(extract<rule_type>(rules[i])); } } }; void export_style() { using namespace boost::python; class_<rules>("Rules",init<>("default ctor")) .def(vector_indexing_suite<rules>()) ; class_<feature_type_style>("Style",init<>("default style constructor")) .def_pickle(style_pickle_suite() ) .add_property("rules",make_function (&feature_type_style::get_rules, return_value_policy<reference_existing_object>())) ; } <|endoftext|>
<commit_before>// Module: LOG4CPLUS // File: loggingserver.cxx // Created: 5/2003 // Author: Tad E. Smith // // // Copyright (C) Tad E. Smith All rights reserved. // // This software is published under the terms of the Apache Software // License version 1.1, a copy of which has been included with this // distribution in the LICENSE.APL file. // // $Log: not supported by cvs2svn $ // Revision 1.3 2003/05/04 08:43:11 tcsmith // Now takes a port and a config file name as parameters on startup. // // Revision 1.2 2003/05/04 07:39:48 tcsmith // Removed a debug message. // // Revision 1.1 2003/05/04 07:25:16 tcsmith // Initial version. // #include <log4cplus/config.h> #include <log4cplus/configurator.h> #include <log4cplus/consoleappender.h> #include <log4cplus/socketappender.h> #include <log4cplus/helpers/loglog.h> #include <log4cplus/helpers/socket.h> #include <log4cplus/helpers/threads.h> #include <log4cplus/spi/loggingevent.h> #include <iostream> using namespace std; using namespace log4cplus; using namespace log4cplus::helpers; using namespace log4cplus::thread; namespace loggingserver { class ClientThread : public AbstractThread { public: ClientThread(Socket clientsock) : clientsock(clientsock) { cout << "Received a client connection!!!!" << endl; } ~ClientThread() { cout << "Client connection closed." << endl; } virtual void run(); private: Socket clientsock; }; } int main(int argc, char** argv) { if(argc < 3) { cout << "Usage: port config_file" << endl; return 1; } int port = atoi(argv[1]); tstring configFile = LOG4CPLUS_C_STR_TO_TSTRING(argv[2]); PropertyConfigurator config(configFile); config.configure(); ServerSocket serverSocket(port); while(1) { loggingserver::ClientThread *thr = new loggingserver::ClientThread(serverSocket.accept()); thr->start(); } return 0; } //////////////////////////////////////////////////////////////////////////////// // loggingserver::ClientThread implementation //////////////////////////////////////////////////////////////////////////////// void loggingserver::ClientThread::run() { while(1) { if(!clientsock.isOpen()) { return; } SocketBuffer msgSizeBuffer(sizeof(unsigned int)); if(!clientsock.read(msgSizeBuffer)) { return; } unsigned int msgSize = msgSizeBuffer.readInt(); SocketBuffer buffer(msgSize); if(!clientsock.read(buffer)) { return; } spi::InternalLoggingEvent event = readFromBuffer(buffer); Logger logger = Logger::getInstance(event.getLoggerName()); logger.callAppenders(event); } } <commit_msg>Fixed a compilation error on MSVC++ 7.<commit_after>// Module: LOG4CPLUS // File: loggingserver.cxx // Created: 5/2003 // Author: Tad E. Smith // // // Copyright (C) Tad E. Smith All rights reserved. // // This software is published under the terms of the Apache Software // License version 1.1, a copy of which has been included with this // distribution in the LICENSE.APL file. // // $Log: not supported by cvs2svn $ // Revision 1.4 2003/06/23 20:56:43 tcsmith // Modified to support the changes in the spi::InternalLoggingEvent class. // // Revision 1.3 2003/05/04 08:43:11 tcsmith // Now takes a port and a config file name as parameters on startup. // // Revision 1.2 2003/05/04 07:39:48 tcsmith // Removed a debug message. // // Revision 1.1 2003/05/04 07:25:16 tcsmith // Initial version. // #include <log4cplus/config.h> #include <log4cplus/configurator.h> #include <log4cplus/consoleappender.h> #include <log4cplus/socketappender.h> #include <log4cplus/helpers/loglog.h> #include <log4cplus/helpers/socket.h> #include <log4cplus/helpers/threads.h> #include <log4cplus/spi/loggerimpl.h> #include <log4cplus/spi/loggingevent.h> #include <iostream> using namespace std; using namespace log4cplus; using namespace log4cplus::helpers; using namespace log4cplus::thread; namespace loggingserver { class ClientThread : public AbstractThread { public: ClientThread(Socket clientsock) : clientsock(clientsock) { cout << "Received a client connection!!!!" << endl; } ~ClientThread() { cout << "Client connection closed." << endl; } virtual void run(); private: Socket clientsock; }; } int main(int argc, char** argv) { if(argc < 3) { cout << "Usage: port config_file" << endl; return 1; } int port = atoi(argv[1]); tstring configFile = LOG4CPLUS_C_STR_TO_TSTRING(argv[2]); PropertyConfigurator config(configFile); config.configure(); ServerSocket serverSocket(port); while(1) { loggingserver::ClientThread *thr = new loggingserver::ClientThread(serverSocket.accept()); thr->start(); } return 0; } //////////////////////////////////////////////////////////////////////////////// // loggingserver::ClientThread implementation //////////////////////////////////////////////////////////////////////////////// void loggingserver::ClientThread::run() { while(1) { if(!clientsock.isOpen()) { return; } SocketBuffer msgSizeBuffer(sizeof(unsigned int)); if(!clientsock.read(msgSizeBuffer)) { return; } unsigned int msgSize = msgSizeBuffer.readInt(); SocketBuffer buffer(msgSize); if(!clientsock.read(buffer)) { return; } spi::InternalLoggingEvent event = readFromBuffer(buffer); Logger logger = Logger::getInstance(event.getLoggerName()); logger.callAppenders(event); } } <|endoftext|>
<commit_before> #include <tclap/CmdLine.h> #include <iostream> #include <string> using namespace TCLAP; string _orTest; string _testc; string _testd; void parseOptions(int argc, char** argv); int main(int argc, char** argv) { parseOptions(argc,argv); cout << "for A OR B we got : " << _orTest<< endl << "for string C we got : " << _testc << endl << "for string D we got : " << _testd << endl; } void parseOptions(int argc, char** argv) { try { CmdLine cmd("this is a message", ' ', "0.99" ); // // Define arguments // ValueArg<string> atest("a", "aaa", "or test a", true, "homer", "string"); ValueArg<string> btest("b", "bbb", "or test b", true, "homer", "string"); ValueArg<string> ctest("c", "ccc", "c test", true, "homer", "string"); ValueArg<string> dtest("d", "ddd", "d test", false, "homer", "string"); cmd.xorAdd( atest, btest ); cmd.add( ctest ); cmd.add( dtest ); // // Parse the command line. // cmd.parse(argc,argv); // // Set variables // if ( atest.isSet() ) _orTest = atest.getValue(); else if ( btest.isSet() ) _orTest = btest.getValue(); else { cout << "badness" << endl; exit(1); } _testc = ctest.getValue(); _testd = dtest.getValue(); } catch ( ArgException e ) { cout << "ERROR: " << e.error() << " " << e.argId() << endl; } } <commit_msg>prettified<commit_after> #include <tclap/CmdLine.h> #include <iostream> #include <string> using namespace TCLAP; string _orTest; string _testc; string _testd; void parseOptions(int argc, char** argv); int main(int argc, char** argv) { parseOptions(argc,argv); cout << "for A OR B we got : " << _orTest<< endl << "for string C we got : " << _testc << endl << "for string D we got : " << _testd << endl; } void parseOptions(int argc, char** argv) { try { CmdLine cmd("this is a message", ' ', "0.99" ); // // Define arguments // ValueArg<string> atest("a", "aaa", "or test a", true, "homer", "string"); ValueArg<string> btest("b", "bbb", "or test b", true, "homer", "string"); ValueArg<string> ctest("c", "ccc", "c test", true, "homer", "string"); ValueArg<string> dtest("d", "ddd", "d test", false, "homer", "string"); cmd.xorAdd( atest, btest ); cmd.add( ctest ); cmd.add( dtest ); // // Parse the command line. // cmd.parse(argc,argv); // // Set variables // if ( atest.isSet() ) _orTest = atest.getValue(); else if ( btest.isSet() ) _orTest = btest.getValue(); else // Should never get here because TCLAP will note that one of the // required args above has not been set. throw("very bad things..."); _testc = ctest.getValue(); _testd = dtest.getValue(); } catch ( ArgException e ) { cout << "ERROR: " << e.error() << " " << e.argId() << endl; } } <|endoftext|>
<commit_before>// this file defines the itkBasicFiltersTest for the test driver // and all it expects is that you have a function called RegisterTests #include "itkTestMain.h" void RegisterTests() { REGISTER_TEST(itkAlgorithmsPrintTest ); REGISTER_TEST(itkAlgorithmsPrintTest2 ); REGISTER_TEST(itkAlgorithmsPrintTest3 ); REGISTER_TEST(itkAntiAliasBinaryImageFilterTest ); REGISTER_TEST(itkAutomaticTopologyMeshSourceTest ); REGISTER_TEST(itkAnisotropicFourthOrderLevelSetImageFilterTest ); REGISTER_TEST(itkAntiAliasBinaryImageFilterTest ); REGISTER_TEST(itkBinaryMinMaxCurvatureFlowImageFilterTest ); REGISTER_TEST(itkBinaryMask3DMeshSourceTest ); REGISTER_TEST(itkBioGeneTest ); REGISTER_TEST(itkBioGeneNetworkTest ); REGISTER_TEST(itkCannySegmentationLevelSetImageFilterTest ); REGISTER_TEST(itkCorrelationCoefficientHistogramImageToImageMetricTest ); REGISTER_TEST(itkCurvatureFlowTest ); REGISTER_TEST(itkCurvesLevelSetImageFilterTest ); REGISTER_TEST(itkDemonsRegistrationFilterTest ); REGISTER_TEST(itkExtensionVelocitiesImageFilterTest ); REGISTER_TEST(itkExtractMeshConnectedRegionsTest ); REGISTER_TEST(itkFastChamferDistanceImageFilterTest ); REGISTER_TEST(itkFastMarchingTest ); REGISTER_TEST(itkFastMarchingExtensionImageFilterTest ); //REGISTER_TEST(itkFEMRegistrationFilterTest ); REGISTER_TEST(itkGeodesicActiveContourLevelSetImageFilterTest ); REGISTER_TEST(itkGeodesicActiveContourShapePriorLevelSetImageFilterTest ); REGISTER_TEST(itkGeodesicActiveContourShapePriorLevelSetImageFilterTest_2 ); REGISTER_TEST(itkGradientVectorFlowImageFilterTest ); REGISTER_TEST(itkSimpleFuzzyConnectednessScalarImageFilterTest ); REGISTER_TEST(itkHistogramMatchingImageFilterTest ); REGISTER_TEST(itkHistogramImageToImageMetricTest ); REGISTER_TEST(itkImageMomentsTest ); REGISTER_TEST(itkImagePCAShapeModelEstimatorTest); REGISTER_TEST(itkImageRegistrationMethodTest ); REGISTER_TEST(itkImageRegistrationMethodTest_1 ); REGISTER_TEST(itkImageRegistrationMethodTest_2 ); REGISTER_TEST(itkImageRegistrationMethodTest_3 ); REGISTER_TEST(itkImageRegistrationMethodTest_4 ); REGISTER_TEST(itkImageRegistrationMethodTest_5 ); REGISTER_TEST(itkImageRegistrationMethodTest_6 ); REGISTER_TEST(itkImageRegistrationMethodTest_7 ); REGISTER_TEST(itkImageRegistrationMethodTest_8 ); REGISTER_TEST(itkImageRegistrationMethodTest_9 ); REGISTER_TEST(itkImageRegistrationMethodTest_10); REGISTER_TEST(itkImageRegistrationMethodTest_11); REGISTER_TEST(itkImageRegistrationMethodTest_12); REGISTER_TEST(itkImageRegistrationMethodTest_13); REGISTER_TEST(itkImageRegistrationMethodTest_14); REGISTER_TEST(itkImageRegistrationMethodTest_15); REGISTER_TEST(itkImageRegistrationMethodTest_16); REGISTER_TEST(itkInterpolateTest ); REGISTER_TEST(itkIsotropicFourthOrderLevelSetImageFilterTest ); REGISTER_TEST(itkIsoContourDistanceImageFilterTest ); REGISTER_TEST(itkKalmanLinearEstimatorTest ); REGISTER_TEST(itkKmeansModelEstimatorTest ); REGISTER_TEST(itkLaplacianSegmentationLevelSetImageFilterTest ); REGISTER_TEST(itkLevelSetNeighborhoodExtractorTest ); REGISTER_TEST(itkLevelSetVelocityNeighborhoodExtractorTest ); REGISTER_TEST(itkMattesMutualInformationImageToImageMetricTest ); REGISTER_TEST(itkMeanSquaresImageMetricTest ); REGISTER_TEST(itkMeanSquaresHistogramImageToImageMetricTest ); REGISTER_TEST(itkMinMaxCurvatureFlowImageFilterTest ); REGISTER_TEST(itkMRFImageFilterTest ); REGISTER_TEST(itkMRIBiasFieldCorrectionFilterTest ); REGISTER_TEST(itkMultiResolutionPyramidImageFilterTest ); REGISTER_TEST(itkRecursiveMultiResolutionPyramidImageFilterTest ); REGISTER_TEST(itkMultiResolutionPDEDeformableRegistrationTest ); REGISTER_TEST(itkMultiResolutionImageRegistrationMethodTest); REGISTER_TEST(itkMultiResolutionImageRegistrationMethodTest_1 ); REGISTER_TEST(itkMultiResolutionImageRegistrationMethodTest_2 ); REGISTER_TEST(itkMutualInformationHistogramImageToImageMetricTest ); REGISTER_TEST(itkMutualInformationMetricTest ); REGISTER_TEST(itkNarrowBandCurvesLevelSetImageFilterTest ); REGISTER_TEST(itkNarrowBandThresholdSegmentationLevelSetImageFilterTest ); REGISTER_TEST(itkNewTest ); REGISTER_TEST(itkNormalizedCorrelationImageMetricTest ); REGISTER_TEST(itkNormalizedCorrelationPointSetToImageMetricTest ); REGISTER_TEST(itkMeanSquaresPointSetToImageMetricTest ); REGISTER_TEST(itkNormalizedMutualInformationHistogramImageToImageMetricTest ); REGISTER_TEST(itkOtsuThresholdImageCalculatorTest ); REGISTER_TEST(itkOrthogonalSwath2DPathFilterTest ); REGISTER_TEST(itkMeanReciprocalSquareDifferenceImageMetricTest ); REGISTER_TEST(itkPointSetToImageRegistrationTest_1 ); REGISTER_TEST(itkRegionGrow2DTest ); REGISTER_TEST(itkReinitializeLevelSetImageFilterTest ); REGISTER_TEST(itkShapeDetectionLevelSetImageFilterTest ); REGISTER_TEST(itkShapePriorMAPCostFunctionTest ); REGISTER_TEST(itkShapePriorSegmentationLevelSetFunctionTest ); REGISTER_TEST(itkSpatialObjectToImageRegistrationTest ); REGISTER_TEST(itkSupervisedImageClassifierTest); REGISTER_TEST(itkSwathChainCodePathFilterTest); REGISTER_TEST(itkGibbsTest ); REGISTER_TEST(itkDeformableTest ); REGISTER_TEST(itk2DDeformableTest ); REGISTER_TEST(itkSphereMeshSourceTest ); REGISTER_TEST(itkUnsharpMaskLevelSetImageFilterTest ); REGISTER_TEST(itkThresholdSegmentationLevelSetImageFilterTest ); } <commit_msg>ENH: FEMRegistrationFilter test uncommented now.<commit_after>// this file defines the itkBasicFiltersTest for the test driver // and all it expects is that you have a function called RegisterTests #include "itkTestMain.h" void RegisterTests() { REGISTER_TEST(itkAlgorithmsPrintTest ); REGISTER_TEST(itkAlgorithmsPrintTest2 ); REGISTER_TEST(itkAlgorithmsPrintTest3 ); REGISTER_TEST(itkAntiAliasBinaryImageFilterTest ); REGISTER_TEST(itkAutomaticTopologyMeshSourceTest ); REGISTER_TEST(itkAnisotropicFourthOrderLevelSetImageFilterTest ); REGISTER_TEST(itkAntiAliasBinaryImageFilterTest ); REGISTER_TEST(itkBinaryMinMaxCurvatureFlowImageFilterTest ); REGISTER_TEST(itkBinaryMask3DMeshSourceTest ); REGISTER_TEST(itkBioGeneTest ); REGISTER_TEST(itkBioGeneNetworkTest ); REGISTER_TEST(itkCannySegmentationLevelSetImageFilterTest ); REGISTER_TEST(itkCorrelationCoefficientHistogramImageToImageMetricTest ); REGISTER_TEST(itkCurvatureFlowTest ); REGISTER_TEST(itkCurvesLevelSetImageFilterTest ); REGISTER_TEST(itkDemonsRegistrationFilterTest ); REGISTER_TEST(itkExtensionVelocitiesImageFilterTest ); REGISTER_TEST(itkExtractMeshConnectedRegionsTest ); REGISTER_TEST(itkFastChamferDistanceImageFilterTest ); REGISTER_TEST(itkFastMarchingTest ); REGISTER_TEST(itkFastMarchingExtensionImageFilterTest ); REGISTER_TEST(itkFEMRegistrationFilterTest ); REGISTER_TEST(itkGeodesicActiveContourLevelSetImageFilterTest ); REGISTER_TEST(itkGeodesicActiveContourShapePriorLevelSetImageFilterTest ); REGISTER_TEST(itkGeodesicActiveContourShapePriorLevelSetImageFilterTest_2 ); REGISTER_TEST(itkGradientVectorFlowImageFilterTest ); REGISTER_TEST(itkSimpleFuzzyConnectednessScalarImageFilterTest ); REGISTER_TEST(itkHistogramMatchingImageFilterTest ); REGISTER_TEST(itkHistogramImageToImageMetricTest ); REGISTER_TEST(itkImageMomentsTest ); REGISTER_TEST(itkImagePCAShapeModelEstimatorTest); REGISTER_TEST(itkImageRegistrationMethodTest ); REGISTER_TEST(itkImageRegistrationMethodTest_1 ); REGISTER_TEST(itkImageRegistrationMethodTest_2 ); REGISTER_TEST(itkImageRegistrationMethodTest_3 ); REGISTER_TEST(itkImageRegistrationMethodTest_4 ); REGISTER_TEST(itkImageRegistrationMethodTest_5 ); REGISTER_TEST(itkImageRegistrationMethodTest_6 ); REGISTER_TEST(itkImageRegistrationMethodTest_7 ); REGISTER_TEST(itkImageRegistrationMethodTest_8 ); REGISTER_TEST(itkImageRegistrationMethodTest_9 ); REGISTER_TEST(itkImageRegistrationMethodTest_10); REGISTER_TEST(itkImageRegistrationMethodTest_11); REGISTER_TEST(itkImageRegistrationMethodTest_12); REGISTER_TEST(itkImageRegistrationMethodTest_13); REGISTER_TEST(itkImageRegistrationMethodTest_14); REGISTER_TEST(itkImageRegistrationMethodTest_15); REGISTER_TEST(itkImageRegistrationMethodTest_16); REGISTER_TEST(itkInterpolateTest ); REGISTER_TEST(itkIsotropicFourthOrderLevelSetImageFilterTest ); REGISTER_TEST(itkIsoContourDistanceImageFilterTest ); REGISTER_TEST(itkKalmanLinearEstimatorTest ); REGISTER_TEST(itkKmeansModelEstimatorTest ); REGISTER_TEST(itkLaplacianSegmentationLevelSetImageFilterTest ); REGISTER_TEST(itkLevelSetNeighborhoodExtractorTest ); REGISTER_TEST(itkLevelSetVelocityNeighborhoodExtractorTest ); REGISTER_TEST(itkMattesMutualInformationImageToImageMetricTest ); REGISTER_TEST(itkMeanSquaresImageMetricTest ); REGISTER_TEST(itkMeanSquaresHistogramImageToImageMetricTest ); REGISTER_TEST(itkMinMaxCurvatureFlowImageFilterTest ); REGISTER_TEST(itkMRFImageFilterTest ); REGISTER_TEST(itkMRIBiasFieldCorrectionFilterTest ); REGISTER_TEST(itkMultiResolutionPyramidImageFilterTest ); REGISTER_TEST(itkRecursiveMultiResolutionPyramidImageFilterTest ); REGISTER_TEST(itkMultiResolutionPDEDeformableRegistrationTest ); REGISTER_TEST(itkMultiResolutionImageRegistrationMethodTest); REGISTER_TEST(itkMultiResolutionImageRegistrationMethodTest_1 ); REGISTER_TEST(itkMultiResolutionImageRegistrationMethodTest_2 ); REGISTER_TEST(itkMutualInformationHistogramImageToImageMetricTest ); REGISTER_TEST(itkMutualInformationMetricTest ); REGISTER_TEST(itkNarrowBandCurvesLevelSetImageFilterTest ); REGISTER_TEST(itkNarrowBandThresholdSegmentationLevelSetImageFilterTest ); REGISTER_TEST(itkNewTest ); REGISTER_TEST(itkNormalizedCorrelationImageMetricTest ); REGISTER_TEST(itkNormalizedCorrelationPointSetToImageMetricTest ); REGISTER_TEST(itkMeanSquaresPointSetToImageMetricTest ); REGISTER_TEST(itkNormalizedMutualInformationHistogramImageToImageMetricTest ); REGISTER_TEST(itkOtsuThresholdImageCalculatorTest ); REGISTER_TEST(itkOrthogonalSwath2DPathFilterTest ); REGISTER_TEST(itkMeanReciprocalSquareDifferenceImageMetricTest ); REGISTER_TEST(itkPointSetToImageRegistrationTest_1 ); REGISTER_TEST(itkRegionGrow2DTest ); REGISTER_TEST(itkReinitializeLevelSetImageFilterTest ); REGISTER_TEST(itkShapeDetectionLevelSetImageFilterTest ); REGISTER_TEST(itkShapePriorMAPCostFunctionTest ); REGISTER_TEST(itkShapePriorSegmentationLevelSetFunctionTest ); REGISTER_TEST(itkSpatialObjectToImageRegistrationTest ); REGISTER_TEST(itkSupervisedImageClassifierTest); REGISTER_TEST(itkSwathChainCodePathFilterTest); REGISTER_TEST(itkGibbsTest ); REGISTER_TEST(itkDeformableTest ); REGISTER_TEST(itk2DDeformableTest ); REGISTER_TEST(itkSphereMeshSourceTest ); REGISTER_TEST(itkUnsharpMaskLevelSetImageFilterTest ); REGISTER_TEST(itkThresholdSegmentationLevelSetImageFilterTest ); } <|endoftext|>
<commit_before>/*------------------------------------------------------------------------ * (The MIT License) * * Copyright (c) 2008-2011 Rhomobile, Inc. * * 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. * * http://rhomobile.com *------------------------------------------------------------------------*/ #include "common/RhoTime.h" #include "common/RhodesApp.h" namespace rho{ namespace common{ CRhoTimer::CTimerItem::CTimerItem(int nInterval, const char* szCallback, const char* szCallbackData): m_nInterval(nInterval), m_strCallback(szCallback), m_strCallbackData(szCallbackData) { m_oFireTime = CTimeInterval::getCurrentTime(); m_oFireTime.addMillis(nInterval); } unsigned long CRhoTimer::getNextTimeout() { if ( m_arItems.size() == 0 ) return 0; CTimeInterval curTime = CTimeInterval::getCurrentTime(); unsigned long nMinInterval = ((unsigned long)-1); for( int i = 0; i < (int)m_arItems.size(); i++ ) { unsigned long nInterval = 0; if ( m_arItems.elementAt(i).m_oFireTime.toULong() > curTime.toULong() ) nInterval = m_arItems.elementAt(i).m_oFireTime.toULong() - curTime.toULong(); if ( nInterval < nMinInterval ) nMinInterval = nInterval; } if ( nMinInterval < 100 ) nMinInterval = 100; return nMinInterval; } boolean CRhoTimer::checkTimers() { boolean bRet = false; CTimeInterval curTime = CTimeInterval::getCurrentTime(); for( int i = (int)m_arItems.size()-1; i >= 0; i--) { CTimerItem oItem = m_arItems.elementAt(i); if ( curTime.toULong() >= oItem.m_oFireTime.toULong() ) { m_arItems.removeElementAt(i); if ( RHODESAPP().callTimerCallback(oItem.m_strCallback, oItem.m_strCallbackData) ) bRet = true; } } return bRet; } void CRhoTimer::stopTimer(const char* szCallback) { if ( !szCallback || !*szCallback) m_arItems.removeAllElements(); for( int i = (int)m_arItems.size()-1; i >= 0; i--) { CTimerItem oItem = m_arItems.elementAt(i); if ( oItem.m_strCallback.compare(szCallback) == 0 ) { m_arItems.removeElementAt(i); } } } } } <commit_msg>SPR25500/EMBPD00137512fix<commit_after>/*------------------------------------------------------------------------ * (The MIT License) * * Copyright (c) 2008-2011 Rhomobile, Inc. * * 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. * * http://rhomobile.com *------------------------------------------------------------------------*/ #include "common/RhoTime.h" #include "common/RhodesApp.h" namespace rho{ namespace common{ CRhoTimer::CTimerItem::CTimerItem(int nInterval, const char* szCallback, const char* szCallbackData): m_nInterval(nInterval), m_strCallback(szCallback), m_strCallbackData(szCallbackData) { m_oFireTime = CTimeInterval::getCurrentTime(); m_overflow = m_oFireTime.addMillis(nInterval); } unsigned long CRhoTimer::getNextTimeout() { if ( m_arItems.size() == 0 ) return 0; CTimeInterval curTime = CTimeInterval::getCurrentTime(); unsigned long nMinInterval = ((unsigned long)-1); for( int i = 0; i < (int)m_arItems.size(); i++ ) { unsigned long nInterval = 0; if ( m_arItems.elementAt(i).m_oFireTime.toULong() > curTime.toULong() ) { nInterval = m_arItems.elementAt(i).m_oFireTime.toULong() - curTime.toULong(); } else { nInterval=nMinInterval+m_arItems.elementAt(i).m_oFireTime.toULong() - curTime.toULong(); } if ( nInterval < nMinInterval ) nMinInterval = nInterval; } if ( nMinInterval < 100 ) nMinInterval = 100; return nMinInterval; } boolean CRhoTimer::checkTimers() { boolean bRet = false; CTimeInterval curTime = CTimeInterval::getCurrentTime(); for( int i = (int)m_arItems.size()-1; i >= 0; i--) { CTimerItem oItem = m_arItems.elementAt(i); if(oItem.m_overflow==false) { if ( curTime.toULong() >= oItem.m_oFireTime.toULong() ) { m_arItems.removeElementAt(i); if ( RHODESAPP().callTimerCallback(oItem.m_strCallback, oItem.m_strCallbackData) ) bRet = true; } } else { if ( curTime.toULong() >= oItem.m_oFireTime.toULong() ) { if((curTime.toULong()-oItem.m_oFireTime.toULong())<=oItem.m_nInterval) { m_arItems.removeElementAt(i); if ( RHODESAPP().callTimerCallback(oItem.m_strCallback, oItem.m_strCallbackData) ) bRet = true; } } } } return bRet; } void CRhoTimer::stopTimer(const char* szCallback) { if ( !szCallback || !*szCallback) m_arItems.removeAllElements(); for( int i = (int)m_arItems.size()-1; i >= 0; i--) { CTimerItem oItem = m_arItems.elementAt(i); if ( oItem.m_strCallback.compare(szCallback) == 0 ) { m_arItems.removeElementAt(i); } } } } } <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkAffineTransformTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2001 Insight Consortium 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. * The name of the Insight Consortium, nor the names of any consortium members, nor of any contributors, may be used to endorse or promote products derived from this software without specific prior written permission. * Modified source versions must be plainly marked as such, and must not be misrepresented as being the original software. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER 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 AUTHORS 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 <iostream> #include "itkAffineTransform.h" #include "itkImage.h" #include "vnl/vnl_vector_fixed.h" typedef itk::Matrix<double,2,2> MatrixType; typedef itk::Vector<double,2> VectorType; void PrintVector( const VectorType & v ) { for( unsigned int i=0; i<VectorType::VectorDimension; i++) { std::cout << v[i] << ", "; } std::cout << std::endl; } int main( int argc, char *argv[]) { int any = 0; // Any errors detected in testing? MatrixType matrix2; MatrixType inverse2; VectorType vector2; int i, j; /* FIXME: This code exercises most of the methods but doesn't actually check that the results are correct. */ any = 0; std::cout << "The AffineTransform class is still being implemented" << std::endl; /* Create a 2D identity transformation and show its parameters */ typedef itk::Point<double,6> ParametersType; typedef itk::Matrix<double,2,6> JacobianType; typedef itk::AffineTransform<double,2> Affine2DType; Affine2DType::Pointer id2 = Affine2DType::New(); matrix2 = id2->GetMatrix(); vector2 = id2->GetOffset(); std::cout << "Matrix from instantiating an identity transform:" << std::endl << matrix2; std::cout << "Vector from instantiating an identity transform:" << std::endl; PrintVector( vector2 ); /* Create and show a simple 2D transform from given parameters */ matrix2[0][0] = 1; matrix2[0][1] = 2; matrix2[1][0] = 3; matrix2[1][1] = 4; vector2[0] = 5; vector2[1] = 6; Affine2DType::Pointer aff2 = Affine2DType::New(); aff2->SetMatrix( matrix2 ); aff2->SetOffset( vector2 ); for (i = 0; i < 2; i++) { for (j = 0; j < 2; j++) matrix2[i][j] = 0.0; vector2[i] = 0.0; } std::cout << "Instantiation of a given 2D transform:" << std::endl << *aff2; inverse2 = aff2->GetInverse(); std::cout << "Inverse matrix for the given transform:" << std::endl << inverse2; /* Set parameters of a 2D transform */ matrix2[0][0] = 6; matrix2[0][1] = 5; matrix2[1][0] = 4; matrix2[1][1] = 3; vector2[0] = 2; vector2[1] = 1; aff2->SetMatrix(matrix2); aff2->SetOffset(vector2); for (i = 0; i < 2; i++) { for (j = 0; j < 2; j++) matrix2[i][j] = 0.0; vector2[i] = 0.0; } matrix2 = aff2->GetMatrix(); vector2 = aff2->GetOffset(); std::cout << "Setting the matrix in an existing transform:" << std::endl << matrix2; std::cout << "Setting the offset in an existing transform:" << std::endl; PrintVector( vector2 ); /* Try composition of two transformations */ aff2->Compose( aff2 ); std::cout << "Result of a composition:" << std::endl << *aff2; /* Compose with a translation */ VectorType trans; trans[0] = 1; trans[1] = 2; aff2->Translate(trans); std::cout << "Result of a translation:" << std::endl << *aff2; /* Compose with an isotropic scaling */ aff2->Scale(.3, 1); std::cout << "Result of isotropic scaling:" << std::endl << *aff2; /* Compose with an anisotropic scaling */ VectorType scale; scale[0] = .3; scale[1] = .2; aff2->Scale(scale); std::cout << "Result of anisotropic scaling:" << std::endl << *aff2; /* Compose with a general N-D rotation */ aff2->Rotate(0, 1, 0.57, 1); std::cout << "Result of general rotation:" << std::endl << *aff2; /* Compose with a 2-D rotation */ aff2->Rotate(0, 1, -0.57, 1); std::cout << "Result of 2-D rotation:" << std::endl << *aff2; /* Compose with a shear */ aff2->Shear(1, 0, .2); std::cout << "Result of shear:" << std::endl << *aff2; /* Transform a point */ itk::Point<double, 2> u2, v2; u2[0] = 3; u2[1] = 5; v2 = aff2->TransformPoint(u2); std::cout << "Transform a point:" << std::endl << v2[0] << " , " << v2[1] << std::endl; /* Back transform a point */ v2 = aff2->BackTransform(u2); std::cout << "Back transform a point:" << std::endl << v2[0] << " , " << v2[1] << std::endl; /* Transform a vnl_vector */ vnl_vector_fixed<double, 2> x2, y2; x2[0] = 1; x2[1] = 2; y2 = aff2->TransformVector(x2); std::cout << "Transform a vnl_vector:" << std::endl << y2[0] << " , " << y2[1] << std::endl; /* Back transform a vector */ y2 = aff2->BackTransform(x2); std::cout << "Back transform a vnl_vector:" << std::endl << y2[0] << " , " << y2[1] << std::endl; /* Transform a vector */ itk::Vector<double, 2> u3, v3; u3[0] = 3; u3[1] = 5; v3 = aff2->TransformVector(u3); std::cout << "Transform a vector:" << std::endl << v3[0] << " , " << v3[1] << std::endl; /* Back transform a vector */ v3 = aff2->BackTransform(u3); std::cout << "Back transform a vector :" << std::endl << v3[0] << " , " << v3[1] << std::endl; /* Transform a Covariant vector */ itk::Vector<double, 2> u4, v4; u4[0] = 3; u4[1] = 5; v4 = aff2->TransformVector(u4); std::cout << "Transform a Covariant vector:" << std::endl << v4[0] << " , " << v4[1] << std::endl; /* Back transform a vector */ v4 = aff2->BackTransform(u4); std::cout << "Back transform a vector :" << std::endl << v4[0] << " , " << v4[1] << std::endl; /* Create a 3D transform and rotate in 3D */ typedef itk::AffineTransform<double,3> Affine3DType; Affine3DType::Pointer aff3 = Affine3DType::New(); itk::Vector<double,3> axis; axis[0] = .707; axis[1] = .707; axis[2] = .707; aff3->Rotate3D(axis, 1.0, 1); std::cout << "Create and rotate a 3D transform:" << std::endl << *aff3; /* Generate inverse transform */ Affine3DType::Pointer inv3; inv3 = aff3->Inverse(); std::cout << "Create an inverse transformation:" << std::endl << inv3; /* Create an image for testing index<->physical transforms */ std::cout << "Creating image for testing index<->physical transforms" << std::endl; double spacing[3] = {1.0, 2.0, 3.0}; double origin [3] = {4.0, 5.0, 6.0}; itk::Image<unsigned char, 3>::Pointer image =itk::Image<unsigned char, 3>::New(); image->SetOrigin (origin); image->SetSpacing(spacing); /* Generate index-to-physical transform */ Affine3DType::Pointer i2p = image->GetIndexToPhysicalTransform(); std::cout << "Index to physical transformation:" << std::endl; std::cout << *i2p << std::endl; /* Generate physical-to-index transform */ Affine3DType::Pointer p2i = image->GetPhysicalToIndexTransform(); std::cout << "Physical to index transformation:" << std::endl; std::cout << *p2i << std::endl; return any; } <commit_msg>FIX: The template function operator<<(ostream) is not recognized by VC++, PrintSelf( std::cout ) is now used instead.<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkAffineTransformTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2001 Insight Consortium 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. * The name of the Insight Consortium, nor the names of any consortium members, nor of any contributors, may be used to endorse or promote products derived from this software without specific prior written permission. * Modified source versions must be plainly marked as such, and must not be misrepresented as being the original software. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER 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 AUTHORS 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 <iostream> #include "itkAffineTransform.h" #include "itkImage.h" #include "vnl/vnl_vector_fixed.h" typedef itk::Matrix<double,2,2> MatrixType; typedef itk::Vector<double,2> VectorType; void PrintVector( const VectorType & v ) { for( unsigned int i=0; i<VectorType::VectorDimension; i++) { std::cout << v[i] << ", "; } std::cout << std::endl; } int main( int argc, char *argv[]) { int any = 0; // Any errors detected in testing? MatrixType matrix2; MatrixType inverse2; VectorType vector2; int i, j; /* FIXME: This code exercises most of the methods but doesn't actually check that the results are correct. */ any = 0; std::cout << "The AffineTransform class is still being implemented" << std::endl; /* Create a 2D identity transformation and show its parameters */ typedef itk::Point<double,6> ParametersType; typedef itk::Matrix<double,2,6> JacobianType; typedef itk::AffineTransform<double,2> Affine2DType; Affine2DType::Pointer id2 = Affine2DType::New(); matrix2 = id2->GetMatrix(); vector2 = id2->GetOffset(); std::cout << "Matrix from instantiating an identity transform:" << std::endl << matrix2; std::cout << "Vector from instantiating an identity transform:" << std::endl; PrintVector( vector2 ); /* Create and show a simple 2D transform from given parameters */ matrix2[0][0] = 1; matrix2[0][1] = 2; matrix2[1][0] = 3; matrix2[1][1] = 4; vector2[0] = 5; vector2[1] = 6; Affine2DType::Pointer aff2 = Affine2DType::New(); aff2->SetMatrix( matrix2 ); aff2->SetOffset( vector2 ); for (i = 0; i < 2; i++) { for (j = 0; j < 2; j++) matrix2[i][j] = 0.0; vector2[i] = 0.0; } std::cout << "Instantiation of a given 2D transform:" << std::endl; aff2->PrintSelf( std::cout ); inverse2 = aff2->GetInverse(); std::cout << "Inverse matrix for the given transform:" << std::endl << inverse2; /* Set parameters of a 2D transform */ matrix2[0][0] = 6; matrix2[0][1] = 5; matrix2[1][0] = 4; matrix2[1][1] = 3; vector2[0] = 2; vector2[1] = 1; aff2->SetMatrix(matrix2); aff2->SetOffset(vector2); for (i = 0; i < 2; i++) { for (j = 0; j < 2; j++) matrix2[i][j] = 0.0; vector2[i] = 0.0; } matrix2 = aff2->GetMatrix(); vector2 = aff2->GetOffset(); std::cout << "Setting the matrix in an existing transform:" << std::endl << matrix2; std::cout << "Setting the offset in an existing transform:" << std::endl; PrintVector( vector2 ); /* Try composition of two transformations */ aff2->Compose( aff2 ); std::cout << "Result of a composition:" << std::endl; aff2->PrintSelf( std::cout ); /* Compose with a translation */ VectorType trans; trans[0] = 1; trans[1] = 2; aff2->Translate(trans); std::cout << "Result of a translation:" << std::endl; aff2->PrintSelf( std::cout ); /* Compose with an isotropic scaling */ aff2->Scale(.3, 1); std::cout << "Result of isotropic scaling:" << std::endl; aff2->PrintSelf( std::cout ); /* Compose with an anisotropic scaling */ VectorType scale; scale[0] = .3; scale[1] = .2; aff2->Scale(scale); std::cout << "Result of anisotropic scaling:" << std::endl; aff2->PrintSelf( std::cout ); /* Compose with a general N-D rotation */ aff2->Rotate(0, 1, 0.57, 1); std::cout << "Result of general rotation:" << std::endl; aff2->PrintSelf( std::cout ); /* Compose with a 2-D rotation */ aff2->Rotate(0, 1, -0.57, 1); std::cout << "Result of 2-D rotation:" << std::endl; aff2->PrintSelf( std::cout ); /* Compose with a shear */ aff2->Shear(1, 0, .2); std::cout << "Result of shear:" << std::endl; aff2->PrintSelf( std::cout ); /* Transform a point */ itk::Point<double, 2> u2, v2; u2[0] = 3; u2[1] = 5; v2 = aff2->TransformPoint(u2); std::cout << "Transform a point:" << std::endl << v2[0] << " , " << v2[1] << std::endl; /* Back transform a point */ v2 = aff2->BackTransform(u2); std::cout << "Back transform a point:" << std::endl << v2[0] << " , " << v2[1] << std::endl; /* Transform a vnl_vector */ vnl_vector_fixed<double, 2> x2, y2; x2[0] = 1; x2[1] = 2; y2 = aff2->TransformVector(x2); std::cout << "Transform a vnl_vector:" << std::endl << y2[0] << " , " << y2[1] << std::endl; /* Back transform a vector */ y2 = aff2->BackTransform(x2); std::cout << "Back transform a vnl_vector:" << std::endl << y2[0] << " , " << y2[1] << std::endl; /* Transform a vector */ itk::Vector<double, 2> u3, v3; u3[0] = 3; u3[1] = 5; v3 = aff2->TransformVector(u3); std::cout << "Transform a vector:" << std::endl << v3[0] << " , " << v3[1] << std::endl; /* Back transform a vector */ v3 = aff2->BackTransform(u3); std::cout << "Back transform a vector :" << std::endl << v3[0] << " , " << v3[1] << std::endl; /* Transform a Covariant vector */ itk::Vector<double, 2> u4, v4; u4[0] = 3; u4[1] = 5; v4 = aff2->TransformVector(u4); std::cout << "Transform a Covariant vector:" << std::endl << v4[0] << " , " << v4[1] << std::endl; /* Back transform a vector */ v4 = aff2->BackTransform(u4); std::cout << "Back transform a vector :" << std::endl << v4[0] << " , " << v4[1] << std::endl; /* Create a 3D transform and rotate in 3D */ typedef itk::AffineTransform<double,3> Affine3DType; Affine3DType::Pointer aff3 = Affine3DType::New(); itk::Vector<double,3> axis; axis[0] = .707; axis[1] = .707; axis[2] = .707; aff3->Rotate3D(axis, 1.0, 1); std::cout << "Create and rotate a 3D transform:" << std::endl << *aff3; /* Generate inverse transform */ Affine3DType::Pointer inv3; inv3 = aff3->Inverse(); std::cout << "Create an inverse transformation:" << std::endl << inv3; /* Create an image for testing index<->physical transforms */ std::cout << "Creating image for testing index<->physical transforms" << std::endl; double spacing[3] = {1.0, 2.0, 3.0}; double origin [3] = {4.0, 5.0, 6.0}; itk::Image<unsigned char, 3>::Pointer image =itk::Image<unsigned char, 3>::New(); image->SetOrigin (origin); image->SetSpacing(spacing); /* Generate index-to-physical transform */ Affine3DType::Pointer i2p = image->GetIndexToPhysicalTransform(); std::cout << "Index to physical transformation:" << std::endl; std::cout << *i2p << std::endl; /* Generate physical-to-index transform */ Affine3DType::Pointer p2i = image->GetPhysicalToIndexTransform(); std::cout << "Physical to index transformation:" << std::endl; std::cout << *p2i << std::endl; return any; } <|endoftext|>
<commit_before>#pragma once #include <string> #include <unordered_map> #include <vector> #include "depthai-shared/common/CameraBoardSocket.hpp" #include "depthai-shared/common/CameraInfo.hpp" #include "depthai-shared/common/Extrinsics.hpp" #include "depthai-shared/common/Point3f.hpp" #include "depthai-shared/common/StereoRectification.hpp" #include "depthai-shared/utility/Serialization.hpp" namespace dai { /** * EepromData structure * * Contains the Calibration and Board data stored on device */ struct EepromData { uint32_t version = 7; std::string productName, boardCustom, boardName, boardRev, boardConf, hardwareConf, batchName; uint64_t batchTime{0}; uint32_t boardBlOptions{0}; std::unordered_map<CameraBoardSocket, CameraInfo> cameraData; StereoRectification stereoRectificationData; Extrinsics imuExtrinsics; std::vector<uint8_t> miscellaneousData; }; DEPTHAI_SERIALIZE_OPTIONAL_EXT(EepromData, version, boardCustom, boardName, boardRev, boardConf, hardwareConf, productName, batchName, batchTime, boardBlOptions, cameraData, stereoRectificationData, imuExtrinsics, miscellaneousData); } // namespace dai <commit_msg>Renamed from boardBlOptions to boardOptions<commit_after>#pragma once #include <string> #include <unordered_map> #include <vector> #include "depthai-shared/common/CameraBoardSocket.hpp" #include "depthai-shared/common/CameraInfo.hpp" #include "depthai-shared/common/Extrinsics.hpp" #include "depthai-shared/common/Point3f.hpp" #include "depthai-shared/common/StereoRectification.hpp" #include "depthai-shared/utility/Serialization.hpp" namespace dai { /** * EepromData structure * * Contains the Calibration and Board data stored on device */ struct EepromData { uint32_t version = 7; std::string productName, boardCustom, boardName, boardRev, boardConf, hardwareConf, batchName; uint64_t batchTime{0}; uint32_t boardOptions{0}; std::unordered_map<CameraBoardSocket, CameraInfo> cameraData; StereoRectification stereoRectificationData; Extrinsics imuExtrinsics; std::vector<uint8_t> miscellaneousData; }; DEPTHAI_SERIALIZE_OPTIONAL_EXT(EepromData, version, boardCustom, boardName, boardRev, boardConf, hardwareConf, productName, batchName, batchTime, boardOptions, cameraData, stereoRectificationData, imuExtrinsics, miscellaneousData); } // namespace dai <|endoftext|>
<commit_before>/* BEGIN_COMMON_COPYRIGHT_HEADER * (c)LGPL2+ * * LXQt - a lightweight, Qt based, desktop toolset * https://lxqt.org * * Copyright: 2015 LXQt team * Authors: * Dmitriy Zhukov <zjesclean@gmail.com> * * This program or 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 * * END_COMMON_COPYRIGHT_HEADER */ #include <QBoxLayout> #include <QLabel> #include <QDebug> #include <QEvent> #include "kbdstate.h" #include "content.h" Content::Content(bool layoutEnabled): QWidget(), m_layoutEnabled(layoutEnabled) { QBoxLayout *box = new QBoxLayout(QBoxLayout::LeftToRight); box->setContentsMargins(0, 0, 0, 0); box->setSpacing(0); setLayout(box); m_capsLock = new QLabel(tr("C", "Label for CapsLock indicator")); m_capsLock->setObjectName(QStringLiteral("CapsLockLabel")); m_capsLock->setAlignment(Qt::AlignCenter); m_capsLock->setToolTip(tr("CapsLock", "Tooltip for CapsLock indicator")); m_capsLock->installEventFilter(this); layout()->addWidget(m_capsLock); m_numLock = new QLabel(tr("N", "Label for NumLock indicator")); m_numLock->setObjectName(QStringLiteral("NumLockLabel")); m_numLock->setToolTip(tr("NumLock", "Tooltip for NumLock indicator")); m_numLock->setAlignment(Qt::AlignCenter); m_numLock->installEventFilter(this); layout()->addWidget(m_numLock); m_scrollLock = new QLabel(tr("S", "Label for ScrollLock indicator")); m_scrollLock->setObjectName(QStringLiteral("ScrollLockLabel")); m_scrollLock->setToolTip(tr("ScrollLock", "Tooltip for ScrollLock indicator")); m_scrollLock->setAlignment(Qt::AlignCenter); m_scrollLock->installEventFilter(this); layout()->addWidget(m_scrollLock); m_layout = new QLabel; m_layout->setObjectName(QStringLiteral("LayoutLabel")); m_layout->setAlignment(Qt::AlignCenter); m_layout->installEventFilter(this); layout()->addWidget(m_layout); m_layout->setEnabled(false); } Content::~Content() {} bool Content::setup() { m_capsLock->setVisible(Settings::instance().showCapLock()); m_numLock->setVisible(Settings::instance().showNumLock()); m_scrollLock->setVisible(Settings::instance().showScrollLock()); m_layout->setVisible(m_layoutEnabled && Settings::instance().showLayout()); return true; } void Content::layoutChanged(const QString & sym, const QString & name, const QString & variant) { m_layout->setText(sym.toUpper()); QString txt = QStringLiteral("<html><table>\ <tr><td>%1: </td><td>%3</td></tr>\ <tr><td>%2: </td><td>%4</td></tr>\ </table></html>").arg(tr("Layout")).arg(tr("Variant")).arg(name).arg(variant); m_layout->setToolTip(txt); } void Content::modifierStateChanged(Controls mod, bool active) { setEnabled(mod, active); } void Content::setEnabled(Controls cnt, bool enabled) { widget(cnt)->setEnabled(enabled); } QWidget* Content::widget(Controls cnt) const { switch(cnt){ case Caps: return m_capsLock; case Num: return m_numLock; case Scroll: return m_scrollLock; case Layout: return m_layout; } return 0; } bool Content::eventFilter(QObject *object, QEvent *event) { if (event->type() == QEvent::QEvent::MouseButtonRelease) { if (object == m_capsLock) emit controlClicked(Controls::Caps); else if (object == m_numLock) emit controlClicked(Controls::Num); else if (object == m_scrollLock) emit controlClicked(Controls::Scroll); else if(object == m_layout){ emit controlClicked(Controls::Layout); } return true; } return QObject::eventFilter(object, event); } void Content::showHorizontal() { qobject_cast<QBoxLayout*>(layout())->setDirection(QBoxLayout::LeftToRight); } void Content::showVertical() { qobject_cast<QBoxLayout*>(layout())->setDirection(QBoxLayout::TopToBottom); } <commit_msg>kbindicator: Fix eventFilter() logic<commit_after>/* BEGIN_COMMON_COPYRIGHT_HEADER * (c)LGPL2+ * * LXQt - a lightweight, Qt based, desktop toolset * https://lxqt.org * * Copyright: 2015 LXQt team * Authors: * Dmitriy Zhukov <zjesclean@gmail.com> * * This program or 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 * * END_COMMON_COPYRIGHT_HEADER */ #include <QBoxLayout> #include <QLabel> #include <QDebug> #include <QEvent> #include "kbdstate.h" #include "content.h" Content::Content(bool layoutEnabled): QWidget(), m_layoutEnabled(layoutEnabled) { QBoxLayout *box = new QBoxLayout(QBoxLayout::LeftToRight); box->setContentsMargins(0, 0, 0, 0); box->setSpacing(0); setLayout(box); m_capsLock = new QLabel(tr("C", "Label for CapsLock indicator")); m_capsLock->setObjectName(QStringLiteral("CapsLockLabel")); m_capsLock->setAlignment(Qt::AlignCenter); m_capsLock->setToolTip(tr("CapsLock", "Tooltip for CapsLock indicator")); m_capsLock->installEventFilter(this); layout()->addWidget(m_capsLock); m_numLock = new QLabel(tr("N", "Label for NumLock indicator")); m_numLock->setObjectName(QStringLiteral("NumLockLabel")); m_numLock->setToolTip(tr("NumLock", "Tooltip for NumLock indicator")); m_numLock->setAlignment(Qt::AlignCenter); m_numLock->installEventFilter(this); layout()->addWidget(m_numLock); m_scrollLock = new QLabel(tr("S", "Label for ScrollLock indicator")); m_scrollLock->setObjectName(QStringLiteral("ScrollLockLabel")); m_scrollLock->setToolTip(tr("ScrollLock", "Tooltip for ScrollLock indicator")); m_scrollLock->setAlignment(Qt::AlignCenter); m_scrollLock->installEventFilter(this); layout()->addWidget(m_scrollLock); m_layout = new QLabel; m_layout->setObjectName(QStringLiteral("LayoutLabel")); m_layout->setAlignment(Qt::AlignCenter); m_layout->installEventFilter(this); layout()->addWidget(m_layout); m_layout->setEnabled(false); } Content::~Content() {} bool Content::setup() { m_capsLock->setVisible(Settings::instance().showCapLock()); m_numLock->setVisible(Settings::instance().showNumLock()); m_scrollLock->setVisible(Settings::instance().showScrollLock()); m_layout->setVisible(m_layoutEnabled && Settings::instance().showLayout()); return true; } void Content::layoutChanged(const QString & sym, const QString & name, const QString & variant) { m_layout->setText(sym.toUpper()); QString txt = QStringLiteral("<html><table>\ <tr><td>%1: </td><td>%3</td></tr>\ <tr><td>%2: </td><td>%4</td></tr>\ </table></html>").arg(tr("Layout")).arg(tr("Variant")).arg(name).arg(variant); m_layout->setToolTip(txt); } void Content::modifierStateChanged(Controls mod, bool active) { setEnabled(mod, active); } void Content::setEnabled(Controls cnt, bool enabled) { widget(cnt)->setEnabled(enabled); } QWidget* Content::widget(Controls cnt) const { switch(cnt){ case Caps: return m_capsLock; case Num: return m_numLock; case Scroll: return m_scrollLock; case Layout: return m_layout; } return 0; } bool Content::eventFilter(QObject *object, QEvent *event) { if (event->type() == QEvent::QEvent::MouseButtonRelease) { if (object == m_capsLock) emit controlClicked(Controls::Caps); else if (object == m_numLock) emit controlClicked(Controls::Num); else if (object == m_scrollLock) emit controlClicked(Controls::Scroll); else if(object == m_layout){ emit controlClicked(Controls::Layout); } } return QWidget::eventFilter(object, event); } void Content::showHorizontal() { qobject_cast<QBoxLayout*>(layout())->setDirection(QBoxLayout::LeftToRight); } void Content::showVertical() { qobject_cast<QBoxLayout*>(layout())->setDirection(QBoxLayout::TopToBottom); } <|endoftext|>
<commit_before>/* * replicated_object_gate.hpp * * Created on: Dec 25, 2017 * Author: zmij */ #ifndef WIRE_UTIL_REPLICATED_OBJECT_GATE_HPP_ #define WIRE_UTIL_REPLICATED_OBJECT_GATE_HPP_ #include <wire/core/connector.hpp> #include <wire/core/connection.hpp> #include <wire/core/locator.hpp> #include <wire/core/proxy.hpp> #include <wire/errors/not_found.hpp> #include <wire/util/timed_cache.hpp> namespace wire { namespace util { template < typename ProxyType > class replicated_object_gate : public ::std::enable_shared_from_this<replicated_object_gate<ProxyType>> { public: using proxy_type = ProxyType; using prx = ::std::shared_ptr<proxy_type>; using gate_type = replicated_object_gate<proxy_type>; using identity = core::identity; using locator_prx = core::locator_prx; using proxy_callback = core::functional::callback< prx >; using exception_callback = core::functional::exception_callback; public: replicated_object_gate(identity const& ada_id, identity const& obj_id, locator_prx locator) : adapter_id_{ ada_id }, object_id_{ obj_id }, locator_{ locator } {} void random_object( proxy_callback __result, exception_callback __exception ) { using core::reference_data; auto connector = locator_->wire_get_connector(); endpoints_ptr eps = endpoints_; if (!eps) { try { auto ada = locator_->find_adapter(adapter_id_); endpoints_ = ada->wire_get_reference()->data().endpoints; eps = endpoints_; } catch (core::adapter_not_found const&) { } } if (!eps || eps->empty()) { core::functional::report_exception( __exception, core::object_not_found{ object_id_ }); } // Copy the endpoint data now as it can go away while get_connector works auto ep_data = *eps; auto _this = this->shared_from_this(); connector->resolve_connection_async( reference_data{ object_id_, {}, {}, ::std::move(ep_data) }, [_this, __result](core::connection_ptr conn) { auto obj = _this->locator_->wire_get_connector()->make_proxy( reference_data{ _this->object_id_, {}, {}, { conn->remote_endpoint() } } ); __result(core::unchecked_cast<proxy_type>(obj)); }, __exception); } private: using endpoint_list = core::endpoint_list; using endpoints_ptr = ::std::shared_ptr<endpoint_list>; using endpoint_cache = timed_cache< endpoint_list, 10 >; identity const adapter_id_; identity const object_id_; locator_prx locator_; endpoint_cache endpoints_; }; } /* namespace util */ } /* namespace wire */ #endif /* WIRE_UTIL_REPLICATED_OBJECT_GATE_HPP_ */ <commit_msg>Fix segfault on no adapters available<commit_after>/* * replicated_object_gate.hpp * * Created on: Dec 25, 2017 * Author: zmij */ #ifndef WIRE_UTIL_REPLICATED_OBJECT_GATE_HPP_ #define WIRE_UTIL_REPLICATED_OBJECT_GATE_HPP_ #include <wire/core/connector.hpp> #include <wire/core/connection.hpp> #include <wire/core/locator.hpp> #include <wire/core/proxy.hpp> #include <wire/errors/not_found.hpp> #include <wire/util/timed_cache.hpp> namespace wire { namespace util { template < typename ProxyType > class replicated_object_gate : public ::std::enable_shared_from_this<replicated_object_gate<ProxyType>> { public: using proxy_type = ProxyType; using prx = ::std::shared_ptr<proxy_type>; using gate_type = replicated_object_gate<proxy_type>; using identity = core::identity; using locator_prx = core::locator_prx; using proxy_callback = core::functional::callback< prx >; using exception_callback = core::functional::exception_callback; public: replicated_object_gate(identity const& ada_id, identity const& obj_id, locator_prx locator) : adapter_id_{ ada_id }, object_id_{ obj_id }, locator_{ locator } {} void random_object( proxy_callback __result, exception_callback __exception ) { using core::reference_data; auto connector = locator_->wire_get_connector(); endpoints_ptr eps = endpoints_; if (!eps) { try { auto ada = locator_->find_adapter(adapter_id_); endpoints_ = ada->wire_get_reference()->data().endpoints; eps = endpoints_; } catch (core::adapter_not_found const&) { } } if (!eps || eps->empty()) { core::functional::report_exception( __exception, core::object_not_found{ object_id_ }); return; } // Copy the endpoint data now as it can go away while get_connector works auto ep_data = *eps; auto _this = this->shared_from_this(); connector->resolve_connection_async( reference_data{ object_id_, {}, {}, ::std::move(ep_data) }, [_this, __result](core::connection_ptr conn) { auto obj = _this->locator_->wire_get_connector()->make_proxy( reference_data{ _this->object_id_, {}, {}, { conn->remote_endpoint() } } ); __result(core::unchecked_cast<proxy_type>(obj)); }, __exception); } private: using endpoint_list = core::endpoint_list; using endpoints_ptr = ::std::shared_ptr<endpoint_list>; using endpoint_cache = timed_cache< endpoint_list, 10 >; identity const adapter_id_; identity const object_id_; locator_prx locator_; endpoint_cache endpoints_; }; } /* namespace util */ } /* namespace wire */ #endif /* WIRE_UTIL_REPLICATED_OBJECT_GATE_HPP_ */ <|endoftext|>
<commit_before>/* BEGIN_COMMON_COPYRIGHT_HEADER * (c)LGPL2+ * * Razor - a lightweight, Qt based, desktop toolset * http://razor-qt.org * * Copyright: 2012 Razor team * Authors: * Johannes Zellner <webmaster@nebulon.de> * * This program or 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 * * END_COMMON_COPYRIGHT_HEADER */ #include "pulseaudiodevice.h" #include "pulseaudioengine.h" PulseAudioDevice::PulseAudioDevice(PulseAudioDeviceType t, PulseAudioEngine *engine, QObject *parent) : QObject(parent), m_engine(engine), m_volume(0), m_mute(false), m_type(t) { } PulseAudioDevice::~PulseAudioDevice() { } // this is just for setting the internal volume void PulseAudioDevice::setVolumeNoCommit(int volume) { if (m_volume == volume) return; m_volume = volume; emit volumeChanged(m_volume); } void PulseAudioDevice::toggleMute() { m_engine->setMute(this, !m_mute); } void PulseAudioDevice::setMute(bool state) { if (m_mute == state) return; m_mute = state; emit muteChanged(); } void PulseAudioDevice::increaseVolume() { setVolume(volume()+10); } void PulseAudioDevice::decreaseVolume() { setVolume(volume()-10); } // this performs a volume change on the device void PulseAudioDevice::setVolume(int volume) { int tmp = volume; if (tmp < 0) tmp = 0; else if (tmp > (int)PA_VOLUME_UI_MAX) tmp = PA_VOLUME_UI_MAX; if (m_volume == tmp) return; m_volume = tmp; if (m_engine) m_engine->commitDeviceVolume(this); } <commit_msg>panel-volume: qBound is much nicer, thanks for the hint from Alexander Sokolov<commit_after>/* BEGIN_COMMON_COPYRIGHT_HEADER * (c)LGPL2+ * * Razor - a lightweight, Qt based, desktop toolset * http://razor-qt.org * * Copyright: 2012 Razor team * Authors: * Johannes Zellner <webmaster@nebulon.de> * * This program or 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 * * END_COMMON_COPYRIGHT_HEADER */ #include "pulseaudiodevice.h" #include "pulseaudioengine.h" PulseAudioDevice::PulseAudioDevice(PulseAudioDeviceType t, PulseAudioEngine *engine, QObject *parent) : QObject(parent), m_engine(engine), m_volume(0), m_mute(false), m_type(t) { } PulseAudioDevice::~PulseAudioDevice() { } // this is just for setting the internal volume void PulseAudioDevice::setVolumeNoCommit(int volume) { if (m_volume == volume) return; m_volume = volume; emit volumeChanged(m_volume); } void PulseAudioDevice::toggleMute() { m_engine->setMute(this, !m_mute); } void PulseAudioDevice::setMute(bool state) { if (m_mute == state) return; m_mute = state; emit muteChanged(); } void PulseAudioDevice::increaseVolume() { setVolume(volume()+10); } void PulseAudioDevice::decreaseVolume() { setVolume(volume()-10); } // this performs a volume change on the device void PulseAudioDevice::setVolume(int volume) { volume = qBound(0, volume, (int)PA_VOLUME_UI_MAX); if (m_volume == volume) return; m_volume = volume; if (m_engine) m_engine->commitDeviceVolume(this); } <|endoftext|>
<commit_before>#include <iostream> #include <boost/filesystem.hpp> #include <boost/program_options.hpp> #include <opencv2/core.hpp> #include <opencv2/highgui.hpp> #include <opencv2/imgproc.hpp> #include "envitools/EnviUtils.hpp" namespace fs = boost::filesystem; namespace po = boost::program_options; namespace et = envitools; int main(int argc, char* argv[]) { ///// Parse the cmd line ///// fs::path imgPathRed, imgPathGreen, imgPathBlue, outputPath; // clang-format off po::options_description options("Options"); options.add_options() ("help,h","Show this message") ("img-path-red,r",po::value<std::string>()->required(), "File path of image for red channel") ("img-path-green,g",po::value<std::string>()->required(), "File path of image for green channel") ("img-path-blue,b",po::value<std::string>()->required(), "File path of image for blue channel") ("output-file,o",po::value<std::string>()->required(), "Output file path") ("gamma", po::value<float>()->default_value(2.2f), "Gamma for floating point image tone mapping"); // clang-format on // parsedOptions will hold the values of all parsed options as a Map po::variables_map parsedOptions; po::store( po::command_line_parser(argc, argv).options(options).run(), parsedOptions); // show the help message if (parsedOptions.count("help") || argc < 5) { std::cout << options << std::endl; return EXIT_SUCCESS; } // warn of missing options try { po::notify(parsedOptions); } catch (po::error& e) { std::cerr << "ERROR: " << e.what() << std::endl; return EXIT_FAILURE; } // Get input file paths imgPathRed = parsedOptions["img-path-red"].as<std::string>(); imgPathGreen = parsedOptions["img-path-green"].as<std::string>(); imgPathBlue = parsedOptions["img-path-blue"].as<std::string>(); if ((!boost::filesystem::exists(imgPathRed)) || (!boost::filesystem::exists(imgPathGreen)) || (!boost::filesystem::exists(imgPathBlue))) { std::cerr << "ERROR: Input image file path(s) do not exist" << std::endl; return EXIT_FAILURE; } // Get output file path outputPath = parsedOptions["output-file"].as<std::string>(); if (boost::filesystem::exists(outputPath)) { std::cerr << "ERROR: Output file path already exists. Cannot overwrite " "output file." << std::endl; return EXIT_FAILURE; } // Load input images into respective cv::Mat cv::Mat r = cv::imread(imgPathRed.string(), -1); cv::Mat g = cv::imread(imgPathGreen.string(), -1); cv::Mat b = cv::imread(imgPathBlue.string(), -1); std::vector<cv::Mat> imgArr; imgArr.push_back(b); imgArr.push_back(g); imgArr.push_back(r); cv::Mat outImage; // Merge images cv::merge(imgArr, outImage); // Tone map for contrast auto gamma = parsedOptions["gamma"].as<float>(); outImage = et::ToneMap(outImage, gamma); // Write new image to output path cv::imwrite(outputPath.string(), outImage); return 0; } <commit_msg>Tone mapping before merging<commit_after>#include <iostream> #include <boost/filesystem.hpp> #include <boost/program_options.hpp> #include <opencv2/core.hpp> #include <opencv2/highgui.hpp> #include <opencv2/imgproc.hpp> #include "envitools/EnviUtils.hpp" namespace fs = boost::filesystem; namespace po = boost::program_options; namespace et = envitools; int main(int argc, char* argv[]) { ///// Parse the cmd line ///// fs::path imgPathRed, imgPathGreen, imgPathBlue, outputPath; // clang-format off po::options_description options("Options"); options.add_options() ("help,h","Show this message") ("img-path-red,r",po::value<std::string>()->required(), "File path of image for red channel") ("img-path-green,g",po::value<std::string>()->required(), "File path of image for green channel") ("img-path-blue,b",po::value<std::string>()->required(), "File path of image for blue channel") ("output-file,o",po::value<std::string>()->required(), "Output file path") ("gamma", po::value<float>()->default_value(2.2f), "Gamma for floating point image tone mapping"); // clang-format on // parsedOptions will hold the values of all parsed options as a Map po::variables_map parsedOptions; po::store( po::command_line_parser(argc, argv).options(options).run(), parsedOptions); // show the help message if (parsedOptions.count("help") || argc < 5) { std::cout << options << std::endl; return EXIT_SUCCESS; } // warn of missing options try { po::notify(parsedOptions); } catch (po::error& e) { std::cerr << "ERROR: " << e.what() << std::endl; return EXIT_FAILURE; } // Get input file paths imgPathRed = parsedOptions["img-path-red"].as<std::string>(); imgPathGreen = parsedOptions["img-path-green"].as<std::string>(); imgPathBlue = parsedOptions["img-path-blue"].as<std::string>(); if ((!boost::filesystem::exists(imgPathRed)) || (!boost::filesystem::exists(imgPathGreen)) || (!boost::filesystem::exists(imgPathBlue))) { std::cerr << "ERROR: Input image file path(s) do not exist" << std::endl; return EXIT_FAILURE; } // Get output file path outputPath = parsedOptions["output-file"].as<std::string>(); if (boost::filesystem::exists(outputPath)) { std::cerr << "ERROR: Output file path already exists. Cannot overwrite " "output file." << std::endl; return EXIT_FAILURE; } // Load input images into respective cv::Mat cv::Mat r = cv::imread(imgPathRed.string(), -1); cv::Mat g = cv::imread(imgPathGreen.string(), -1); cv::Mat b = cv::imread(imgPathBlue.string(), -1); // Tone map for contrast auto gamma = parsedOptions["gamma"].as<float>(); r = et::ToneMap(r, gamma); g = et::ToneMap(g, gamma); b = et::ToneMap(b, gamma); // Merge images std::vector<cv::Mat> imgArr; cv::Mat outImage; imgArr.push_back(b); imgArr.push_back(g); imgArr.push_back(r); cv::merge(imgArr, outImage); // Write new image to output path cv::imwrite(outputPath.string(), outImage); return 0; } <|endoftext|>
<commit_before>/* * * Copyright 2015, Google Inc. * 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 Google Inc. 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. * */ #include <string.h> #include <node.h> #include <nan.h> #include "grpc/grpc.h" #include "grpc/byte_buffer_reader.h" #include "grpc/support/slice.h" #include "byte_buffer.h" namespace grpc { namespace node { using Nan::MaybeLocal; using v8::Function; using v8::Local; using v8::Object; using v8::Number; using v8::Value; grpc_byte_buffer *BufferToByteBuffer(Local<Value> buffer) { Nan::HandleScope scope; int length = ::node::Buffer::Length(buffer); char *data = ::node::Buffer::Data(buffer); grpc_slice slice = grpc_slice_malloc(length); memcpy(GRPC_SLICE_START_PTR(slice), data, length); grpc_byte_buffer *byte_buffer(grpc_raw_byte_buffer_create(&slice, 1)); grpc_slice_unref(slice); return byte_buffer; } namespace { void delete_buffer(char *data, void *hint) { delete[] data; } } Local<Value> ByteBufferToBuffer(grpc_byte_buffer *buffer) { Nan::EscapableHandleScope scope; if (buffer == NULL) { return scope.Escape(Nan::Null()); } grpc_byte_buffer_reader reader; if (!grpc_byte_buffer_reader_init(&reader, buffer)) { Nan::ThrowError("Error initializing byte buffer reader."); return scope.Escape(Nan::Undefined()); } grpc_slice slice = grpc_byte_buffer_reader_readall(&reader); size_t length = GRPC_SLICE_LENGTH(slice); char *result = new char[length]; memcpy(result, GRPC_SLICE_START_PTR(slice), length); grpc_slice_unref(slice); return scope.Escape(MakeFastBuffer( Nan::NewBuffer(result, length, delete_buffer, NULL).ToLocalChecked())); } Local<Value> MakeFastBuffer(Local<Value> slowBuffer) { Nan::EscapableHandleScope scope; Local<Object> globalObj = Nan::GetCurrentContext()->Global(); MaybeLocal<Value> constructorValue = Nan::Get( globalObj, Nan::New("Buffer").ToLocalChecked()); Local<Function> bufferConstructor = Local<Function>::Cast( constructorValue.ToLocalChecked()); const int argc = 3; Local<Value> consArgs[argc] = { slowBuffer, Nan::New<Number>(::node::Buffer::Length(slowBuffer)), Nan::New<Number>(0) }; MaybeLocal<Object> fastBuffer = Nan::NewInstance(bufferConstructor, argc, consArgs); return scope.Escape(fastBuffer.ToLocalChecked()); } } // namespace node } // namespace grpc <commit_msg>Some slice and resource quota updates to UV and Node code<commit_after>/* * * Copyright 2015, Google Inc. * 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 Google Inc. 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. * */ #include <string.h> #include <node.h> #include <nan.h> #include "grpc/grpc.h" #include "grpc/byte_buffer_reader.h" #include "grpc/slice.h" #include "byte_buffer.h" namespace grpc { namespace node { using Nan::MaybeLocal; using v8::Function; using v8::Local; using v8::Object; using v8::Number; using v8::Value; grpc_byte_buffer *BufferToByteBuffer(Local<Value> buffer) { Nan::HandleScope scope; int length = ::node::Buffer::Length(buffer); char *data = ::node::Buffer::Data(buffer); grpc_slice slice = grpc_slice_malloc(length); memcpy(GRPC_SLICE_START_PTR(slice), data, length); grpc_byte_buffer *byte_buffer(grpc_raw_byte_buffer_create(&slice, 1)); grpc_slice_unref(slice); return byte_buffer; } namespace { void delete_buffer(char *data, void *hint) { delete[] data; } } Local<Value> ByteBufferToBuffer(grpc_byte_buffer *buffer) { Nan::EscapableHandleScope scope; if (buffer == NULL) { return scope.Escape(Nan::Null()); } grpc_byte_buffer_reader reader; if (!grpc_byte_buffer_reader_init(&reader, buffer)) { Nan::ThrowError("Error initializing byte buffer reader."); return scope.Escape(Nan::Undefined()); } grpc_slice slice = grpc_byte_buffer_reader_readall(&reader); size_t length = GRPC_SLICE_LENGTH(slice); char *result = new char[length]; memcpy(result, GRPC_SLICE_START_PTR(slice), length); grpc_slice_unref(slice); return scope.Escape(MakeFastBuffer( Nan::NewBuffer(result, length, delete_buffer, NULL).ToLocalChecked())); } Local<Value> MakeFastBuffer(Local<Value> slowBuffer) { Nan::EscapableHandleScope scope; Local<Object> globalObj = Nan::GetCurrentContext()->Global(); MaybeLocal<Value> constructorValue = Nan::Get( globalObj, Nan::New("Buffer").ToLocalChecked()); Local<Function> bufferConstructor = Local<Function>::Cast( constructorValue.ToLocalChecked()); const int argc = 3; Local<Value> consArgs[argc] = { slowBuffer, Nan::New<Number>(::node::Buffer::Length(slowBuffer)), Nan::New<Number>(0) }; MaybeLocal<Object> fastBuffer = Nan::NewInstance(bufferConstructor, argc, consArgs); return scope.Escape(fastBuffer.ToLocalChecked()); } } // namespace node } // namespace grpc <|endoftext|>
<commit_before>/** @file ConnectionSTREAMing.cpp @author Lime Microsystems @brief Implementation of STREAM board connection (streaming API) */ #include "ConnectionSTREAM.h" #include "LMS_StreamBoard.h" #include "StreamerLTE.h" #include "fifo.h" //from StreamerLTE #include <LMS7002M.h> #include <iostream> #include <thread> #include <chrono> #include <algorithm> #include <complex> using namespace lime; #define LTE_CHAN_COUNT 2 #define STREAM_MTU (PacketFrame::maxSamplesInPacket/(LTE_CHAN_COUNT)) /*********************************************************************** * Custom StreamerLTE for streaming API hooks **********************************************************************/ struct USBStreamService : StreamerLTE { USBStreamService( LMS64CProtocol *dataPort, const size_t channelsCount = LTE_CHAN_COUNT, const StreamDataFormat format = STREAM_12_BIT_COMPRESSED ): StreamerLTE(dataPort), mLastRxTimestamp(0), mTimestampOffset(0) { mRxFIFO->Reset(2*4096, channelsCount); mTxFIFO->Reset(2*4096, channelsCount); //switch off Rx uint16_t regVal = Reg_read(dataPort, 0x0005); Reg_write(dataPort, 0x0005, regVal & ~0x6); //enable MIMO mode, 12 bit compressed values if (channelsCount == 2) { Reg_write(dataPort, 0x0001, 0x0003); Reg_write(dataPort, 0x0007, 0x000A); } else { Reg_write(dataPort, 0x0001, 0x0001); Reg_write(dataPort, 0x0007, 0x0008); } //USB FIFO reset //TODO direction specific reset using isTx LMS64CProtocol::GenericPacket ctrPkt; ctrPkt.cmd = CMD_USB_FIFO_RST; ctrPkt.outBuffer.push_back(0x01); dataPort->TransferPacket(ctrPkt); ctrPkt.outBuffer[0] = 0x00; dataPort->TransferPacket(ctrPkt); auto reporter = std::bind(&USBStreamService::handleRxStatus, this, std::placeholders::_1, std::placeholders::_2); auto getRxCmd = std::bind(&ConcurrentQueue<RxCommand>::try_pop, &mRxCmdQueue, std::placeholders::_1); stopRx = false; stopTx = false; StreamerLTE_ThreadData threadRxArgs; threadRxArgs.dataPort = mDataPort; threadRxArgs.FIFO = mRxFIFO; threadRxArgs.terminate = &stopRx; threadRxArgs.dataRate_Bps = &mRxDataRate; threadRxArgs.report = reporter; threadRxArgs.getCmd = getRxCmd; StreamerLTE_ThreadData threadTxArgs; threadTxArgs.dataPort = mDataPort; threadTxArgs.FIFO = mTxFIFO; threadTxArgs.terminate = &stopTx; threadTxArgs.dataRate_Bps = &mTxDataRate; if (format == STREAM_12_BIT_COMPRESSED) { threadRx = std::thread(ReceivePackets, threadRxArgs); threadTx = std::thread(TransmitPackets, threadTxArgs); } else { threadRx = std::thread(ReceivePacketsUncompressed, threadRxArgs); threadTx = std::thread(TransmitPacketsUncompressed, threadTxArgs); } this->start(); } ~USBStreamService(void) { this->stop(); stopRx = true; stopTx = true; threadRx.join(); threadTx.join(); } void start(void) { //switch on Rx auto regVal = Reg_read(mDataPort, 0x0005); bool timeOff = 1 << 5; Reg_write(mDataPort, 0x0005, (regVal & ~0x20) | 0x5 | timeOff); } void stop(void) { //stop Tx Rx if they were active uint32_t regVal = Reg_read(mDataPort, 0x0005); Reg_write(mDataPort, 0x0005, regVal & ~0x6); } void handleRxStatus(const int status, const uint64_t &counter) { if (status == STATUS_FLAG_TIME_UP) { mLastRxTimestamp = counter; return; } StreamMetadata metadata; metadata.hasTimestamp = true; metadata.timestamp = counter + mTimestampOffset; const bool isTx = ((status & STATUS_FLAG_TX_LATE) != 0); metadata.endOfBurst = (status & STATUS_FLAG_RX_END) != 0; metadata.lateTimestamp = (status & STATUS_FLAG_RX_LATE) != 0; metadata.lateTimestamp = (status & STATUS_FLAG_TX_LATE) != 0; metadata.packetDropped = (status & STATUS_FLAG_RX_DROP) != 0; if (isTx) mTxStatQueue.push(metadata); else mRxStatQueue.push(metadata); } LMS_SamplesFIFO *GetRxFIFO(void) const { return mRxFIFO; } LMS_SamplesFIFO *GetTxFIFO(void) const { return mTxFIFO; } std::atomic<bool> txTimeEnabled; std::atomic<uint64_t> mLastRxTimestamp; std::atomic<int64_t> mTimestampOffset; std::atomic<double> mHwCounterRate; ConcurrentQueue<RxCommand> mRxCmdQueue; ConcurrentQueue<StreamMetadata> mRxStatQueue; ConcurrentQueue<StreamMetadata> mTxStatQueue; }; struct USBStreamServiceChannel { USBStreamServiceChannel(bool isTx, const size_t channelsCount, const bool convertFloat): isTx(isTx), channelsCount(channelsCount), convertFloat(convertFloat) { for (size_t i = 0; i < channelsCount; i++) { FIFOBuffers.push_back(new complex16_t[STREAM_MTU]); } } ~USBStreamServiceChannel(void) { for (size_t i = 0; i < channelsCount; i++) { delete [] FIFOBuffers[i]; } FIFOBuffers.clear(); } const bool isTx; const size_t channelsCount; const bool convertFloat; std::vector<complex16_t *> FIFOBuffers; }; /*********************************************************************** * Streaming API implementation **********************************************************************/ std::string ConnectionSTREAM::SetupStream(size_t &streamID, const StreamConfig &config) { streamID = ~0; //API format check bool convertFloat = false; if (config.format == StreamConfig::STREAM_COMPLEX_FLOAT32) convertFloat = true; else if (config.format == StreamConfig::STREAM_12_BIT_IN_16) convertFloat = false; else return "ConnectionSTREAM::setupStream() only complex floats or int16"; //check channel config //provide a default channel 0 if none specified std::vector<size_t> channels(config.channels); if (channels.empty()) channels.push_back(0); if (channels.size() > 2) return "SoapyIConnection::setupStream() 2 channels max"; if (channels.front() > 1) return "SoapyIConnection::setupStream() channels must be [0, 1]"; if (channels.back() > 1) return "SoapyIConnection::setupStream() channels must be [0, 1]"; bool pos0isA = channels.front() == 0; bool pos1isA = channels.back() == 0; //determine sample positions based on channels auto s0 = pos1isA?LMS7002M::AI:LMS7002M::BI; auto s1 = pos1isA?LMS7002M::AQ:LMS7002M::BQ; auto s2 = pos0isA?LMS7002M::AI:LMS7002M::BI; auto s3 = pos0isA?LMS7002M::AQ:LMS7002M::BQ; //Note: only when FPGA is also in 1-ch mode //if (channels.size() == 1) s0 = s3; //configure LML based on channel config LMS7002M rfic; rfic.SetConnection(this); if (config.isTx) rfic.ConfigureLML_BB2RF(s0, s1, s2, s3); else rfic.ConfigureLML_RF2BB(s0, s1, s2, s3); streamID = size_t(new USBStreamServiceChannel(config.isTx, channels.size(), convertFloat)); return ""; //success } void ConnectionSTREAM::CloseStream(const size_t streamID) { auto *stream = (USBStreamServiceChannel *)streamID; delete stream; } size_t ConnectionSTREAM::GetStreamSize(const size_t streamID) { return STREAM_MTU; } bool ConnectionSTREAM::ControlStream(const size_t streamID, const bool enable, const size_t burstSize, const StreamMetadata &metadata) { auto *stream = (USBStreamServiceChannel *)streamID; if (!stream->isTx) { RxCommand rxCmd; rxCmd.waitForTimestamp = metadata.hasTimestamp; rxCmd.timestamp = metadata.timestamp-mStreamService->mTimestampOffset; rxCmd.finiteRead = metadata.endOfBurst; rxCmd.numSamps = burstSize; mStreamService->mRxCmdQueue.push(rxCmd); } return true; } int ConnectionSTREAM::ReadStream(const size_t streamID, void * const *buffs, const size_t length, const long timeout_ms, StreamMetadata &metadata) { auto *stream = (USBStreamServiceChannel *)streamID; size_t samplesCount = std::min<size_t>(length, STREAM_MTU); complex16_t **popBuffer(nullptr); if (stream->convertFloat) popBuffer = (complex16_t **)stream->FIFOBuffers.data(); else popBuffer = (complex16_t **)buffs; uint32_t fifoFlags = 0; size_t sampsPopped = mStreamService->GetRxFIFO()->pop_samples( popBuffer, samplesCount, stream->channelsCount, &metadata.timestamp, timeout_ms, &fifoFlags); metadata.hasTimestamp = metadata.timestamp != 0; metadata.timestamp += mStreamService->mTimestampOffset; metadata.endOfBurst = (fifoFlags & STATUS_FLAG_RX_END) != 0; samplesCount = (std::min)(samplesCount, sampsPopped); if (stream->convertFloat) { for (size_t i = 0; i < stream->channelsCount; i++) { auto buffIn = stream->FIFOBuffers[i]; auto buffOut = (std::complex<float> *)buffs[i]; for (size_t j = 0; j < samplesCount; j++) { buffOut[j] = std::complex<float>( float(buffIn[j].i)/2048, float(buffIn[j].q)/2048); } } } return samplesCount; } int ConnectionSTREAM::WriteStream(const size_t streamID, const void * const *buffs, const size_t length, const long timeout_ms, const StreamMetadata &metadata) { auto *stream = (USBStreamServiceChannel *)streamID; //set the time enabled register if usage changed //TODO maybe the FPGA should check a flag in the pkt if (mStreamService->txTimeEnabled != metadata.hasTimestamp) { uint32_t regVal; this->ReadRegister(0x0005, regVal); if (metadata.hasTimestamp) regVal &= ~(1 << 5); else regVal |= (1 << 5); this->WriteRegister(0x0005, regVal); mStreamService->txTimeEnabled = metadata.hasTimestamp; } size_t samplesCount = std::min<size_t>(length, STREAM_MTU); const complex16_t **pushBuffer(nullptr); if (stream->convertFloat) { pushBuffer = (const complex16_t **)stream->FIFOBuffers.data(); for (size_t i = 0; i < stream->channelsCount; i++) { auto buffIn = (const std::complex<float> *)buffs[i]; auto bufOut = stream->FIFOBuffers[i]; for (size_t j = 0; j < samplesCount; j++) { bufOut[j].i = int16_t(buffIn[j].real()*2048); bufOut[j].q = int16_t(buffIn[j].imag()*2048); } } } else pushBuffer = (const complex16_t **)buffs; auto ticks = metadata.timestamp - mStreamService->mTimestampOffset; size_t sampsPushed = mStreamService->GetTxFIFO()->push_samples( pushBuffer, samplesCount, stream->channelsCount, metadata.hasTimestamp?ticks:0, timeout_ms); samplesCount = (std::min)(samplesCount, sampsPushed); return samplesCount; } int ConnectionSTREAM::ReadStreamStatus(const size_t streamID, const long timeout_ms, StreamMetadata &metadata) { auto *stream = (USBStreamServiceChannel *)streamID; if (stream->isTx and mStreamService->mTxStatQueue.wait_and_pop(metadata, timeout_ms)) return 0; if (!stream->isTx and mStreamService->mRxStatQueue.wait_and_pop(metadata, timeout_ms)) return 0; return -1; } void ConnectionSTREAM::UpdateExternalDataRate(const size_t channel, const double txRate, const double rxRate) { //std::cout << "LMS_StreamBoard::ConfigurePLL(tx=" << txRate/1e6 << "MHz, rx=" << rxRate/1e6 << "MHz)" << std::endl; LMS_StreamBoard::ConfigurePLL(this, txRate/1e6, rxRate/1e6, 90); if (mStreamService) mStreamService->mHwCounterRate = rxRate; } void ConnectionSTREAM::EnterSelfCalibration(const size_t channel) { if (mStreamService) mStreamService->stop(); } void ConnectionSTREAM::ExitSelfCalibration(const size_t channel) { if (mStreamService) mStreamService->start(); } uint64_t ConnectionSTREAM::GetHardwareTimestamp(void) { return mStreamService->mLastRxTimestamp + mStreamService->mTimestampOffset; } void ConnectionSTREAM::SetHardwareTimestamp(const uint64_t now) { if (not mStreamService) mStreamService.reset(new USBStreamService(this)); mStreamService->mTimestampOffset = int64_t(now)-int64_t(mStreamService->mLastRxTimestamp); } double ConnectionSTREAM::GetHardwareTimestampRate(void) { return mStreamService->mHwCounterRate; } <commit_msg>Ton of stream work around thread start/stop<commit_after>/** @file ConnectionSTREAMing.cpp @author Lime Microsystems @brief Implementation of STREAM board connection (streaming API) */ #include "ConnectionSTREAM.h" #include "LMS_StreamBoard.h" #include "StreamerLTE.h" #include "fifo.h" //from StreamerLTE #include <LMS7002M.h> #include <iostream> #include <thread> #include <chrono> #include <algorithm> #include <complex> using namespace lime; #define LTE_CHAN_COUNT 2 #define STREAM_MTU (PacketFrame::maxSamplesInPacket/(LTE_CHAN_COUNT)) /*********************************************************************** * Custom StreamerLTE for streaming API hooks **********************************************************************/ struct USBStreamService : StreamerLTE { USBStreamService( LMS64CProtocol *dataPort, const size_t channelsCount = LTE_CHAN_COUNT, const StreamDataFormat format = STREAM_12_BIT_COMPRESSED ): StreamerLTE(dataPort), format(format), rxStreamUseCount(1), //always need rx for status reporting txStreamUseCount(0), mTxThread(nullptr), mRxThread(nullptr), rxStreamingContinuous(false), mLastRxTimestamp(0), mTimestampOffset(0), mHwCounterRate(0.0) { mRxFIFO->Reset(2*4096, channelsCount); mTxFIFO->Reset(2*4096, channelsCount); //switch off Rx uint16_t regVal = Reg_read(dataPort, 0x0005); Reg_write(dataPort, 0x0005, regVal & ~0x6); //enable MIMO mode, 12 bit compressed values if (channelsCount == 2) { Reg_write(dataPort, 0x0001, 0x0003); Reg_write(dataPort, 0x0007, 0x000A); } else { Reg_write(dataPort, 0x0001, 0x0001); Reg_write(dataPort, 0x0007, 0x0008); } //USB FIFO reset //TODO direction specific reset using isTx LMS64CProtocol::GenericPacket ctrPkt; ctrPkt.cmd = CMD_USB_FIFO_RST; ctrPkt.outBuffer.push_back(0x01); dataPort->TransferPacket(ctrPkt); ctrPkt.outBuffer[0] = 0x00; dataPort->TransferPacket(ctrPkt); } ~USBStreamService(void) { this->updateThreadState(true); } void updateThreadState(const bool forceStop = false) { auto reporter = std::bind(&USBStreamService::handleRxStatus, this, std::placeholders::_1, std::placeholders::_2); auto getRxCmd = std::bind(&ConcurrentQueue<RxCommand>::try_pop, &mRxCmdQueue, std::placeholders::_1); stopRx = false; stopTx = false; StreamerLTE_ThreadData threadRxArgs; threadRxArgs.dataPort = mDataPort; threadRxArgs.FIFO = mRxFIFO; threadRxArgs.terminate = &stopRx; threadRxArgs.dataRate_Bps = &mRxDataRate; threadRxArgs.report = reporter; threadRxArgs.getCmd = getRxCmd; StreamerLTE_ThreadData threadTxArgs; threadTxArgs.dataPort = mDataPort; threadTxArgs.FIFO = mTxFIFO; threadTxArgs.terminate = &stopTx; threadTxArgs.dataRate_Bps = &mTxDataRate; if (mRxThread == nullptr and rxStreamUseCount != 0 and not forceStop) { //restore stream state continuous if (rxStreamingContinuous) { RxCommand rxCmd; rxCmd.waitForTimestamp = false; rxCmd.timestamp = 0; rxCmd.finiteRead = false; rxCmd.numSamps = 0; mRxCmdQueue.push(rxCmd); } if (format == STREAM_12_BIT_COMPRESSED) { mRxThread = new std::thread(ReceivePackets, threadRxArgs); } else { mRxThread = new std::thread(ReceivePacketsUncompressed, threadRxArgs); } } if (mTxThread == nullptr and txStreamUseCount != 0 and not forceStop) { if (format == STREAM_12_BIT_COMPRESSED) { mTxThread = new std::thread(TransmitPackets, threadTxArgs); } else { mTxThread = new std::thread(TransmitPacketsUncompressed, threadTxArgs); } } if ((forceStop or txStreamUseCount == 0) and mTxThread != nullptr) { stopTx = true; mTxThread->join(); delete mTxThread; mTxThread = nullptr; } if ((forceStop or rxStreamUseCount == 0) and mRxThread != nullptr) { stopRx = true; mRxThread->join(); delete mRxThread; mRxThread = nullptr; } } void start(void) { if (mHwCounterRate == 0.0) return; //not configured //switch on Rx auto regVal = Reg_read(mDataPort, 0x0005); bool timeOff = 1 << 5; Reg_write(mDataPort, 0x0005, (regVal & ~0x20) | 0x5 | timeOff); this->updateThreadState(); } void stop(void) { //stop Tx Rx if they were active uint32_t regVal = Reg_read(mDataPort, 0x0005); Reg_write(mDataPort, 0x0005, regVal & ~0x6); this->updateThreadState(true); } void handleRxStatus(const int status, const uint64_t &counter) { if (status == STATUS_FLAG_TIME_UP) { if (counter < mLastRxTimestamp) std::cerr << "C"; mLastRxTimestamp = counter; return; } StreamMetadata metadata; metadata.hasTimestamp = true; metadata.timestamp = counter + mTimestampOffset; const bool isTx = ((status & STATUS_FLAG_TX_LATE) != 0); metadata.endOfBurst = (status & STATUS_FLAG_RX_END) != 0; metadata.lateTimestamp = (status & STATUS_FLAG_RX_LATE) != 0; metadata.lateTimestamp = (status & STATUS_FLAG_TX_LATE) != 0; metadata.packetDropped = (status & STATUS_FLAG_RX_DROP) != 0; if (isTx) mTxStatQueue.push(metadata); else mRxStatQueue.push(metadata); } LMS_SamplesFIFO *GetRxFIFO(void) const { return mRxFIFO; } LMS_SamplesFIFO *GetTxFIFO(void) const { return mTxFIFO; } const StreamDataFormat format; std::atomic<int> rxStreamUseCount; std::atomic<int> txStreamUseCount; std::thread *mTxThread; std::thread *mRxThread; //! was the last rx command for continuous streaming? //! this lets us restore streaming after calibration std::atomic<bool> rxStreamingContinuous; std::atomic<bool> txTimeEnabled; std::atomic<uint64_t> mLastRxTimestamp; std::atomic<int64_t> mTimestampOffset; std::atomic<double> mHwCounterRate; ConcurrentQueue<RxCommand> mRxCmdQueue; ConcurrentQueue<StreamMetadata> mRxStatQueue; ConcurrentQueue<StreamMetadata> mTxStatQueue; }; struct USBStreamServiceChannel { USBStreamServiceChannel(bool isTx, const size_t channelsCount, const bool convertFloat): isTx(isTx), channelsCount(channelsCount), convertFloat(convertFloat) { for (size_t i = 0; i < channelsCount; i++) { FIFOBuffers.push_back(new complex16_t[STREAM_MTU]); } } ~USBStreamServiceChannel(void) { for (size_t i = 0; i < channelsCount; i++) { delete [] FIFOBuffers[i]; } FIFOBuffers.clear(); } const bool isTx; const size_t channelsCount; const bool convertFloat; std::vector<complex16_t *> FIFOBuffers; }; /*********************************************************************** * Streaming API implementation **********************************************************************/ std::string ConnectionSTREAM::SetupStream(size_t &streamID, const StreamConfig &config) { streamID = ~0; //API format check bool convertFloat = false; if (config.format == StreamConfig::STREAM_COMPLEX_FLOAT32) convertFloat = true; else if (config.format == StreamConfig::STREAM_12_BIT_IN_16) convertFloat = false; else return "ConnectionSTREAM::setupStream() only complex floats or int16"; //check channel config //provide a default channel 0 if none specified std::vector<size_t> channels(config.channels); if (channels.empty()) channels.push_back(0); if (channels.size() > 2) return "SoapyIConnection::setupStream() 2 channels max"; if (channels.front() > 1) return "SoapyIConnection::setupStream() channels must be [0, 1]"; if (channels.back() > 1) return "SoapyIConnection::setupStream() channels must be [0, 1]"; bool pos0isA = channels.front() == 0; bool pos1isA = channels.back() == 0; //determine sample positions based on channels auto s0 = pos1isA?LMS7002M::AI:LMS7002M::BI; auto s1 = pos1isA?LMS7002M::AQ:LMS7002M::BQ; auto s2 = pos0isA?LMS7002M::AI:LMS7002M::BI; auto s3 = pos0isA?LMS7002M::AQ:LMS7002M::BQ; //Note: only when FPGA is also in 1-ch mode //if (channels.size() == 1) s0 = s3; //configure LML based on channel config LMS7002M rfic; rfic.SetConnection(this); if (config.isTx) rfic.ConfigureLML_BB2RF(s0, s1, s2, s3); else rfic.ConfigureLML_RF2BB(s0, s1, s2, s3); if (config.isTx) mStreamService->txStreamUseCount++; if (!config.isTx) mStreamService->rxStreamUseCount++; mStreamService->updateThreadState(); streamID = size_t(new USBStreamServiceChannel(config.isTx, channels.size(), convertFloat)); return ""; //success } void ConnectionSTREAM::CloseStream(const size_t streamID) { auto *stream = (USBStreamServiceChannel *)streamID; if (stream->isTx) mStreamService->txStreamUseCount--; if (!stream->isTx) mStreamService->rxStreamUseCount--; delete stream; } size_t ConnectionSTREAM::GetStreamSize(const size_t streamID) { return STREAM_MTU; } bool ConnectionSTREAM::ControlStream(const size_t streamID, const bool enable, const size_t burstSize, const StreamMetadata &metadata) { auto *stream = (USBStreamServiceChannel *)streamID; if (!stream->isTx) { RxCommand rxCmd; rxCmd.waitForTimestamp = metadata.hasTimestamp; rxCmd.timestamp = metadata.timestamp-mStreamService->mTimestampOffset; rxCmd.finiteRead = metadata.endOfBurst; rxCmd.numSamps = burstSize; mStreamService->mRxCmdQueue.push(rxCmd); mStreamService->rxStreamingContinuous = not metadata.endOfBurst; } return true; } int ConnectionSTREAM::ReadStream(const size_t streamID, void * const *buffs, const size_t length, const long timeout_ms, StreamMetadata &metadata) { auto *stream = (USBStreamServiceChannel *)streamID; size_t samplesCount = std::min<size_t>(length, STREAM_MTU); complex16_t **popBuffer(nullptr); if (stream->convertFloat) popBuffer = (complex16_t **)stream->FIFOBuffers.data(); else popBuffer = (complex16_t **)buffs; uint32_t fifoFlags = 0; size_t sampsPopped = mStreamService->GetRxFIFO()->pop_samples( popBuffer, samplesCount, stream->channelsCount, &metadata.timestamp, timeout_ms, &fifoFlags); metadata.hasTimestamp = metadata.timestamp != 0; metadata.timestamp += mStreamService->mTimestampOffset; metadata.endOfBurst = (fifoFlags & STATUS_FLAG_RX_END) != 0; samplesCount = (std::min)(samplesCount, sampsPopped); if (stream->convertFloat) { for (size_t i = 0; i < stream->channelsCount; i++) { auto buffIn = stream->FIFOBuffers[i]; auto buffOut = (std::complex<float> *)buffs[i]; for (size_t j = 0; j < samplesCount; j++) { buffOut[j] = std::complex<float>( float(buffIn[j].i)/2048, float(buffIn[j].q)/2048); } } } return samplesCount; } int ConnectionSTREAM::WriteStream(const size_t streamID, const void * const *buffs, const size_t length, const long timeout_ms, const StreamMetadata &metadata) { auto *stream = (USBStreamServiceChannel *)streamID; //set the time enabled register if usage changed //TODO maybe the FPGA should check a flag in the pkt if (mStreamService->txTimeEnabled != metadata.hasTimestamp) { uint32_t regVal; this->ReadRegister(0x0005, regVal); if (metadata.hasTimestamp) regVal &= ~(1 << 5); else regVal |= (1 << 5); this->WriteRegister(0x0005, regVal); mStreamService->txTimeEnabled = metadata.hasTimestamp; } size_t samplesCount = std::min<size_t>(length, STREAM_MTU); const complex16_t **pushBuffer(nullptr); if (stream->convertFloat) { pushBuffer = (const complex16_t **)stream->FIFOBuffers.data(); for (size_t i = 0; i < stream->channelsCount; i++) { auto buffIn = (const std::complex<float> *)buffs[i]; auto bufOut = stream->FIFOBuffers[i]; for (size_t j = 0; j < samplesCount; j++) { bufOut[j].i = int16_t(buffIn[j].real()*2048); bufOut[j].q = int16_t(buffIn[j].imag()*2048); } } } else pushBuffer = (const complex16_t **)buffs; auto ticks = metadata.timestamp - mStreamService->mTimestampOffset; size_t sampsPushed = mStreamService->GetTxFIFO()->push_samples( pushBuffer, samplesCount, stream->channelsCount, metadata.hasTimestamp?ticks:0, timeout_ms); samplesCount = (std::min)(samplesCount, sampsPushed); return samplesCount; } int ConnectionSTREAM::ReadStreamStatus(const size_t streamID, const long timeout_ms, StreamMetadata &metadata) { auto *stream = (USBStreamServiceChannel *)streamID; if (stream->isTx and mStreamService->mTxStatQueue.wait_and_pop(metadata, timeout_ms)) return 0; if (!stream->isTx and mStreamService->mRxStatQueue.wait_and_pop(metadata, timeout_ms)) return 0; return -1; } void ConnectionSTREAM::UpdateExternalDataRate(const size_t channel, const double txRate, const double rxRate) { //std::cout << "LMS_StreamBoard::ConfigurePLL(tx=" << txRate/1e6 << "MHz, rx=" << rxRate/1e6 << "MHz)" << std::endl; LMS_StreamBoard::ConfigurePLL(this, txRate/1e6, rxRate/1e6, 90); if (mStreamService) mStreamService->mHwCounterRate = rxRate; } void ConnectionSTREAM::EnterSelfCalibration(const size_t channel) { if (mStreamService) mStreamService->stop(); } void ConnectionSTREAM::ExitSelfCalibration(const size_t channel) { if (mStreamService) mStreamService->start(); } uint64_t ConnectionSTREAM::GetHardwareTimestamp(void) { return mStreamService->mLastRxTimestamp + mStreamService->mTimestampOffset; } void ConnectionSTREAM::SetHardwareTimestamp(const uint64_t now) { if (not mStreamService) mStreamService.reset(new USBStreamService(this)); mStreamService->mTimestampOffset = int64_t(now)-int64_t(mStreamService->mLastRxTimestamp); } double ConnectionSTREAM::GetHardwareTimestampRate(void) { return mStreamService->mHwCounterRate; } <|endoftext|>
<commit_before>/** * For conditions of distribution and use, see copyright notice in license.txt * * @file CloneAssetDialog.cpp * @brief Dialog for cloning asset. */ #include "StableHeaders.h" #include "DebugOperatorNew.h" #include "CloneAssetDialog.h" #include "IAsset.h" #include "AssetAPI.h" #include "MemoryLeakCheck.h" CloneAssetDialog::CloneAssetDialog(const AssetPtr &asset, AssetAPI *assetApi, QWidget *parent, Qt::WindowFlags f) : QDialog(parent, f) { this->asset = asset; this->assetApi = assetApi; setWindowTitle(tr("Clone Asset: ") + asset->Name()); setAttribute(Qt::WA_DeleteOnClose); if (graphicsProxyWidget()) graphicsProxyWidget()->setWindowTitle(windowTitle()); QVBoxLayout *layout = new QVBoxLayout(this); layout->setContentsMargins(5,5,5,5); //layout->setSpacing(6); QLabel *newNameLabel = new QLabel(tr("New name:"), this); nameLineEdit = new QLineEdit; errorLabel = new QLabel(this); QHBoxLayout *buttonLayout = new QHBoxLayout(this); QSpacerItem *spacer = new QSpacerItem(20, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); okButton = new QPushButton(tr("OK"), this); okButton->setDisabled(false); buttonLayout->addSpacerItem(spacer); buttonLayout->addWidget(okButton); layout->addWidget(newNameLabel); layout->addWidget(nameLineEdit); layout->addWidget(errorLabel); layout->addLayout(buttonLayout); connect(okButton, SIGNAL(clicked()), SLOT(accept())); connect(nameLineEdit, SIGNAL(textChanged(const QString &)), SLOT(ValidateNewName(const QString &))); //connect(cancelButton, SIGNAL(clicked()), this, SLOT(reject())); } QString CloneAssetDialog::NewName() const { return nameLineEdit->text(); } void CloneAssetDialog::hideEvent(QHideEvent * /*e*/) { deleteLater(); } void CloneAssetDialog::ValidateNewName(const QString &newName) { if (newName.trimmed().isEmpty()) { okButton->setEnabled(false); errorLabel->setText(tr("Cannot use an empty name!")); } else if (assetApi->GetAsset(newName)) { okButton->setEnabled(false); errorLabel->setText(tr("Name already taken!")); } else { okButton->setEnabled(true); errorLabel->clear(); } } <commit_msg>Fix brainfart of previous commit.<commit_after>/** * For conditions of distribution and use, see copyright notice in license.txt * * @file CloneAssetDialog.cpp * @brief Dialog for cloning asset. */ #include "StableHeaders.h" #include "DebugOperatorNew.h" #include "CloneAssetDialog.h" #include "IAsset.h" #include "AssetAPI.h" #include "MemoryLeakCheck.h" CloneAssetDialog::CloneAssetDialog(const AssetPtr &asset, AssetAPI *assetApi, QWidget *parent, Qt::WindowFlags f) : QDialog(parent, f) { this->asset = asset; this->assetApi = assetApi; setWindowTitle(tr("Clone Asset: ") + asset->Name()); setAttribute(Qt::WA_DeleteOnClose); if (graphicsProxyWidget()) graphicsProxyWidget()->setWindowTitle(windowTitle()); QVBoxLayout *layout = new QVBoxLayout(this); layout->setContentsMargins(5,5,5,5); //layout->setSpacing(6); QLabel *newNameLabel = new QLabel(tr("New name:"), this); nameLineEdit = new QLineEdit; errorLabel = new QLabel(this); QHBoxLayout *buttonLayout = new QHBoxLayout(this); QSpacerItem *spacer = new QSpacerItem(20, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); okButton = new QPushButton(tr("OK"), this); okButton->setDisabled(true); buttonLayout->addSpacerItem(spacer); buttonLayout->addWidget(okButton); layout->addWidget(newNameLabel); layout->addWidget(nameLineEdit); layout->addWidget(errorLabel); layout->addLayout(buttonLayout); connect(okButton, SIGNAL(clicked()), SLOT(accept())); connect(nameLineEdit, SIGNAL(textChanged(const QString &)), SLOT(ValidateNewName(const QString &))); //connect(cancelButton, SIGNAL(clicked()), this, SLOT(reject())); } QString CloneAssetDialog::NewName() const { return nameLineEdit->text(); } void CloneAssetDialog::hideEvent(QHideEvent * /*e*/) { deleteLater(); } void CloneAssetDialog::ValidateNewName(const QString &newName) { if (newName.trimmed().isEmpty()) { okButton->setEnabled(false); errorLabel->setText(tr("Cannot use an empty name!")); } else if (assetApi->GetAsset(newName)) { okButton->setEnabled(false); errorLabel->setText(tr("Name already taken!")); } else { okButton->setEnabled(true); errorLabel->clear(); } } <|endoftext|>