text
stringlengths
54
60.6k
<commit_before>// $Id: solventParameter.C,v 1.3 2000/10/17 17:20:45 anker Exp $ #include <BALL/SOLVATION/solventParameter.h> using namespace std; namespace BALL { SolventParameter::SolventParameter() throw() : ParameterSection(), name_(), number_density_(0.0), solvent_atoms_(), solvent_descriptor_() { } SolventParameter::SolventParameter(const SolventParameter& param) throw() : ParameterSection(param), name_(param.name_), number_density_(param.number_density_), solvent_atoms_(param.solvent_atoms_), solvent_descriptor_(param.solvent_descriptor_) { } SolventParameter::~SolventParameter() throw() { clear(); valid_ = false; } void SolventParameter::clear() throw() { ParameterSection::clear(); name_ = ""; number_density_ = 0.0; solvent_descriptor_.clear(); solvent_atoms_.clear(); } const SolventParameter& SolventParameter::operator = (const SolventParameter& param) throw() { ParameterSection::operator = (param); name_ = param.name_; number_density_ = param.number_density_; solvent_atoms_ = param.solvent_atoms_; solvent_descriptor_ = param.solvent_descriptor_; return *this; } bool SolventParameter::operator == (const SolventParameter& param) const throw() { // BAUSTELLE return ((ParameterSection::operator == (param)) && (name_ == param.name_) && (number_density_ == param.number_density_)); // && (solvent_atoms_ == param.solvent_atoms_) // && (solvent_descriptor_ == param.solvent_descriptor_)); } SolventDescriptor SolventParameter::getSolventDescriptor() const throw() { return solvent_descriptor_; } bool SolventParameter::extractSection(ForceFieldParameters& parameters, const String& section_name) throw() { // BAUSTELLE if (!parameters.isValid()) { return false; } // extract the basis information ParameterSection::extractSection(parameters, section_name); // check whether all variables we need are defined, terminate otherwi if (!hasVariable("radius") || !hasVariable("number_of_atoms") || !hasVariable("element_symbol")) { Log.error() << "SolventParameter::extractSection(): Variable missing." << endl; return false; } else { if (options.has("name")) { name_ = options.get("name"); } else { Log.warn() << "SolventParameter::extractSection(): no name given." << endl; } if (options.has("number_density")) { number_density_ = options.getReal("number_density"); } else { Log.warn() << "SolventParameter::extractSection(): " << "no number density given." << endl; } AtomTypes& atom_types = parameters.getAtomTypes(); Size number_of_keys = getNumberOfKeys(); solvent_atoms_.resize(number_of_keys); Size index_element_symbol = getColumnIndex("element_symbol"); Size index_radius = getColumnIndex("radius"); Size index_number_of_atoms = getColumnIndex("number_of_atoms"); for (Size i = 0; i < number_of_keys; ++i) { String type_name = getKey(i); if (atom_types.has(type_name)) { solvent_atoms_[i].type = atom_types.getType(type_name); solvent_atoms_[i].element_symbol = getValue(i, index_element_symbol); solvent_atoms_[i].radius = getValue(i, index_radius).toFloat(); solvent_atoms_[i].number_of_atoms = getValue(i, index_number_of_atoms).toInt(); } else { Log.error() << "SolventParameter::extractSection(): " << "Cannot assign atom type." << endl; } } // build descriptor solvent_descriptor_ = SolventDescriptor(name_, number_density_, solvent_atoms_); return true; } // control flow should not reach this point Log.error() << "SolventParameter::extractSection(): " << "reached unreachable part of program" << endl; return false; } } <commit_msg>fixed: removed unreachable code<commit_after>// $Id: solventParameter.C,v 1.4 2000/10/20 15:20:44 anker Exp $ #include <BALL/SOLVATION/solventParameter.h> using namespace std; namespace BALL { SolventParameter::SolventParameter() throw() : ParameterSection(), name_(), number_density_(0.0), solvent_atoms_(), solvent_descriptor_() { } SolventParameter::SolventParameter(const SolventParameter& param) throw() : ParameterSection(param), name_(param.name_), number_density_(param.number_density_), solvent_atoms_(param.solvent_atoms_), solvent_descriptor_(param.solvent_descriptor_) { } SolventParameter::~SolventParameter() throw() { clear(); valid_ = false; } void SolventParameter::clear() throw() { ParameterSection::clear(); name_ = ""; number_density_ = 0.0; solvent_descriptor_.clear(); solvent_atoms_.clear(); } const SolventParameter& SolventParameter::operator = (const SolventParameter& param) throw() { ParameterSection::operator = (param); name_ = param.name_; number_density_ = param.number_density_; solvent_atoms_ = param.solvent_atoms_; solvent_descriptor_ = param.solvent_descriptor_; return *this; } bool SolventParameter::operator == (const SolventParameter& param) const throw() { // BAUSTELLE return ((ParameterSection::operator == (param)) && (name_ == param.name_) && (number_density_ == param.number_density_)); // && (solvent_atoms_ == param.solvent_atoms_) // && (solvent_descriptor_ == param.solvent_descriptor_)); } SolventDescriptor SolventParameter::getSolventDescriptor() const throw() { return solvent_descriptor_; } bool SolventParameter::extractSection(ForceFieldParameters& parameters, const String& section_name) throw() { // BAUSTELLE if (!parameters.isValid()) { return false; } // extract the basis information ParameterSection::extractSection(parameters, section_name); // check whether all variables we need are defined, terminate otherwi if (!hasVariable("radius") || !hasVariable("number_of_atoms") || !hasVariable("element_symbol")) { Log.error() << "SolventParameter::extractSection(): Variable missing." << endl; return false; } else { if (options.has("name")) { name_ = options.get("name"); } else { Log.warn() << "SolventParameter::extractSection(): no name given." << endl; } if (options.has("number_density")) { number_density_ = options.getReal("number_density"); } else { Log.warn() << "SolventParameter::extractSection(): " << "no number density given." << endl; } AtomTypes& atom_types = parameters.getAtomTypes(); Size number_of_keys = getNumberOfKeys(); solvent_atoms_.resize(number_of_keys); Size index_element_symbol = getColumnIndex("element_symbol"); Size index_radius = getColumnIndex("radius"); Size index_number_of_atoms = getColumnIndex("number_of_atoms"); for (Size i = 0; i < number_of_keys; ++i) { String type_name = getKey(i); if (atom_types.has(type_name)) { solvent_atoms_[i].type = atom_types.getType(type_name); solvent_atoms_[i].element_symbol = getValue(i, index_element_symbol); solvent_atoms_[i].radius = getValue(i, index_radius).toFloat(); solvent_atoms_[i].number_of_atoms = getValue(i, index_number_of_atoms).toInt(); } else { Log.error() << "SolventParameter::extractSection(): " << "Cannot assign atom type." << endl; } } // build descriptor solvent_descriptor_ = SolventDescriptor(name_, number_density_, solvent_atoms_); return true; } } } <|endoftext|>
<commit_before>#include "poi_parser.h" #include "type/data.h" #include "utils/csv.h" #include "utils/functions.h" namespace ed{ namespace connectors{ PoiParser::PoiParser(const std::string & path, const ed::connectors::ConvCoord& conv_coord): path(path), conv_coord(conv_coord){ logger = log4cplus::Logger::getInstance("log"); } void PoiParser::fill_poi_type(){ CsvReader reader(this->path + "/poi_type.txt" , ';', true, true); if(!reader.is_open()) { throw PoiParserException("Error on open file " + reader.filename); } std::vector<std::string> mandatory_headers = {"poi_type_id" , "poi_type_name"}; if(!reader.validate(mandatory_headers)) { throw PoiParserException("Impossible to parse file " + reader.filename +" . Not find column : " + reader.missing_headers(mandatory_headers)); } int id_c = reader.get_pos_col("poi_type_id"); int name_c = reader.get_pos_col("poi_type_name"); while(!reader.eof()){ std::vector<std::string> row = reader.next(); if (reader.is_valid(id_c, row) && reader.is_valid(name_c, row)){ const auto& itm = this->data.poi_types.find(row[id_c]); if(itm == this->data.poi_types.end()){ ed::types::PoiType* poi_type = new ed::types::PoiType; poi_type->id = this->data.poi_types.size() + 1; poi_type->name = row[name_c]; this->data.poi_types[row[id_c]] = poi_type; } } } } void PoiParser::fill_poi(){ CsvReader reader(this->path + "/poi.txt", ';', true, true); if(!reader.is_open()) { throw PoiParserException("Error on open file " + reader.filename); } std::vector<std::string> mandatory_headers = {"poi_id", "poi_name", "poi_weight", "poi_visible", "poi_lat", "poi_lon", "poi_type_id"}; if(!reader.validate(mandatory_headers)) { throw PoiParserException("Impossible to parse file " + reader.filename +" . Not find column : " + reader.missing_headers(mandatory_headers)); } int id_c = reader.get_pos_col("poi_id"); int name_c = reader.get_pos_col("poi_name"); int weight_c = reader.get_pos_col("poi_weight"); int visible_c = reader.get_pos_col("poi_visible"); int lat_c = reader.get_pos_col("poi_lat"); int lon_c = reader.get_pos_col("poi_lon"); int type_id_c = reader.get_pos_col("poi_type_id"); while(!reader.eof()){ std::vector<std::string> row = reader.next(); if (reader.is_valid(id_c, row) && reader.is_valid(name_c, row) && reader.is_valid(weight_c, row) && reader.is_valid(visible_c, row) && reader.is_valid(lat_c, row) && reader.is_valid(lon_c, row) && reader.is_valid(type_id_c, row)){ const auto& itm = this->data.pois.find(row[id_c]); if(itm == this->data.pois.end()){ const auto& poi_type = this->data.poi_types.find(row[type_id_c]); if(poi_type != this->data.poi_types.end()){ ed::types::Poi* poi = new ed::types::Poi; poi->id = this->data.pois.size() + 1; poi->name = row[name_c]; try{ poi->visible = boost::lexical_cast<bool>(row[visible_c]); }catch(boost::bad_lexical_cast ) { LOG4CPLUS_WARN(logger, "Impossible to parse the visible for " + row[id_c] + " " + row[name_c]); poi->visible = true; } try{ poi->weight = boost::lexical_cast<int>(row[weight_c]); }catch(boost::bad_lexical_cast ) { LOG4CPLUS_WARN(logger, "Impossible to parse the weight for " + row[id_c] + " " + row[name_c]); poi->weight = 0; } poi->poi_type = poi_type->second; poi->coord = this->conv_coord.convert_to(navitia::type::GeographicalCoord(str_to_double(row[lon_c]), str_to_double(row[lat_c]))); this->data.pois[row[id_c]] = poi; } } } } } void PoiParser::fill(){ fill_poi_type(); fill_poi(); } }} <commit_msg>ed : modify message<commit_after>#include "poi_parser.h" #include "type/data.h" #include "utils/csv.h" #include "utils/functions.h" namespace ed{ namespace connectors{ PoiParser::PoiParser(const std::string & path, const ed::connectors::ConvCoord& conv_coord): path(path), conv_coord(conv_coord){ logger = log4cplus::Logger::getInstance("log"); } void PoiParser::fill_poi_type(){ CsvReader reader(this->path + "/poi_type.txt" , ';', true, true); if(!reader.is_open()) { throw PoiParserException("Cannot open file : " + reader.filename); } std::vector<std::string> mandatory_headers = {"poi_type_id" , "poi_type_name"}; if(!reader.validate(mandatory_headers)) { throw PoiParserException("Impossible to parse file " + reader.filename +" . Not find column : " + reader.missing_headers(mandatory_headers)); } int id_c = reader.get_pos_col("poi_type_id"); int name_c = reader.get_pos_col("poi_type_name"); while(!reader.eof()){ std::vector<std::string> row = reader.next(); if (reader.is_valid(id_c, row) && reader.is_valid(name_c, row)){ const auto& itm = this->data.poi_types.find(row[id_c]); if(itm == this->data.poi_types.end()){ ed::types::PoiType* poi_type = new ed::types::PoiType; poi_type->id = this->data.poi_types.size() + 1; poi_type->name = row[name_c]; this->data.poi_types[row[id_c]] = poi_type; } } } } void PoiParser::fill_poi(){ CsvReader reader(this->path + "/poi.txt", ';', true, true); if(!reader.is_open()) { throw PoiParserException("Cannot open file : " + reader.filename); } std::vector<std::string> mandatory_headers = {"poi_id", "poi_name", "poi_weight", "poi_visible", "poi_lat", "poi_lon", "poi_type_id"}; if(!reader.validate(mandatory_headers)) { throw PoiParserException("Impossible to parse file " + reader.filename +" . Not find column : " + reader.missing_headers(mandatory_headers)); } int id_c = reader.get_pos_col("poi_id"); int name_c = reader.get_pos_col("poi_name"); int weight_c = reader.get_pos_col("poi_weight"); int visible_c = reader.get_pos_col("poi_visible"); int lat_c = reader.get_pos_col("poi_lat"); int lon_c = reader.get_pos_col("poi_lon"); int type_id_c = reader.get_pos_col("poi_type_id"); while(!reader.eof()){ std::vector<std::string> row = reader.next(); if (reader.is_valid(id_c, row) && reader.is_valid(name_c, row) && reader.is_valid(weight_c, row) && reader.is_valid(visible_c, row) && reader.is_valid(lat_c, row) && reader.is_valid(lon_c, row) && reader.is_valid(type_id_c, row)){ const auto& itm = this->data.pois.find(row[id_c]); if(itm == this->data.pois.end()){ const auto& poi_type = this->data.poi_types.find(row[type_id_c]); if(poi_type != this->data.poi_types.end()){ ed::types::Poi* poi = new ed::types::Poi; poi->id = this->data.pois.size() + 1; poi->name = row[name_c]; try{ poi->visible = boost::lexical_cast<bool>(row[visible_c]); }catch(boost::bad_lexical_cast ) { LOG4CPLUS_WARN(logger, "Impossible to parse the visible for " + row[id_c] + " " + row[name_c]); poi->visible = true; } try{ poi->weight = boost::lexical_cast<int>(row[weight_c]); }catch(boost::bad_lexical_cast ) { LOG4CPLUS_WARN(logger, "Impossible to parse the weight for " + row[id_c] + " " + row[name_c]); poi->weight = 0; } poi->poi_type = poi_type->second; poi->coord = this->conv_coord.convert_to(navitia::type::GeographicalCoord(str_to_double(row[lon_c]), str_to_double(row[lat_c]))); this->data.pois[row[id_c]] = poi; } } } } } void PoiParser::fill(){ fill_poi_type(); fill_poi(); } }} <|endoftext|>
<commit_before>/* Calf DSP Library * Module wrapper methods. * * Copyright (C) 2001-2007 Krzysztof Foltman * * This program 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 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser 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. */ #include <config.h> #include <assert.h> #include <memory.h> #include <calf/giface.h> #include <calf/modules.h> #include <calf/lv2wrap.h> using namespace synth; using namespace std; using namespace calf_utils; float parameter_properties::from_01(double value01) const { double value = dsp::clip(value01, 0., 1.); switch(flags & PF_SCALEMASK) { case PF_SCALE_DEFAULT: case PF_SCALE_LINEAR: case PF_SCALE_PERC: default: value = min + (max - min) * value01; break; case PF_SCALE_QUAD: value = min + (max - min) * value01 * value01; break; case PF_SCALE_LOG: value = min * pow(double(max / min), value01); break; case PF_SCALE_GAIN: if (value01 < 0.00001) value = min; else { float rmin = std::max(1.0f / 1024.0f, min); value = rmin * pow(double(max / rmin), value01); } break; case PF_SCALE_LOG_INF: assert(step); if (value01 > (step - 1.0) / step) value = FAKE_INFINITY; else value = min * pow(double(max / min), value01 * step / (step - 1.0)); break; } switch(flags & PF_TYPEMASK) { case PF_INT: case PF_BOOL: case PF_ENUM: case PF_ENUM_MULTI: if (value > 0) value = (int)(value + 0.5); else value = (int)(value - 0.5); break; } return value; } double parameter_properties::to_01(float value) const { switch(flags & PF_SCALEMASK) { case PF_SCALE_DEFAULT: case PF_SCALE_LINEAR: case PF_SCALE_PERC: default: return double(value - min) / (max - min); case PF_SCALE_QUAD: return sqrt(double(value - min) / (max - min)); case PF_SCALE_LOG: value /= min; return log((double)value) / log((double)max / min); case PF_SCALE_LOG_INF: if (IS_FAKE_INFINITY(value)) return max; value /= min; assert(step); return (step - 1.0) * log((double)value) / (step * log((double)max / min)); case PF_SCALE_GAIN: if (value < 1.0 / 1024.0) // new bottom limit - 60 dB return 0; double rmin = std::max(1.0f / 1024.0f, min); value /= rmin; return log((double)value) / log(max / rmin); } } float parameter_properties::get_increment() const { float increment = 0.01; if (step > 1) increment = 1.0 / (step - 1); else if (step > 0 && step < 1) increment = step; else if ((flags & PF_TYPEMASK) != PF_FLOAT) increment = 1.0 / (max - min); return increment; } int parameter_properties::get_char_count() const { if ((flags & PF_SCALEMASK) == PF_SCALE_PERC) return 6; if ((flags & PF_SCALEMASK) == PF_SCALE_GAIN) { char buf[256]; size_t len = 0; sprintf(buf, "%0.0f dB", 6.0 * log(min) / log(2)); len = strlen(buf); sprintf(buf, "%0.0f dB", 6.0 * log(max) / log(2)); len = std::max(len, strlen(buf)) + 2; return (int)len; } return std::max(to_string(min).length(), std::max(to_string(max).length(), to_string(max * 0.999999).length())); } std::string parameter_properties::to_string(float value) const { char buf[32]; if ((flags & PF_SCALEMASK) == PF_SCALE_PERC) { sprintf(buf, "%0.f%%", 100.0 * value); return string(buf); } if ((flags & PF_SCALEMASK) == PF_SCALE_GAIN) { if (value < 1.0 / 1024.0) // new bottom limit - 60 dB return "-inf dB"; // XXXKF change to utf-8 infinity sprintf(buf, "%0.1f dB", 6.0 * log(value) / log(2)); return string(buf); } switch(flags & PF_TYPEMASK) { case PF_INT: case PF_BOOL: case PF_ENUM: case PF_ENUM_MULTI: value = (int)value; break; } if ((flags & PF_SCALEMASK) == PF_SCALE_LOG_INF && IS_FAKE_INFINITY(value)) sprintf(buf, "+inf"); // XXXKF change to utf-8 infinity else sprintf(buf, "%g", value); switch(flags & PF_UNITMASK) { case PF_UNIT_DB: return string(buf) + " dB"; case PF_UNIT_HZ: return string(buf) + " Hz"; case PF_UNIT_SEC: return string(buf) + " s"; case PF_UNIT_MSEC: return string(buf) + " ms"; case PF_UNIT_CENTS: return string(buf) + " ct"; case PF_UNIT_SEMITONES: return string(buf) + "#"; case PF_UNIT_BPM: return string(buf) + " bpm"; case PF_UNIT_RPM: return string(buf) + " rpm"; case PF_UNIT_DEG: return string(buf) + " deg"; case PF_UNIT_NOTE: { static const char *notes = "C C#D D#E F F#G G#A A#B "; int note = (int)value; if (note < 0 || note > 127) return "---"; return string(notes + 2 * (note % 12), 2) + i2s(note / 12 - 2); } } return string(buf); } std::string synth::xml_escape(const std::string &src) { string dest; for (size_t i = 0; i < src.length(); i++) { // XXXKF take care of string encoding if (src[i] < 0 || src[i] == '"' || src[i] == '<' || src[i] == '>' || src[i] == '&') dest += "&"+i2s((uint8_t)src[i])+";"; else dest += src[i]; } return dest; } <commit_msg>+ Framework: remove unnecessary dependencies of giface.cpp<commit_after>/* Calf DSP Library * Module wrapper methods. * * Copyright (C) 2001-2007 Krzysztof Foltman * * This program 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 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser 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. */ #include <config.h> #include <assert.h> #include <memory.h> #include <calf/giface.h> using namespace synth; using namespace std; using namespace calf_utils; float parameter_properties::from_01(double value01) const { double value = dsp::clip(value01, 0., 1.); switch(flags & PF_SCALEMASK) { case PF_SCALE_DEFAULT: case PF_SCALE_LINEAR: case PF_SCALE_PERC: default: value = min + (max - min) * value01; break; case PF_SCALE_QUAD: value = min + (max - min) * value01 * value01; break; case PF_SCALE_LOG: value = min * pow(double(max / min), value01); break; case PF_SCALE_GAIN: if (value01 < 0.00001) value = min; else { float rmin = std::max(1.0f / 1024.0f, min); value = rmin * pow(double(max / rmin), value01); } break; case PF_SCALE_LOG_INF: assert(step); if (value01 > (step - 1.0) / step) value = FAKE_INFINITY; else value = min * pow(double(max / min), value01 * step / (step - 1.0)); break; } switch(flags & PF_TYPEMASK) { case PF_INT: case PF_BOOL: case PF_ENUM: case PF_ENUM_MULTI: if (value > 0) value = (int)(value + 0.5); else value = (int)(value - 0.5); break; } return value; } double parameter_properties::to_01(float value) const { switch(flags & PF_SCALEMASK) { case PF_SCALE_DEFAULT: case PF_SCALE_LINEAR: case PF_SCALE_PERC: default: return double(value - min) / (max - min); case PF_SCALE_QUAD: return sqrt(double(value - min) / (max - min)); case PF_SCALE_LOG: value /= min; return log((double)value) / log((double)max / min); case PF_SCALE_LOG_INF: if (IS_FAKE_INFINITY(value)) return max; value /= min; assert(step); return (step - 1.0) * log((double)value) / (step * log((double)max / min)); case PF_SCALE_GAIN: if (value < 1.0 / 1024.0) // new bottom limit - 60 dB return 0; double rmin = std::max(1.0f / 1024.0f, min); value /= rmin; return log((double)value) / log(max / rmin); } } float parameter_properties::get_increment() const { float increment = 0.01; if (step > 1) increment = 1.0 / (step - 1); else if (step > 0 && step < 1) increment = step; else if ((flags & PF_TYPEMASK) != PF_FLOAT) increment = 1.0 / (max - min); return increment; } int parameter_properties::get_char_count() const { if ((flags & PF_SCALEMASK) == PF_SCALE_PERC) return 6; if ((flags & PF_SCALEMASK) == PF_SCALE_GAIN) { char buf[256]; size_t len = 0; sprintf(buf, "%0.0f dB", 6.0 * log(min) / log(2)); len = strlen(buf); sprintf(buf, "%0.0f dB", 6.0 * log(max) / log(2)); len = std::max(len, strlen(buf)) + 2; return (int)len; } return std::max(to_string(min).length(), std::max(to_string(max).length(), to_string(max * 0.999999).length())); } std::string parameter_properties::to_string(float value) const { char buf[32]; if ((flags & PF_SCALEMASK) == PF_SCALE_PERC) { sprintf(buf, "%0.f%%", 100.0 * value); return string(buf); } if ((flags & PF_SCALEMASK) == PF_SCALE_GAIN) { if (value < 1.0 / 1024.0) // new bottom limit - 60 dB return "-inf dB"; // XXXKF change to utf-8 infinity sprintf(buf, "%0.1f dB", 6.0 * log(value) / log(2)); return string(buf); } switch(flags & PF_TYPEMASK) { case PF_INT: case PF_BOOL: case PF_ENUM: case PF_ENUM_MULTI: value = (int)value; break; } if ((flags & PF_SCALEMASK) == PF_SCALE_LOG_INF && IS_FAKE_INFINITY(value)) sprintf(buf, "+inf"); // XXXKF change to utf-8 infinity else sprintf(buf, "%g", value); switch(flags & PF_UNITMASK) { case PF_UNIT_DB: return string(buf) + " dB"; case PF_UNIT_HZ: return string(buf) + " Hz"; case PF_UNIT_SEC: return string(buf) + " s"; case PF_UNIT_MSEC: return string(buf) + " ms"; case PF_UNIT_CENTS: return string(buf) + " ct"; case PF_UNIT_SEMITONES: return string(buf) + "#"; case PF_UNIT_BPM: return string(buf) + " bpm"; case PF_UNIT_RPM: return string(buf) + " rpm"; case PF_UNIT_DEG: return string(buf) + " deg"; case PF_UNIT_NOTE: { static const char *notes = "C C#D D#E F F#G G#A A#B "; int note = (int)value; if (note < 0 || note > 127) return "---"; return string(notes + 2 * (note % 12), 2) + i2s(note / 12 - 2); } } return string(buf); } std::string synth::xml_escape(const std::string &src) { string dest; for (size_t i = 0; i < src.length(); i++) { // XXXKF take care of string encoding if (src[i] < 0 || src[i] == '"' || src[i] == '<' || src[i] == '>' || src[i] == '&') dest += "&"+i2s((uint8_t)src[i])+";"; else dest += src[i]; } return dest; } <|endoftext|>
<commit_before>#include "audio_ctx.hpp" #include "sound.hpp" #include "music.hpp" #include "../asset/asset_manager.hpp" #include <sf2/sf2.hpp> #include <sf2/FileParser.hpp> #include <SDL2/SDL_mixer.h> namespace mo { namespace audio { namespace { struct Sounds_cfg { int frequence; int channels; int buffer_size; float music_volume = 0.5; float sound_volume = 1; }; sf2_structDef(Sounds_cfg, sf2_member(frequence), sf2_member(channels), sf2_member(buffer_size), sf2_member(music_volume), sf2_member(sound_volume) ) #ifndef EMSCRIPTEN constexpr auto default_cfg = Sounds_cfg{44100, 2, 4096, 0.5, 1}; #else constexpr auto default_cfg = Sounds_cfg{44100, 2, 2048, 0.5, 1}; #endif constexpr auto create_mask(int i) -> uint16_t { return i==1 ? 1 : (create_mask(i-1)<<1 | 1); } constexpr auto static_channels = 16; constexpr auto version_bits = 4u; constexpr auto version_mask = create_mask(version_bits); constexpr auto extract_channel(Channel_id c) { return c>>version_bits; } constexpr auto extract_version(Channel_id c) { return c & version_mask; } constexpr auto build_channel_id(int16_t channel, int8_t version) { return channel<<version_bits | version; } } } namespace asset { template<> struct Loader<audio::Sounds_cfg> { using RT = std::shared_ptr<audio::Sounds_cfg>; static RT load(istream in) throw(Loading_failed) { auto r = std::make_shared<audio::Sounds_cfg>(); sf2::parseStream(in, *r); return r; } static void store(ostream out, const audio::Sounds_cfg& asset) throw (Loading_failed) { sf2::writeStream(out, asset); } }; } namespace audio { using namespace unit_literals; Audio_ctx::Audio_ctx(asset::Asset_manager& assets) : _channels{}, _channels_last{}, _channel_versions{}, _channel_sounds{} { _channels.fill(false); _channels_last.fill(false); _channel_versions.fill(0); _channel_sounds.fill(nullptr); _free_channels.reserve(_dynamic_channels); for(int16_t i=0; i<_dynamic_channels; ++i) _free_channels.push_back(i); auto& cfg = asset::unpack(assets.load_maybe<Sounds_cfg>("cfg:sounds"_aid)).get_or_other( default_cfg ); if(&cfg==&default_cfg) { assets.save<Sounds_cfg>("cfg:sounds"_aid, cfg); } // Checking if frequence is faulty -> setting to 44100MHz int verified_frequence = (cfg.frequence % 22050 == 0) ? cfg.frequence : 44100; DEBUG("frequence: " << verified_frequence << " | " << ((cfg.channels == 1) ? "Mono" : "Stereo") << " | buffer: " << cfg.buffer_size); // Open SDL Audio Mixer if(Mix_OpenAudio(verified_frequence, MIX_DEFAULT_FORMAT, cfg.channels, cfg.buffer_size) == 0) { DEBUG("Sound_ctx succesfully initialized!"); } else { FAIL("Initializing Sound incomplete: " << Mix_GetError()); } Mix_AllocateChannels(_dynamic_channels+static_channels); Mix_ReserveChannels(_dynamic_channels); sound_volume(cfg.sound_volume); music_volume(cfg.music_volume); } Audio_ctx::~Audio_ctx() { Mix_CloseAudio(); } void Audio_ctx::flip() { for(int16_t i=0; i<_dynamic_channels; ++i) { if(!_channels[i] && _channels_last[i]) { Mix_Pause(i); _free_channels.push_back(i); } } _channels_last = _channels; _channels.fill(false); } void Audio_ctx::play_music(std::shared_ptr<const audio::Music> music, Time fade_time) { if(_playing_music==music) return; if(_playing_music) { // TODO: fade Mix_HaltMusic(); } _playing_music = music; Mix_FadeInMusic(music->getMusic(), -1, fade_time/1_ms); } auto Audio_ctx::play_static(const audio::Sound& sound) -> Channel_id { auto c = Mix_PlayChannel(-1, sound.getSound(), 0); return build_channel_id(c, 0); } auto Audio_ctx::play_dynamic(const audio::Sound& sound, Angle angle, Distance dist, bool loop, Channel_id id) -> Channel_id { int16_t c; uint8_t v; if(id>=0) { c = extract_channel(id); v = extract_version(id); if(v!=_channel_versions[c]) id=-1; else if(_channels[c]==_channels_last[c] && !_channels[c]) id=-1; else if(&sound == _channel_sounds[c]) { if(Mix_Paused(c)) { Mix_Resume(c); update(id, angle, dist); return id; } else if(Mix_Playing(c)) { update(id, angle, dist); return id; } } } if(id<0) { if(_free_channels.empty()) { DEBUG("No free channel left."); return -1; } c = _free_channels.back(); _free_channels.pop_back(); v = ++_channel_versions[c]; id = build_channel_id(c,v); } _channel_sounds[c] = &sound; Mix_PlayChannel(c, sound.getSound(), loop ? -1 : 0); update(id, angle, dist); return id; } void Audio_ctx::update(Channel_id id, Angle angle, Distance dist) { auto c = extract_channel(id); auto v = extract_version(id); if(c<_dynamic_channels && _channel_versions[c]==v) { Mix_SetPosition(id, angle.value(), dist.value()); _channels[c] = true; } } void Audio_ctx::stop(Channel_id id) { auto c = extract_channel(id); auto v = extract_version(id); if(c>=_dynamic_channels || _channel_versions[c]==v) Mix_HaltChannel(c); } void Audio_ctx::pause_sounds() { Mix_Pause(-1); } void Audio_ctx::resume_sounds() { Mix_Resume(-1); } void Audio_ctx::stop_sounds() { Mix_HaltChannel(-1); _channels.fill(false); _channels_last.fill(false); _channel_versions.fill(0); _channel_sounds.fill(nullptr); _free_channels.clear(); for(int i=0; i<_dynamic_channels; ++i) _free_channels.push_back(i); } void Audio_ctx::sound_volume(float volume) { _sound_volume = volume; Mix_Volume(-1, 128 * _sound_volume); } void Audio_ctx::music_volume(float volume) { _music_volume = volume; Mix_VolumeMusic(128 * _music_volume); } } } <commit_msg>fix for Windows<commit_after>#include "audio_ctx.hpp" #include "sound.hpp" #include "music.hpp" #include "../asset/asset_manager.hpp" #include <sf2/sf2.hpp> #include <sf2/FileParser.hpp> #include <SDL2/SDL_mixer.h> namespace mo { namespace audio { namespace { struct Sounds_cfg { int frequence; int channels; int buffer_size; float music_volume; float sound_volume; }; sf2_structDef(Sounds_cfg, sf2_member(frequence), sf2_member(channels), sf2_member(buffer_size), sf2_member(music_volume), sf2_member(sound_volume) ) #ifndef EMSCRIPTEN constexpr auto default_cfg = Sounds_cfg{44100, 2, 4096, 0.5f, 1.0f}; #else constexpr auto default_cfg = Sounds_cfg{44100, 2, 2048, 0.5f, 1.0f}; #endif constexpr auto create_mask(int i) -> uint16_t { return i==1 ? 1 : (create_mask(i-1)<<1 | 1); } constexpr auto static_channels = 16; constexpr auto version_bits = 4u; constexpr auto version_mask = create_mask(version_bits); constexpr auto extract_channel(Channel_id c) { return c>>version_bits; } constexpr auto extract_version(Channel_id c) { return c & version_mask; } constexpr auto build_channel_id(int16_t channel, int8_t version) { return channel<<version_bits | version; } } } namespace asset { template<> struct Loader<audio::Sounds_cfg> { using RT = std::shared_ptr<audio::Sounds_cfg>; static RT load(istream in) throw(Loading_failed) { auto r = std::make_shared<audio::Sounds_cfg>(); sf2::parseStream(in, *r); return r; } static void store(ostream out, const audio::Sounds_cfg& asset) throw (Loading_failed) { sf2::writeStream(out, asset); } }; } namespace audio { using namespace unit_literals; Audio_ctx::Audio_ctx(asset::Asset_manager& assets) : _channels{nullptr}, _channels_last{nullptr}, _channel_versions{0}, _channel_sounds{0} { _channels.fill(false); _channels_last.fill(false); _channel_versions.fill(0); _channel_sounds.fill(nullptr); _free_channels.reserve(_dynamic_channels); for(int16_t i=0; i<_dynamic_channels; ++i) _free_channels.push_back(i); auto& cfg = asset::unpack(assets.load_maybe<Sounds_cfg>("cfg:sounds"_aid)).get_or_other( default_cfg ); if(&cfg==&default_cfg) { assets.save<Sounds_cfg>("cfg:sounds"_aid, cfg); } // Checking if frequence is faulty -> setting to 44100MHz int verified_frequence = (cfg.frequence % 22050 == 0) ? cfg.frequence : 44100; DEBUG("frequence: " << verified_frequence << " | " << ((cfg.channels == 1) ? "Mono" : "Stereo") << " | buffer: " << cfg.buffer_size); // Open SDL Audio Mixer if(Mix_OpenAudio(verified_frequence, MIX_DEFAULT_FORMAT, cfg.channels, cfg.buffer_size) == 0) { DEBUG("Sound_ctx succesfully initialized!"); } else { FAIL("Initializing Sound incomplete: " << Mix_GetError()); } Mix_AllocateChannels(_dynamic_channels+static_channels); Mix_ReserveChannels(_dynamic_channels); sound_volume(cfg.sound_volume); music_volume(cfg.music_volume); } Audio_ctx::~Audio_ctx() { Mix_CloseAudio(); } void Audio_ctx::flip() { for(int16_t i=0; i<_dynamic_channels; ++i) { if(!_channels[i] && _channels_last[i]) { Mix_Pause(i); _free_channels.push_back(i); } } _channels_last = _channels; _channels.fill(false); } void Audio_ctx::play_music(std::shared_ptr<const audio::Music> music, Time fade_time) { if(_playing_music==music) return; if(_playing_music) { // TODO: fade Mix_HaltMusic(); } _playing_music = music; Mix_FadeInMusic(music->getMusic(), -1, fade_time/1_ms); } auto Audio_ctx::play_static(const audio::Sound& sound) -> Channel_id { auto c = Mix_PlayChannel(-1, sound.getSound(), 0); return build_channel_id(c, 0); } auto Audio_ctx::play_dynamic(const audio::Sound& sound, Angle angle, Distance dist, bool loop, Channel_id id) -> Channel_id { int16_t c; uint8_t v; if(id>=0) { c = extract_channel(id); v = extract_version(id); if(v!=_channel_versions[c]) id=-1; else if(_channels[c]==_channels_last[c] && !_channels[c]) id=-1; else if(&sound == _channel_sounds[c]) { if(Mix_Paused(c)) { Mix_Resume(c); update(id, angle, dist); return id; } else if(Mix_Playing(c)) { update(id, angle, dist); return id; } } } if(id<0) { if(_free_channels.empty()) { DEBUG("No free channel left."); return -1; } c = _free_channels.back(); _free_channels.pop_back(); v = ++_channel_versions[c]; id = build_channel_id(c,v); } _channel_sounds[c] = &sound; Mix_PlayChannel(c, sound.getSound(), loop ? -1 : 0); update(id, angle, dist); return id; } void Audio_ctx::update(Channel_id id, Angle angle, Distance dist) { auto c = extract_channel(id); auto v = extract_version(id); if(c<_dynamic_channels && _channel_versions[c]==v) { Mix_SetPosition(id, angle.value(), dist.value()); _channels[c] = true; } } void Audio_ctx::stop(Channel_id id) { auto c = extract_channel(id); auto v = extract_version(id); if(c>=_dynamic_channels || _channel_versions[c]==v) Mix_HaltChannel(c); } void Audio_ctx::pause_sounds() { Mix_Pause(-1); } void Audio_ctx::resume_sounds() { Mix_Resume(-1); } void Audio_ctx::stop_sounds() { Mix_HaltChannel(-1); _channels.fill(false); _channels_last.fill(false); _channel_versions.fill(0); _channel_sounds.fill(nullptr); _free_channels.clear(); for(int i=0; i<_dynamic_channels; ++i) _free_channels.push_back(i); } void Audio_ctx::sound_volume(float volume) { _sound_volume = volume; Mix_Volume(-1, 128 * _sound_volume); } void Audio_ctx::music_volume(float volume) { _music_volume = volume; Mix_VolumeMusic(128 * _music_volume); } } } <|endoftext|>
<commit_before>/* * Copyright (c) 2016-2017, The OpenThread Authors. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** * @file * This file defines OpenThread Notifier class. */ #ifndef NOTIFIER_HPP_ #define NOTIFIER_HPP_ #include "openthread-core-config.h" #include "utils/wrap_stdbool.h" #include "utils/wrap_stdint.h" #include <openthread/instance.h> #include <openthread/platform/toolchain.h> #include "common/locator.hpp" #include "common/tasklet.hpp" namespace ot { /** * @addtogroup core-notifier * * @brief * This module includes definitions for OpenThread Notifier class. * * @{ * */ /** * This class implements the OpenThread Notifier. * * It can be used to register callbacks to be notified of state or configuration changes within OpenThread. * */ class Notifier : public InstanceLocator { public: /** * This class defines a callback instance that can be registered with the `Notifier`. * */ class Callback : public OwnerLocator { friend class Notifier; public: /** * This type defines the function pointer which is called to notify of state or configuration changes. * * @param[in] aCallback A reference to callback instance. * @param[in] aFlags A bit-field indicating specific state or configuration that has changed. * */ typedef void (*Handler)(Callback &aCallback, otChangedFlags aFlags); /** * This constructor initializes a `Callback` instance * * @param[in] aInstance A reference to OpenThread instance. * @param[in] aHandler A function pointer to the callback handler. * @param[in] aOwner A pointer to the owner of the `Callback` instance. * */ Callback(Instance &aInstance, Handler aHandler, void *aOwner); private: void Invoke(otChangedFlags aFlags) { mHandler(*this, aFlags); } Handler mHandler; Callback *mNext; }; /** * This constructor initializes a `Notifier` instance. * * @param[in] aInstance A reference to OpenThread instance. * */ explicit Notifier(Instance &aInstance); /** * This method registers an `otStateChangedCallback` handler. * * @param[in] aCallback A pointer to the handler function that is called to notify of the changes. * @param[in] aContext A pointer to arbitrary context information. * * @retval OT_ERROR_NONE Successfully registered the callback. * @retval OT_ERROR_ALREADY The callback was already registered. * @retval OT_ERROR_NO_BUFS Could not add the callback due to resource constraints. * */ otError RegisterCallback(otStateChangedCallback aCallback, void *aContext); /** * This method removes/unregisters a previously registered `otStateChangedCallback` handler. * * @param[in] aCallback A pointer to the callback function pointer. * @param[in] aContex A pointer to arbitrary context information. * */ void RemoveCallback(otStateChangedCallback aCallback, void *aContext); /** * This method schedules signaling of changed flags. * * @param[in] aFlags A bit-field indicating what configuration or state has changed. * */ void Signal(otChangedFlags aFlags); /** * This method schedules signaling of changed flags only if the set of flags has not been signaled before (first * time signal). * * @param[in] aFlags A bit-field indicating what configuration or state has changed. * */ void SignalIfFirst(otChangedFlags aFlags); /** * This method indicates whether or not a changed callback is pending. * * @returns TRUE if a state changed callback is pending, FALSE otherwise. * */ bool IsPending(void) const { return (mFlagsToSignal != 0); } /** * This method indicates whether or not a changed notification for a given set of flags has been signaled before. * * @param[in] aFlags A bit-field containing the flag-bits to check. * * @retval TRUE All flag bits in @p aFlags have been signaled before. * @retval FALSE At least one flag bit in @p aFlags has not been signaled before. * */ bool HasSignaled(otChangedFlags aFlags) const { return (mSignaledFlags & aFlags) == aFlags; } private: enum { kMaxExternalHandlers = OPENTHREAD_CONFIG_MAX_STATECHANGE_HANDLERS, kFlagsStringLineLimit = 70, // Character limit to divide the log into multiple lines in `LogChangedFlags()`. kMaxFlagNameLength = 25, // Max length for string representation of a flag by `FlagToString()`. kFlagsStringBufferSize = kFlagsStringLineLimit + kMaxFlagNameLength, }; struct ExternalCallback { otStateChangedCallback mHandler; void * mContext; }; void RegisterCallback(Callback &aCallback); static void HandleStateChanged(Tasklet &aTasklet); void HandleStateChanged(void); void LogChangedFlags(otChangedFlags aFlags) const; const char *FlagToString(otChangedFlags aFlag) const; otChangedFlags mFlagsToSignal; otChangedFlags mSignaledFlags; Tasklet mTask; Callback * mCallbacks; ExternalCallback mExternalCallbacks[kMaxExternalHandlers]; }; /** * @} * */ } // namespace ot #endif // NOTIFIER_HPP_ <commit_msg>[notifier] enhance documentation (#3583)<commit_after>/* * Copyright (c) 2016-2017, The OpenThread Authors. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** * @file * This file defines OpenThread Notifier class. */ #ifndef NOTIFIER_HPP_ #define NOTIFIER_HPP_ #include "openthread-core-config.h" #include "utils/wrap_stdbool.h" #include "utils/wrap_stdint.h" #include <openthread/instance.h> #include <openthread/platform/toolchain.h> #include "common/locator.hpp" #include "common/tasklet.hpp" namespace ot { /** * @addtogroup core-notifier * * @brief * This module includes definitions for OpenThread Notifier class. * * @{ * */ /** * This class implements the OpenThread Notifier. * * It can be used to register callbacks that notify of state or configuration changes within OpenThread. * * Two callback models are provided: * * - A `Notifier::Callback` object that upon initialization (from its constructor) auto-registers itself with * the `Notifier`. This model is mainly used by OpenThread core modules. * * - A `otStateChangedCallback` callback handler which needs to be explicitly registered with the `Notifier`. This is * commonly used by external users (provided as an OpenThread public API). Max number of such callbacks that can be * registered at the same time is specified by `OPENTHREAD_CONFIG_MAX_STATECHANGE_HANDLERS` configuration parameter. * */ class Notifier : public InstanceLocator { public: /** * This class defines a `Notifier` callback instance. * */ class Callback : public OwnerLocator { friend class Notifier; public: /** * This type defines the function pointer which is called to notify of state or configuration changes. * * @param[in] aCallback A reference to callback instance. * @param[in] aFlags A bit-field indicating specific state or configuration that has changed. * */ typedef void (*Handler)(Callback &aCallback, otChangedFlags aFlags); /** * This constructor initializes a `Callback` instance and registers it with `Notifier`. * * @param[in] aInstance A reference to OpenThread instance. * @param[in] aHandler A function pointer to the callback handler. * @param[in] aOwner A pointer to the owner of the `Callback` instance. * */ Callback(Instance &aInstance, Handler aHandler, void *aOwner); private: void Invoke(otChangedFlags aFlags) { mHandler(*this, aFlags); } Handler mHandler; Callback *mNext; }; /** * This constructor initializes a `Notifier` instance. * * @param[in] aInstance A reference to OpenThread instance. * */ explicit Notifier(Instance &aInstance); /** * This method registers an `otStateChangedCallback` handler. * * @param[in] aCallback A pointer to the handler function that is called to notify of the changes. * @param[in] aContext A pointer to arbitrary context information. * * @retval OT_ERROR_NONE Successfully registered the callback. * @retval OT_ERROR_ALREADY The callback was already registered. * @retval OT_ERROR_NO_BUFS Could not add the callback due to resource constraints. * */ otError RegisterCallback(otStateChangedCallback aCallback, void *aContext); /** * This method removes/unregisters a previously registered `otStateChangedCallback` handler. * * @param[in] aCallback A pointer to the callback function pointer. * @param[in] aContex A pointer to arbitrary context information. * */ void RemoveCallback(otStateChangedCallback aCallback, void *aContext); /** * This method schedules signaling of changed flags. * * @param[in] aFlags A bit-field indicating what configuration or state has changed. * */ void Signal(otChangedFlags aFlags); /** * This method schedules signaling of changed flags only if the set of flags has not been signaled before (first * time signal). * * @param[in] aFlags A bit-field indicating what configuration or state has changed. * */ void SignalIfFirst(otChangedFlags aFlags); /** * This method indicates whether or not a changed callback is pending. * * @returns TRUE if a state changed callback is pending, FALSE otherwise. * */ bool IsPending(void) const { return (mFlagsToSignal != 0); } /** * This method indicates whether or not a changed notification for a given set of flags has been signaled before. * * @param[in] aFlags A bit-field containing the flag-bits to check. * * @retval TRUE All flag bits in @p aFlags have been signaled before. * @retval FALSE At least one flag bit in @p aFlags has not been signaled before. * */ bool HasSignaled(otChangedFlags aFlags) const { return (mSignaledFlags & aFlags) == aFlags; } private: enum { kMaxExternalHandlers = OPENTHREAD_CONFIG_MAX_STATECHANGE_HANDLERS, kFlagsStringLineLimit = 70, // Character limit to divide the log into multiple lines in `LogChangedFlags()`. kMaxFlagNameLength = 25, // Max length for string representation of a flag by `FlagToString()`. kFlagsStringBufferSize = kFlagsStringLineLimit + kMaxFlagNameLength, }; struct ExternalCallback { otStateChangedCallback mHandler; void * mContext; }; void RegisterCallback(Callback &aCallback); static void HandleStateChanged(Tasklet &aTasklet); void HandleStateChanged(void); void LogChangedFlags(otChangedFlags aFlags) const; const char *FlagToString(otChangedFlags aFlag) const; otChangedFlags mFlagsToSignal; otChangedFlags mSignaledFlags; Tasklet mTask; Callback * mCallbacks; ExternalCallback mExternalCallbacks[kMaxExternalHandlers]; }; /** * @} * */ } // namespace ot #endif // NOTIFIER_HPP_ <|endoftext|>
<commit_before>/* This file is part of Zanshin Todo. Copyright (C) 2012 Christian Mollekopf <chrigi_1@fastmail.fm> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "globaldefs.h" #include "core/projectstrategy.h" #include "core/incidenceitem.h" #include "core/pimitemmodel.h" #include "core/pimitemservices.h" #include "reparentingmodel/todonode.h" #include "reparentingmodel/reparentingmodel.h" #include "todohelpers.h" #include <KLocalizedString> #include <KIcon> #include <QMimeData> #include <Akonadi/ItemModifyJob> #include <Akonadi/ItemFetchJob> #include <Akonadi/ItemFetchScope> #include <KUrl> ProjectStrategy::ProjectStrategy(ProjectStructureCache *structure) : ReparentingStrategy(), mInbox(1), mRelations(structure) { PimItemServices::projectInstance().setRelationsStructure(mRelations.data()); mReparentOnRemoval = false; connect(mRelations.data(), SIGNAL(nodeRemoved(Id)), this, SLOT(doRemoveNode(Id))); connect(mRelations.data(), SIGNAL(parentsChanged(Id,IdList)), this, SLOT(doChangeParents(Id, IdList))); } void ProjectStrategy::init() { ReparentingStrategy::init(); //FIXME we should be setting this earlier, here the inserted signals have already been emitted QList<TodoNode*> nodes = createNode(mInbox, IdList(), "Inbox"); Q_ASSERT(nodes.size() == 1); TodoNode *node = nodes.first(); node->setData(i18n("Inbox"), 0, Qt::DisplayRole); node->setData(KIcon("mail-folder-inbox"), 0, Qt::DecorationRole); node->setRowData(Zanshin::Inbox, Zanshin::ItemTypeRole); } static Id translateFrom(Id id) { //TODO proper id mapping return id+10; } static Id translateTo(Id id) { //TODO proper id mapping return id-10; } static IdList translateFrom(IdList l) { IdList list; foreach (Id id, l) { list << translateFrom(id); } return list; } void ProjectStrategy::doRemoveNode(Id id) { kDebug() << id; //FIXME // ReparentingStrategy::removeNode(translateFrom(id)); } void ProjectStrategy::doChangeParents(Id id, IdList parents) { IdList p; if (parents.isEmpty()) { bool isProject = mRelations->hasChildren(id); if (isProject) { const Akonadi::Collection col = getParentCollection(translateFrom(id)); if (col.isValid()) { p << translateFrom(mRelations->addCollection(col)); } } else { p << mInbox; } } else { p << translateFrom(parents); } ReparentingStrategy::updateParents(translateFrom(id), p); } Id ProjectStrategy::getId(const QModelIndex &sourceChildIndex) { Zanshin::ItemType type = (Zanshin::ItemType) sourceChildIndex.data(Zanshin::ItemTypeRole).toInt(); if (type==Zanshin::Collection) { return translateFrom(mRelations->addCollection(sourceChildIndex.data(Akonadi::EntityTreeModel::CollectionRole).value<Akonadi::Collection>())); } // kDebug() << sourceChildIndex.data(Akonadi::EntityTreeModel::ItemRole).value<Akonadi::Item>().url() << sourceChildIndex << type; const Akonadi::Item &item = sourceChildIndex.data(Akonadi::EntityTreeModel::ItemRole).value<Akonadi::Item>(); Q_ASSERT(item.isValid()); Id id = mRelations->addItem(item); if (id < 0) { return -1; } return translateFrom(id); } bool ProjectStrategy::isProject(Id id, Zanshin::ItemType itemType) const { if (itemType == Zanshin::ProjectTodo || ((itemType == Zanshin::StandardTodo) && mRelations->hasChildren(translateTo(id)))) { return true; } return false; } IdList ProjectStrategy::getParents(const QModelIndex &sourceChildIndex, const IdList &ignore) { Q_ASSERT(sourceChildIndex.isValid()); // kDebug() << sourceChildIndex.data(Akonadi::EntityTreeModel::ItemRole).value<Akonadi::Item>().url(); // kDebug() << sourceChildIndex.data().toString(); // mRelations->printCache(); IdList parents; Zanshin::ItemType type = (Zanshin::ItemType) sourceChildIndex.data(Zanshin::ItemTypeRole).toInt(); if (type==Zanshin::Collection) { const QModelIndex &parent = sourceChildIndex.parent(); if (parent.isValid()) { return IdList() << getId(parent); } return IdList(); } const Akonadi::Item &item = sourceChildIndex.data(Akonadi::EntityTreeModel::ItemRole).value<Akonadi::Item>(); Id id = mRelations->getItemId(item); parents = translateFrom(mRelations->getParents(id)); bool isNote = (sourceChildIndex.data(PimItemModel::ItemTypeRole).toInt() == PimItem::Note); if (parents.isEmpty() || isNote) { if (!isProject(translateFrom(id), type) && !isNote) { return IdList() << mInbox; } const QModelIndex &parent = sourceChildIndex.parent(); if (parent.isValid()) { parents << getId(parent); } } Q_ASSERT(!parents.contains(translateFrom(id))); foreach(Id i, ignore) { parents.removeAll(i); } // kDebug() << id << parents; checkParents(parents); return parents; } void ProjectStrategy::onNodeRemoval(const Id& changed) { IdList parents = translateFrom(mRelations->getParents(translateTo(changed))); // kDebug() << changed << parents; mRelations->removeNode(translateTo(changed)); checkParents(parents); } void ProjectStrategy::checkParents(const IdList &parentsToCheck) { foreach(Id id, parentsToCheck) { //Because we may have just removed a project ReparentingStrategy::updateParents(id); } } void ProjectStrategy::reset() { ReparentingStrategy::reset(); } Qt::ItemFlags ProjectStrategy::flags(const QModelIndex& index, Qt::ItemFlags existingFlags) { Zanshin::ItemType type = (Zanshin::ItemType)index.data(Zanshin::ItemTypeRole).toInt(); if (type == Zanshin::Inbox) { return Qt::ItemIsSelectable | Qt::ItemIsDropEnabled | Qt::ItemIsEnabled; } Akonadi::Collection collection; if (type==Zanshin::Collection) { collection = index.data(Akonadi::EntityTreeModel::CollectionRole).value<Akonadi::Collection>(); } else if (type == Zanshin::ProjectTodo) { //isProject(getId(index), type) FIXME for some reason the item is invalid in getid // We use ParentCollectionRole instead of Akonadi::Item::parentCollection() because the // information about the rights is not valid on retrieved items. collection = index.data(Akonadi::EntityTreeModel::ParentCollectionRole).value<Akonadi::Collection>(); } if (!(collection.rights() & Akonadi::Collection::CanCreateItem)) { existingFlags &= ~Qt::ItemIsDropEnabled; } else { existingFlags |= Qt::ItemIsDropEnabled; } return existingFlags; } Qt::DropActions ProjectStrategy::supportedDropActions() const { return Qt::MoveAction/*|Qt::LinkAction*/; } bool ProjectStrategy::onDropMimeData(Id id, const QMimeData* mimeData, Qt::DropAction action) { if (action != Qt::MoveAction || !KUrl::List::canDecode(mimeData)) { return false; } KUrl::List urls = KUrl::List::fromMimeData(mimeData); Akonadi::Collection collection; bool forward; Zanshin::ItemType parentType = (Zanshin::ItemType)data(id, 0, Zanshin::ItemTypeRole, forward).toInt(); if (parentType == Zanshin::Collection) { collection = getData(id, Akonadi::EntityTreeModel::CollectionRole).value<Akonadi::Collection>(); } else { const Akonadi::Item parentItem = getData(id, Akonadi::EntityTreeModel::ItemRole).value<Akonadi::Item>(); collection = parentItem.parentCollection(); } QString parentUid = getData(id, Zanshin::UidRole).toString(); foreach (const KUrl &url, urls) { const Akonadi::Item urlItem = Akonadi::Item::fromUrl(url); //TODO make sure we never get here during testing (although we normally shouldn't anyways if (urlItem.isValid()) { //TODO replace by getData/setData? Akonadi::ItemFetchJob *job = new Akonadi::ItemFetchJob(urlItem); job->fetchScope().setAncestorRetrieval(Akonadi::ItemFetchScope::Parent); job->fetchScope().fetchFullPayload(); if ( !job->exec() ) { continue; } Q_ASSERT(job->items().size()==1); Akonadi::Item item = job->items().first(); Q_ASSERT(item.isValid()); if (PimItem::itemType(item) == PimItem::Todo) { return TodoHelpers::moveTodoToProject(item, parentUid, parentType, collection); } else if (PimItem::itemType(item) == PimItem::Note) { TodoHelpers::moveToProject(item, parentUid); setData(id, QVariant::fromValue<Akonadi::Item>(item), Akonadi::EntityTreeModel::ItemRole); return true; } } } return false; } QVariant ProjectStrategy::data(Id id, int column, int role, bool &forward) const { //We simply override the todometadatamodel data for todos with children (which are also projects) const Zanshin::ItemType itemType = static_cast<Zanshin::ItemType>(getData(id, Zanshin::ItemTypeRole).toInt()); bool project = isProject(id, itemType); switch (role) { case Zanshin::ItemTypeRole: { if (id == mInbox) { return Zanshin::Inbox; } if (project) { return Zanshin::ProjectTodo; } return itemType; } case Qt::CheckStateRole: if (project) { forward = false; return QVariant(); } break; case Qt::DecorationRole: if (project && !column) { return KIcon("view-pim-tasks"); } break; } return QVariant(); } <commit_msg>Use PimItemServices instead of Todohelpers<commit_after>/* This file is part of Zanshin Todo. Copyright (C) 2012 Christian Mollekopf <chrigi_1@fastmail.fm> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "globaldefs.h" #include "core/projectstrategy.h" #include "core/incidenceitem.h" #include "core/pimitemmodel.h" #include "core/pimitemservices.h" #include "reparentingmodel/todonode.h" #include "reparentingmodel/reparentingmodel.h" #include "todohelpers.h" #include <KLocalizedString> #include <KIcon> #include <QMimeData> #include <Akonadi/ItemModifyJob> #include <Akonadi/ItemFetchJob> #include <Akonadi/ItemFetchScope> #include <KUrl> ProjectStrategy::ProjectStrategy(ProjectStructureCache *structure) : ReparentingStrategy(), mInbox(1), mRelations(structure) { PimItemServices::projectInstance().setRelationsStructure(mRelations.data()); mReparentOnRemoval = false; connect(mRelations.data(), SIGNAL(nodeRemoved(Id)), this, SLOT(doRemoveNode(Id))); connect(mRelations.data(), SIGNAL(parentsChanged(Id,IdList)), this, SLOT(doChangeParents(Id, IdList))); } void ProjectStrategy::init() { ReparentingStrategy::init(); //FIXME we should be setting this earlier, here the inserted signals have already been emitted QList<TodoNode*> nodes = createNode(mInbox, IdList(), "Inbox"); Q_ASSERT(nodes.size() == 1); TodoNode *node = nodes.first(); node->setData(i18n("Inbox"), 0, Qt::DisplayRole); node->setData(KIcon("mail-folder-inbox"), 0, Qt::DecorationRole); node->setRowData(Zanshin::Inbox, Zanshin::ItemTypeRole); } static Id translateFrom(Id id) { //TODO proper id mapping return id+10; } static Id translateTo(Id id) { //TODO proper id mapping return id-10; } static IdList translateFrom(IdList l) { IdList list; foreach (Id id, l) { list << translateFrom(id); } return list; } void ProjectStrategy::doRemoveNode(Id id) { kDebug() << id; //FIXME // ReparentingStrategy::removeNode(translateFrom(id)); } void ProjectStrategy::doChangeParents(Id id, IdList parents) { IdList p; if (parents.isEmpty()) { bool isProject = mRelations->hasChildren(id); if (isProject) { const Akonadi::Collection col = getParentCollection(translateFrom(id)); if (col.isValid()) { p << translateFrom(mRelations->addCollection(col)); } } else { p << mInbox; } } else { p << translateFrom(parents); } ReparentingStrategy::updateParents(translateFrom(id), p); } Id ProjectStrategy::getId(const QModelIndex &sourceChildIndex) { Zanshin::ItemType type = (Zanshin::ItemType) sourceChildIndex.data(Zanshin::ItemTypeRole).toInt(); if (type==Zanshin::Collection) { return translateFrom(mRelations->addCollection(sourceChildIndex.data(Akonadi::EntityTreeModel::CollectionRole).value<Akonadi::Collection>())); } // kDebug() << sourceChildIndex.data(Akonadi::EntityTreeModel::ItemRole).value<Akonadi::Item>().url() << sourceChildIndex << type; const Akonadi::Item &item = sourceChildIndex.data(Akonadi::EntityTreeModel::ItemRole).value<Akonadi::Item>(); Q_ASSERT(item.isValid()); Id id = mRelations->addItem(item); if (id < 0) { return -1; } return translateFrom(id); } bool ProjectStrategy::isProject(Id id, Zanshin::ItemType itemType) const { if (itemType == Zanshin::ProjectTodo || ((itemType == Zanshin::StandardTodo) && mRelations->hasChildren(translateTo(id)))) { return true; } return false; } IdList ProjectStrategy::getParents(const QModelIndex &sourceChildIndex, const IdList &ignore) { Q_ASSERT(sourceChildIndex.isValid()); // kDebug() << sourceChildIndex.data(Akonadi::EntityTreeModel::ItemRole).value<Akonadi::Item>().url(); // kDebug() << sourceChildIndex.data().toString(); // mRelations->printCache(); IdList parents; Zanshin::ItemType type = (Zanshin::ItemType) sourceChildIndex.data(Zanshin::ItemTypeRole).toInt(); if (type==Zanshin::Collection) { const QModelIndex &parent = sourceChildIndex.parent(); if (parent.isValid()) { return IdList() << getId(parent); } return IdList(); } const Akonadi::Item &item = sourceChildIndex.data(Akonadi::EntityTreeModel::ItemRole).value<Akonadi::Item>(); Id id = mRelations->getItemId(item); parents = translateFrom(mRelations->getParents(id)); bool isNote = (sourceChildIndex.data(PimItemModel::ItemTypeRole).toInt() == PimItem::Note); if (parents.isEmpty() || isNote) { if (!isProject(translateFrom(id), type) && !isNote) { return IdList() << mInbox; } const QModelIndex &parent = sourceChildIndex.parent(); if (parent.isValid()) { parents << getId(parent); } } Q_ASSERT(!parents.contains(translateFrom(id))); foreach(Id i, ignore) { parents.removeAll(i); } // kDebug() << id << parents; checkParents(parents); return parents; } void ProjectStrategy::onNodeRemoval(const Id& changed) { IdList parents = translateFrom(mRelations->getParents(translateTo(changed))); // kDebug() << changed << parents; mRelations->removeNode(translateTo(changed)); checkParents(parents); } void ProjectStrategy::checkParents(const IdList &parentsToCheck) { foreach(Id id, parentsToCheck) { //Because we may have just removed a project ReparentingStrategy::updateParents(id); } } void ProjectStrategy::reset() { ReparentingStrategy::reset(); } Qt::ItemFlags ProjectStrategy::flags(const QModelIndex& index, Qt::ItemFlags existingFlags) { Zanshin::ItemType type = (Zanshin::ItemType)index.data(Zanshin::ItemTypeRole).toInt(); if (type == Zanshin::Inbox) { return Qt::ItemIsSelectable | Qt::ItemIsDropEnabled | Qt::ItemIsEnabled; } Akonadi::Collection collection; if (type==Zanshin::Collection) { collection = index.data(Akonadi::EntityTreeModel::CollectionRole).value<Akonadi::Collection>(); } else if (type == Zanshin::ProjectTodo) { //isProject(getId(index), type) FIXME for some reason the item is invalid in getid // We use ParentCollectionRole instead of Akonadi::Item::parentCollection() because the // information about the rights is not valid on retrieved items. collection = index.data(Akonadi::EntityTreeModel::ParentCollectionRole).value<Akonadi::Collection>(); } if (!(collection.rights() & Akonadi::Collection::CanCreateItem)) { existingFlags &= ~Qt::ItemIsDropEnabled; } else { existingFlags |= Qt::ItemIsDropEnabled; } return existingFlags; } Qt::DropActions ProjectStrategy::supportedDropActions() const { return Qt::MoveAction/*|Qt::LinkAction*/; } bool ProjectStrategy::onDropMimeData(Id id, const QMimeData* mimeData, Qt::DropAction action) { if (action != Qt::MoveAction || !KUrl::List::canDecode(mimeData)) { return false; } KUrl::List urls = KUrl::List::fromMimeData(mimeData); PimNode parentNode(PimNode::Invalid); bool forward; Zanshin::ItemType parentType = (Zanshin::ItemType)data(id, 0, Zanshin::ItemTypeRole, forward).toInt(); if (parentType == Zanshin::Collection) { parentNode.collection = getData(id, Akonadi::EntityTreeModel::CollectionRole).value<Akonadi::Collection>(); parentNode.type = PimNode::Collection; } else { parentNode.item = getData(id, Akonadi::EntityTreeModel::ItemRole).value<Akonadi::Item>(); parentNode.collection = parentNode.item.parentCollection(); parentNode.type = PimNode::Project; parentNode.uid = getData(id, Zanshin::UidRole).toString(); } foreach (const KUrl &url, urls) { const Akonadi::Item urlItem = Akonadi::Item::fromUrl(url); //TODO make sure we never get here during testing (although we normally shouldn't anyways if (urlItem.isValid()) { //TODO replace by getData/setData? Akonadi::ItemFetchJob *job = new Akonadi::ItemFetchJob(urlItem); job->fetchScope().setAncestorRetrieval(Akonadi::ItemFetchScope::Parent); job->fetchScope().fetchFullPayload(); if ( !job->exec() ) { continue; } Q_ASSERT(job->items().size()==1); Akonadi::Item item = job->items().first(); Q_ASSERT(item.isValid()); PimNode node(PimNode::Invalid); if (PimItem::itemType(item) == PimItem::Todo) { node.type = PimNode::Todo; } else { node.type = PimNode::Note; } node.item = item; PimItemServices::moveTo(node, parentNode); return true; } } return false; } QVariant ProjectStrategy::data(Id id, int column, int role, bool &forward) const { //We simply override the todometadatamodel data for todos with children (which are also projects) const Zanshin::ItemType itemType = static_cast<Zanshin::ItemType>(getData(id, Zanshin::ItemTypeRole).toInt()); bool project = isProject(id, itemType); switch (role) { case Zanshin::ItemTypeRole: { if (id == mInbox) { return Zanshin::Inbox; } if (project) { return Zanshin::ProjectTodo; } return itemType; } case Qt::CheckStateRole: if (project) { forward = false; return QVariant(); } break; case Qt::DecorationRole: if (project && !column) { return KIcon("view-pim-tasks"); } break; } return QVariant(); } <|endoftext|>
<commit_before>/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2012-2017 Inviwo 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. * * 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 <inviwo/core/util/logcentral.h> #include <inviwo/core/util/stacktrace.h> #include <inviwo/core/util/filesystem.h> #include <inviwo/core/common/inviwoapplication.h> #include <inviwo/core/processors/processor.h> #include <inviwo/core/network/processornetwork.h> namespace inviwo { void Logger::logProcessor(Processor* processor, LogLevel level, LogAudience audience, std::string msg, const char* file, const char* function, int line) { log("Processor " + processor->getIdentifier(), level, audience, file, function, line, msg); } void Logger::logNetwork(LogLevel level, LogAudience audience, std::string msg, const char* file, const char* function, int line) { log("ProcessorNetwork", level, audience, file, function, line, msg); } void Logger::logAssertion(const char* fileName, const char* functionName, long lineNumber, std::string message) { log("Assertion failed", LogLevel::Error, LogAudience::Developer, fileName, functionName, lineNumber, message); } LogCentral::LogCentral() : logLevel_(LogLevel::Info), logStacktrace_(false) {} void LogCentral::registerLogger(std::weak_ptr<Logger> logger) { loggers_.push_back(logger); } void LogCentral::log(std::string source, LogLevel level, LogAudience audience, const char* file, const char* function, int line, std::string msg) { if (logStacktrace_ && level == LogLevel::Error && audience == LogAudience::Developer) { std::stringstream ss; ss << msg; std::vector<std::string> stacktrace = getStackTrace(); // start at i == 3 to remove log and getStacktrace from stackgrace for (size_t i = 3; i < stacktrace.size(); ++i) { ss << std::endl << stacktrace[i]; } // append an extra line break to easier separate several stacktraces in a row ss << std::endl; msg = ss.str(); } if (level >= logLevel_) { // use remove if here to remove expired weak pointers while calling the loggers. util::erase_remove_if(loggers_, [&](const std::weak_ptr<Logger>& logger) { if (auto l = logger.lock()) { l->log(source, level, audience, file, function, line, msg); return false; } else { return true; } }); } } void LogCentral::logProcessor(Processor* processor, LogLevel level, LogAudience audience, std::string msg, const char* file, const char* function, int line) { if (level >= logLevel_) { // use remove if here to remove expired weak pointers while calling the loggers. util::erase_remove_if(loggers_, [&](const std::weak_ptr<Logger>& logger) { if (auto l = logger.lock()) { l->logProcessor(processor, level, audience, msg, file, function, line); return false; } else { return true; } }); } } void LogCentral::logNetwork(LogLevel level, LogAudience audience, std::string msg, const char* file, const char* function, int line) { if (level >= logLevel_) { // use remove if here to remove expired weak pointers while calling the loggers. util::erase_remove_if(loggers_, [&](const std::weak_ptr<Logger>& logger) { if (auto l = logger.lock()) { l->logNetwork(level, audience, msg, file, function, line); return false; } else { return true; } }); } } void LogCentral::logAssertion(const char* fileName, const char* functionName, long lineNumber, std::string message) { util::erase_remove_if(loggers_, [&](const std::weak_ptr<Logger>& logger) { if (auto l = logger.lock()) { l->logAssertion(fileName, functionName, lineNumber, message); return false; } else { return true; } }); } void LogCentral::setLogStacktrace(const bool& logStacktrace) { logStacktrace_ = logStacktrace; } bool LogCentral::getLogStacktrace() const { return logStacktrace_; } void util::log(ExceptionContext context, std::string message, LogLevel level, LogAudience audience) { LogCentral::getPtr()->log(context.getCaller(), level, audience, context.getFile().c_str(), context.getFunction().c_str(), context.getLine(), message); } } // namespace inviwo<commit_msg>Core: added newline<commit_after>/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2012-2017 Inviwo 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. * * 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 <inviwo/core/util/logcentral.h> #include <inviwo/core/util/stacktrace.h> #include <inviwo/core/util/filesystem.h> #include <inviwo/core/common/inviwoapplication.h> #include <inviwo/core/processors/processor.h> #include <inviwo/core/network/processornetwork.h> namespace inviwo { void Logger::logProcessor(Processor* processor, LogLevel level, LogAudience audience, std::string msg, const char* file, const char* function, int line) { log("Processor " + processor->getIdentifier(), level, audience, file, function, line, msg); } void Logger::logNetwork(LogLevel level, LogAudience audience, std::string msg, const char* file, const char* function, int line) { log("ProcessorNetwork", level, audience, file, function, line, msg); } void Logger::logAssertion(const char* fileName, const char* functionName, long lineNumber, std::string message) { log("Assertion failed", LogLevel::Error, LogAudience::Developer, fileName, functionName, lineNumber, message); } LogCentral::LogCentral() : logLevel_(LogLevel::Info), logStacktrace_(false) {} void LogCentral::registerLogger(std::weak_ptr<Logger> logger) { loggers_.push_back(logger); } void LogCentral::log(std::string source, LogLevel level, LogAudience audience, const char* file, const char* function, int line, std::string msg) { if (logStacktrace_ && level == LogLevel::Error && audience == LogAudience::Developer) { std::stringstream ss; ss << msg; std::vector<std::string> stacktrace = getStackTrace(); // start at i == 3 to remove log and getStacktrace from stackgrace for (size_t i = 3; i < stacktrace.size(); ++i) { ss << std::endl << stacktrace[i]; } // append an extra line break to easier separate several stacktraces in a row ss << std::endl; msg = ss.str(); } if (level >= logLevel_) { // use remove if here to remove expired weak pointers while calling the loggers. util::erase_remove_if(loggers_, [&](const std::weak_ptr<Logger>& logger) { if (auto l = logger.lock()) { l->log(source, level, audience, file, function, line, msg); return false; } else { return true; } }); } } void LogCentral::logProcessor(Processor* processor, LogLevel level, LogAudience audience, std::string msg, const char* file, const char* function, int line) { if (level >= logLevel_) { // use remove if here to remove expired weak pointers while calling the loggers. util::erase_remove_if(loggers_, [&](const std::weak_ptr<Logger>& logger) { if (auto l = logger.lock()) { l->logProcessor(processor, level, audience, msg, file, function, line); return false; } else { return true; } }); } } void LogCentral::logNetwork(LogLevel level, LogAudience audience, std::string msg, const char* file, const char* function, int line) { if (level >= logLevel_) { // use remove if here to remove expired weak pointers while calling the loggers. util::erase_remove_if(loggers_, [&](const std::weak_ptr<Logger>& logger) { if (auto l = logger.lock()) { l->logNetwork(level, audience, msg, file, function, line); return false; } else { return true; } }); } } void LogCentral::logAssertion(const char* fileName, const char* functionName, long lineNumber, std::string message) { util::erase_remove_if(loggers_, [&](const std::weak_ptr<Logger>& logger) { if (auto l = logger.lock()) { l->logAssertion(fileName, functionName, lineNumber, message); return false; } else { return true; } }); } void LogCentral::setLogStacktrace(const bool& logStacktrace) { logStacktrace_ = logStacktrace; } bool LogCentral::getLogStacktrace() const { return logStacktrace_; } void util::log(ExceptionContext context, std::string message, LogLevel level, LogAudience audience) { LogCentral::getPtr()->log(context.getCaller(), level, audience, context.getFile().c_str(), context.getFunction().c_str(), context.getLine(), message); } } // namespace inviwo <|endoftext|>
<commit_before>/* Copyright (c) 2008-2014, Avian Contributors Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. There is NO WARRANTY for this software. See license.txt for details. */ #include "jni.h" #include "avian/machine.h" #include "sockets.h" #include "jni-util.h" using namespace avian::classpath::sockets; extern "C" JNIEXPORT void JNICALL Java_java_net_Socket_init(JNIEnv* e, jclass) { init(e); } extern "C" JNIEXPORT SOCKET JNICALL Java_java_net_Socket_create(JNIEnv* e, jclass) { return create(e); } extern "C" JNIEXPORT void JNICALL Java_java_net_Socket_connect(JNIEnv* e, jclass, SOCKET sock, long addr, short port) { connect(e, sock, addr, port); } extern "C" JNIEXPORT void JNICALL Java_java_net_Socket_bind(JNIEnv* e, jclass, SOCKET sock, long addr, short port) { bind(e, sock, addr, port); } extern "C" JNIEXPORT void JNICALL Java_java_net_Socket_abort(JNIEnv* e, jclass, SOCKET sock) { abort(e, sock); } extern "C" JNIEXPORT void JNICALL Java_java_net_Socket_close(JNIEnv* e, jclass, SOCKET sock) { close(e, sock); } extern "C" JNIEXPORT void JNICALL Java_java_net_Socket_closeOutput(JNIEnv* e, jclass, SOCKET sock) { close_output(e, sock); } extern "C" JNIEXPORT void JNICALL Java_java_net_Socket_closeInput(JNIEnv* e, jclass, SOCKET sock) { close_input(e, sock); } extern "C" JNIEXPORT void JNICALL Avian_java_net_Socket_send(vm::Thread* t, vm::object, uintptr_t* arguments) { /* SOCKET s, object buffer_obj, int start_pos, int count */ SOCKET& s = *(reinterpret_cast<SOCKET*>(&arguments[0])); vm::GcByteArray* buffer_obj = vm::cast<vm::GcByteArray>( t, reinterpret_cast<vm::object>(arguments[2])); int32_t& start_pos = *(reinterpret_cast<int32_t*>(&arguments[3])); int32_t& count = *(reinterpret_cast<int32_t*>(&arguments[4])); char* buffer = reinterpret_cast<char*>(&buffer_obj->body()[start_pos]); avian::classpath::sockets::send((JNIEnv*)t, s, buffer, count); } extern "C" JNIEXPORT int64_t JNICALL Avian_java_net_Socket_recv(vm::Thread* t, vm::object, uintptr_t* arguments) { /* SOCKET s, object buffer_obj, int start_pos, int count */ SOCKET& s = *(reinterpret_cast<SOCKET*>(&arguments[0])); vm::GcByteArray* buffer_obj = vm::cast<vm::GcByteArray>( t, reinterpret_cast<vm::object>(arguments[2])); int32_t& start_pos = *(reinterpret_cast<int32_t*>(&arguments[3])); int32_t& count = *(reinterpret_cast<int32_t*>(&arguments[4])); char* buffer = reinterpret_cast<char*>(&buffer_obj->body()[start_pos]); return avian::classpath::sockets::recv((JNIEnv*)t, s, buffer, count); } extern "C" JNIEXPORT jint JNICALL Java_java_net_InetAddress_ipv4AddressForName(JNIEnv* e, jclass, jstring name) { const char* chars = e->GetStringUTFChars(name, 0); if (chars) { #ifdef PLATFORM_WINDOWS hostent* host = gethostbyname(chars); e->ReleaseStringUTFChars(name, chars); if (host) { return ntohl(reinterpret_cast<in_addr*>(host->h_addr_list[0])->s_addr); } else { throwNew(e, "java/net/UnknownHostException", 0); return 0; } #else addrinfo hints; memset(&hints, 0, sizeof(addrinfo)); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; addrinfo* result; int r = getaddrinfo(chars, 0, &hints, &result); e->ReleaseStringUTFChars(name, chars); if (r != 0) { throwNew(e, "java/net/UnknownHostException", 0); return 0; } else { int address = ntohl( reinterpret_cast<sockaddr_in*>(result->ai_addr)->sin_addr.s_addr); freeaddrinfo(result); return address; } #endif } else { throwNew(e, "java/lang/OutOfMemoryError", 0); return 0; } } <commit_msg>cp/avian/java-net.cpp: fix segfault<commit_after>/* Copyright (c) 2008-2014, Avian Contributors Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. There is NO WARRANTY for this software. See license.txt for details. */ #include "jni.h" #include "avian/machine.h" #include "sockets.h" #include "jni-util.h" using namespace avian::classpath::sockets; extern "C" JNIEXPORT void JNICALL Java_java_net_Socket_init(JNIEnv* e, jclass) { init(e); } extern "C" JNIEXPORT SOCKET JNICALL Java_java_net_Socket_create(JNIEnv* e, jclass) { return create(e); } extern "C" JNIEXPORT void JNICALL Java_java_net_Socket_connect(JNIEnv* e, jclass, SOCKET sock, long addr, short port) { connect(e, sock, addr, port); } extern "C" JNIEXPORT void JNICALL Java_java_net_Socket_bind(JNIEnv* e, jclass, SOCKET sock, long addr, short port) { bind(e, sock, addr, port); } extern "C" JNIEXPORT void JNICALL Java_java_net_Socket_abort(JNIEnv* e, jclass, SOCKET sock) { abort(e, sock); } extern "C" JNIEXPORT void JNICALL Java_java_net_Socket_close(JNIEnv* e, jclass, SOCKET sock) { close(e, sock); } extern "C" JNIEXPORT void JNICALL Java_java_net_Socket_closeOutput(JNIEnv* e, jclass, SOCKET sock) { close_output(e, sock); } extern "C" JNIEXPORT void JNICALL Java_java_net_Socket_closeInput(JNIEnv* e, jclass, SOCKET sock) { close_input(e, sock); } extern "C" JNIEXPORT void JNICALL Avian_java_net_Socket_send(vm::Thread* t, vm::object, uintptr_t* arguments) { /* SOCKET s, object buffer_obj, int start_pos, int count */ SOCKET& s = *(reinterpret_cast<SOCKET*>(&arguments[0])); vm::GcByteArray* buffer_obj = vm::cast<vm::GcByteArray>( t, reinterpret_cast<vm::object>(arguments[2])); int32_t& start_pos = *(reinterpret_cast<int32_t*>(&arguments[3])); int32_t& count = *(reinterpret_cast<int32_t*>(&arguments[4])); char* buffer = reinterpret_cast<char*>(&buffer_obj->body()[start_pos]); avian::classpath::sockets::send((JNIEnv*)t, s, buffer, count); } extern "C" JNIEXPORT int64_t JNICALL Avian_java_net_Socket_recv(vm::Thread* t, vm::object, uintptr_t* arguments) { /* SOCKET s, object buffer_obj, int start_pos, int count */ SOCKET& s = *(reinterpret_cast<SOCKET*>(&arguments[0])); vm::GcByteArray* buffer_obj = vm::cast<vm::GcByteArray>( t, reinterpret_cast<vm::object>(arguments[2])); int32_t& start_pos = *(reinterpret_cast<int32_t*>(&arguments[3])); int32_t& count = *(reinterpret_cast<int32_t*>(&arguments[4])); char* buffer = reinterpret_cast<char*>(&buffer_obj->body()[start_pos]); return avian::classpath::sockets::recv((JNIEnv*)t, s, buffer, count); } extern "C" JNIEXPORT jint JNICALL Java_java_net_InetAddress_ipv4AddressForName(JNIEnv* e, jclass, jstring name) { if(!name) { throwNew(e, "java/lang/NullPointerException", 0); return 0; } const char* chars = e->GetStringUTFChars(name, 0); if (chars) { #ifdef PLATFORM_WINDOWS hostent* host = gethostbyname(chars); e->ReleaseStringUTFChars(name, chars); if (host) { return ntohl(reinterpret_cast<in_addr*>(host->h_addr_list[0])->s_addr); } else { throwNew(e, "java/net/UnknownHostException", 0); return 0; } #else addrinfo hints; memset(&hints, 0, sizeof(addrinfo)); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; addrinfo* result; int r = getaddrinfo(chars, 0, &hints, &result); e->ReleaseStringUTFChars(name, chars); if (r != 0) { throwNew(e, "java/net/UnknownHostException", 0); return 0; } else { int address = ntohl( reinterpret_cast<sockaddr_in*>(result->ai_addr)->sin_addr.s_addr); freeaddrinfo(result); return address; } #endif } else { throwNew(e, "java/lang/OutOfMemoryError", 0); return 0; } } <|endoftext|>
<commit_before>/************************************************************************** * * Copyright 2007-2011 VMware, Inc. * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * **************************************************************************/ #include <assert.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "os.hpp" #include "os_thread.hpp" #include "os_string.hpp" #include "trace_file.hpp" #include "trace_writer.hpp" #include "trace_format.hpp" namespace trace { static const char *memcpy_args[3] = {"dest", "src", "n"}; const FunctionSig memcpy_sig = {0, "memcpy", 3, memcpy_args}; static const char *malloc_args[1] = {"size"}; const FunctionSig malloc_sig = {1, "malloc", 1, malloc_args}; static const char *free_args[1] = {"ptr"}; const FunctionSig free_sig = {2, "free", 1, free_args}; static const char *realloc_args[2] = {"ptr", "size"}; const FunctionSig realloc_sig = {3, "realloc", 2, realloc_args}; static void exceptionCallback(void) { localWriter.flush(); } LocalWriter::LocalWriter() : acquired(0) { // Install the signal handlers as early as possible, to prevent // interfering with the application's signal handling. os::setExceptionCallback(exceptionCallback); } LocalWriter::~LocalWriter() { os::resetExceptionCallback(); } void LocalWriter::open(void) { os::String szFileName; const char *lpFileName; lpFileName = getenv("TRACE_FILE"); if (!lpFileName) { static unsigned dwCounter = 0; os::String process = os::getProcessName(); #ifdef _WIN32 process.trimExtension(); #endif process.trimDirectory(); os::String prefix = os::getCurrentDir(); prefix.join(process); for (;;) { FILE *file; if (dwCounter) szFileName = os::String::format("%s.%u.trace", prefix.str(), dwCounter); else szFileName = os::String::format("%s.trace", prefix.str()); lpFileName = szFileName; file = fopen(lpFileName, "rb"); if (file == NULL) break; fclose(file); ++dwCounter; } } os::log("apitrace: tracing to %s\n", lpFileName); if (!Writer::open(lpFileName)) { os::log("apitrace: error: failed to open %s\n", lpFileName); os::abort(); } #if 0 // For debugging the exception handler *((int *)0) = 0; #endif } static unsigned next_thread_id = 0; static os::thread_specific_ptr<unsigned> thread_id_specific_ptr; unsigned LocalWriter::beginEnter(const FunctionSig *sig) { os::acquireMutex(); ++acquired; if (!m_file->isOpened()) { open(); } unsigned *thread_id_ptr = thread_id_specific_ptr.get(); unsigned thread_id; if (thread_id_ptr) { thread_id = *thread_id_ptr; } else { thread_id = next_thread_id++; thread_id_ptr = new unsigned; *thread_id_ptr = thread_id; thread_id_specific_ptr.reset(thread_id_ptr); } return Writer::beginEnter(sig, thread_id); } void LocalWriter::endEnter(void) { Writer::endEnter(); --acquired; os::releaseMutex(); } void LocalWriter::beginLeave(unsigned call) { os::acquireMutex(); ++acquired; Writer::beginLeave(call); } void LocalWriter::endLeave(void) { Writer::endLeave(); --acquired; os::releaseMutex(); } void LocalWriter::flush(void) { /* * Do nothing if the mutex is already acquired (e.g., if a segfault happen * while writing the file) to prevent dead-lock. */ if (!acquired) { os::acquireMutex(); if (m_file->isOpened()) { os::log("apitrace: flushing trace due to an exception\n"); m_file->flush(); } os::releaseMutex(); } } LocalWriter localWriter; } /* namespace trace */ <commit_msg>More helpful messages on exceptions inside apitrace code.<commit_after>/************************************************************************** * * Copyright 2007-2011 VMware, Inc. * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * **************************************************************************/ #include <assert.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "os.hpp" #include "os_thread.hpp" #include "os_string.hpp" #include "trace_file.hpp" #include "trace_writer.hpp" #include "trace_format.hpp" namespace trace { static const char *memcpy_args[3] = {"dest", "src", "n"}; const FunctionSig memcpy_sig = {0, "memcpy", 3, memcpy_args}; static const char *malloc_args[1] = {"size"}; const FunctionSig malloc_sig = {1, "malloc", 1, malloc_args}; static const char *free_args[1] = {"ptr"}; const FunctionSig free_sig = {2, "free", 1, free_args}; static const char *realloc_args[2] = {"ptr", "size"}; const FunctionSig realloc_sig = {3, "realloc", 2, realloc_args}; static void exceptionCallback(void) { localWriter.flush(); } LocalWriter::LocalWriter() : acquired(0) { // Install the signal handlers as early as possible, to prevent // interfering with the application's signal handling. os::setExceptionCallback(exceptionCallback); } LocalWriter::~LocalWriter() { os::resetExceptionCallback(); } void LocalWriter::open(void) { os::String szFileName; const char *lpFileName; lpFileName = getenv("TRACE_FILE"); if (!lpFileName) { static unsigned dwCounter = 0; os::String process = os::getProcessName(); #ifdef _WIN32 process.trimExtension(); #endif process.trimDirectory(); os::String prefix = os::getCurrentDir(); prefix.join(process); for (;;) { FILE *file; if (dwCounter) szFileName = os::String::format("%s.%u.trace", prefix.str(), dwCounter); else szFileName = os::String::format("%s.trace", prefix.str()); lpFileName = szFileName; file = fopen(lpFileName, "rb"); if (file == NULL) break; fclose(file); ++dwCounter; } } os::log("apitrace: tracing to %s\n", lpFileName); if (!Writer::open(lpFileName)) { os::log("apitrace: error: failed to open %s\n", lpFileName); os::abort(); } #if 0 // For debugging the exception handler *((int *)0) = 0; #endif } static unsigned next_thread_id = 0; static os::thread_specific_ptr<unsigned> thread_id_specific_ptr; unsigned LocalWriter::beginEnter(const FunctionSig *sig) { os::acquireMutex(); ++acquired; if (!m_file->isOpened()) { open(); } unsigned *thread_id_ptr = thread_id_specific_ptr.get(); unsigned thread_id; if (thread_id_ptr) { thread_id = *thread_id_ptr; } else { thread_id = next_thread_id++; thread_id_ptr = new unsigned; *thread_id_ptr = thread_id; thread_id_specific_ptr.reset(thread_id_ptr); } return Writer::beginEnter(sig, thread_id); } void LocalWriter::endEnter(void) { Writer::endEnter(); --acquired; os::releaseMutex(); } void LocalWriter::beginLeave(unsigned call) { os::acquireMutex(); ++acquired; Writer::beginLeave(call); } void LocalWriter::endLeave(void) { Writer::endLeave(); --acquired; os::releaseMutex(); } void LocalWriter::flush(void) { /* * Do nothing if the mutex is already acquired (e.g., if a segfault happen * while writing the file) to prevent dead-lock. */ os::acquireMutex(); if (acquired) { os::log("apitrace: ignoring exception while tracing\n"); } else { ++acquired; if (m_file->isOpened()) { os::log("apitrace: flushing trace due to an exception\n"); m_file->flush(); } --acquired; } os::releaseMutex(); } LocalWriter localWriter; } /* namespace trace */ <|endoftext|>
<commit_before>/*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifdef __MINGW32__ // We need to inlclude winbase.h here in order to declare // atomic intrinsics like InterlockedIncrement correctly. // Otherwhise, they would be declared wrong within qatomic_windows.h . #include <windows.h> #endif #include "berryHelpSearchView.h" #include "berryHelpPluginActivator.h" #include "berryQHelpEngineWrapper.h" #include "berryHelpEditorInput.h" #include "berryHelpEditor.h" #include <QLayout> #include <QMenu> #include <QEvent> #include <QMouseEvent> #include <QTextBrowser> #include <QClipboard> #include <QHelpSearchQueryWidget> #include <QHelpSearchResultWidget> #include <QApplication> namespace berry { HelpSearchView::HelpSearchView() : m_ZoomCount(0) , m_Parent(0) , m_SearchEngine(HelpPluginActivator::getInstance()->getQHelpEngine().searchEngine()) , m_ResultWidget(0) , m_QueryWidget(0) { } HelpSearchView::~HelpSearchView() { // prevent deletion of the widget m_ResultWidget->setParent(0); } void HelpSearchView::CreateQtPartControl(QWidget* parent) { if (m_ResultWidget == 0) { m_Parent = parent; QVBoxLayout* vLayout = new QVBoxLayout(parent); // This will be lead to strange behavior when using multiple instances of this view // because the QHelpSearchResultWidget instance is shared. The new view will // reparent the widget. m_ResultWidget = m_SearchEngine->resultWidget(); m_QueryWidget = new QHelpSearchQueryWidget(); vLayout->addWidget(m_QueryWidget); vLayout->addWidget(m_ResultWidget); connect(m_QueryWidget, SIGNAL(search()), this, SLOT(search())); connect(m_ResultWidget, SIGNAL(requestShowLink(QUrl)), this, SLOT(requestShowLink(QUrl))); connect(m_SearchEngine, SIGNAL(searchingStarted()), this, SLOT(searchingStarted())); connect(m_SearchEngine, SIGNAL(searchingFinished(int)), this, SLOT(searchingFinished(int))); QTextBrowser* browser = qFindChild<QTextBrowser*>(m_ResultWidget); if (browser) // Will be null if QtHelp was configured not to use CLucene. { browser->viewport()->installEventFilter(this); browser->setContextMenuPolicy(Qt::CustomContextMenu); connect(browser, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(showContextMenu(QPoint))); } } } void HelpSearchView::SetFocus() { if (!(m_ResultWidget->hasFocus())) { m_QueryWidget->setFocus(); } } void HelpSearchView::zoomIn() { QTextBrowser* browser = qFindChild<QTextBrowser*>(m_ResultWidget); if (browser && m_ZoomCount != 10) { m_ZoomCount++; browser->zoomIn(); } } void HelpSearchView::zoomOut() { QTextBrowser* browser = qFindChild<QTextBrowser*>(m_ResultWidget); if (browser && m_ZoomCount != -5) { m_ZoomCount--; browser->zoomOut(); } } void HelpSearchView::resetZoom() { if (m_ZoomCount == 0) return; QTextBrowser* browser = qFindChild<QTextBrowser*>(m_ResultWidget); if (browser) { browser->zoomOut(m_ZoomCount); m_ZoomCount = 0; } } void HelpSearchView::search() const { QList<QHelpSearchQuery> query = m_QueryWidget->query(); m_SearchEngine->search(query); } void HelpSearchView::searchingStarted() { m_Parent->setCursor(QCursor(Qt::WaitCursor)); } void HelpSearchView::searchingFinished(int hits) { Q_UNUSED(hits) m_Parent->unsetCursor(); //qApp->restoreOverrideCursor(); } void HelpSearchView::requestShowLink(const QUrl &link) { HelpPluginActivator::linkActivated(this->GetSite()->GetPage(), link); } bool HelpSearchView::eventFilter(QObject* o, QEvent *e) { QTextBrowser* browser = qFindChild<QTextBrowser*>(m_ResultWidget); if (browser && o == browser->viewport() && e->type() == QEvent::MouseButtonRelease) { QMouseEvent* me = static_cast<QMouseEvent*>(e); QUrl link = m_ResultWidget->linkAt(me->pos()); if (!link.isEmpty() || link.isValid()) { bool controlPressed = me->modifiers() & Qt::ControlModifier; if((me->button() == Qt::LeftButton && controlPressed) || (me->button() == Qt::MidButton)) { IEditorInput::Pointer input(new HelpEditorInput(link)); this->GetSite()->GetPage()->OpenEditor(input, HelpEditor::EDITOR_ID); } } } return QObject::eventFilter(o,e); } void HelpSearchView::showContextMenu(const QPoint& point) { QMenu menu; QTextBrowser* browser = qFindChild<QTextBrowser*>(m_ResultWidget); if (!browser) return; // QPoint point = browser->mapFromGlobal(pos); // if (!browser->rect().contains(point, true)) // return; QUrl link = browser->anchorAt(point); QKeySequence keySeq(QKeySequence::Copy); QAction *copyAction = menu.addAction(tr("&Copy") + QLatin1String("\t") + keySeq.toString(QKeySequence::NativeText)); copyAction->setEnabled(QTextCursor(browser->textCursor()).hasSelection()); QAction *copyAnchorAction = menu.addAction(tr("Copy &Link Location")); copyAnchorAction->setEnabled(!link.isEmpty() && link.isValid()); keySeq = QKeySequence(Qt::CTRL); QAction *newTabAction = menu.addAction(tr("Open Link in New Tab") + QLatin1String("\t") + keySeq.toString(QKeySequence::NativeText) + QLatin1String("LMB")); newTabAction->setEnabled(!link.isEmpty() && link.isValid()); menu.addSeparator(); keySeq = QKeySequence::SelectAll; QAction *selectAllAction = menu.addAction(tr("Select All") + QLatin1String("\t") + keySeq.toString(QKeySequence::NativeText)); QAction *usedAction = menu.exec(browser->mapToGlobal(point)); if (usedAction == copyAction) { QTextCursor cursor = browser->textCursor(); if (!cursor.isNull() && cursor.hasSelection()) { QString selectedText = cursor.selectedText(); QMimeData *data = new QMimeData(); data->setText(selectedText); QApplication::clipboard()->setMimeData(data); } } else if (usedAction == copyAnchorAction) { QApplication::clipboard()->setText(link.toString()); } else if (usedAction == newTabAction) { IEditorInput::Pointer input(new HelpEditorInput(link)); this->GetSite()->GetPage()->OpenEditor(input, HelpEditor::EDITOR_ID); } else if (usedAction == selectAllAction) { browser->selectAll(); } } } <commit_msg>Replaced qFindChild macros with equivalent QObject::findChild method calls.<commit_after>/*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifdef __MINGW32__ // We need to inlclude winbase.h here in order to declare // atomic intrinsics like InterlockedIncrement correctly. // Otherwhise, they would be declared wrong within qatomic_windows.h . #include <windows.h> #endif #include "berryHelpSearchView.h" #include "berryHelpPluginActivator.h" #include "berryQHelpEngineWrapper.h" #include "berryHelpEditorInput.h" #include "berryHelpEditor.h" #include <QLayout> #include <QMenu> #include <QEvent> #include <QMouseEvent> #include <QMimeData> #include <QTextBrowser> #include <QClipboard> #include <QHelpSearchQueryWidget> #include <QHelpSearchResultWidget> #include <QApplication> namespace berry { HelpSearchView::HelpSearchView() : m_ZoomCount(0) , m_Parent(0) , m_SearchEngine(HelpPluginActivator::getInstance()->getQHelpEngine().searchEngine()) , m_ResultWidget(0) , m_QueryWidget(0) { } HelpSearchView::~HelpSearchView() { // prevent deletion of the widget m_ResultWidget->setParent(0); } void HelpSearchView::CreateQtPartControl(QWidget* parent) { if (m_ResultWidget == 0) { m_Parent = parent; QVBoxLayout* vLayout = new QVBoxLayout(parent); // This will be lead to strange behavior when using multiple instances of this view // because the QHelpSearchResultWidget instance is shared. The new view will // reparent the widget. m_ResultWidget = m_SearchEngine->resultWidget(); m_QueryWidget = new QHelpSearchQueryWidget(); vLayout->addWidget(m_QueryWidget); vLayout->addWidget(m_ResultWidget); connect(m_QueryWidget, SIGNAL(search()), this, SLOT(search())); connect(m_ResultWidget, SIGNAL(requestShowLink(QUrl)), this, SLOT(requestShowLink(QUrl))); connect(m_SearchEngine, SIGNAL(searchingStarted()), this, SLOT(searchingStarted())); connect(m_SearchEngine, SIGNAL(searchingFinished(int)), this, SLOT(searchingFinished(int))); QTextBrowser* browser = m_ResultWidget->findChild<QTextBrowser*>(); if (browser) // Will be null if QtHelp was configured not to use CLucene. { browser->viewport()->installEventFilter(this); browser->setContextMenuPolicy(Qt::CustomContextMenu); connect(browser, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(showContextMenu(QPoint))); } } } void HelpSearchView::SetFocus() { if (!(m_ResultWidget->hasFocus())) { m_QueryWidget->setFocus(); } } void HelpSearchView::zoomIn() { QTextBrowser* browser = m_ResultWidget->findChild<QTextBrowser*>(); if (browser && m_ZoomCount != 10) { m_ZoomCount++; browser->zoomIn(); } } void HelpSearchView::zoomOut() { QTextBrowser* browser = m_ResultWidget->findChild<QTextBrowser*>(); if (browser && m_ZoomCount != -5) { m_ZoomCount--; browser->zoomOut(); } } void HelpSearchView::resetZoom() { if (m_ZoomCount == 0) return; QTextBrowser* browser = m_ResultWidget->findChild<QTextBrowser*>(); if (browser) { browser->zoomOut(m_ZoomCount); m_ZoomCount = 0; } } void HelpSearchView::search() const { QList<QHelpSearchQuery> query = m_QueryWidget->query(); m_SearchEngine->search(query); } void HelpSearchView::searchingStarted() { m_Parent->setCursor(QCursor(Qt::WaitCursor)); } void HelpSearchView::searchingFinished(int hits) { Q_UNUSED(hits) m_Parent->unsetCursor(); //qApp->restoreOverrideCursor(); } void HelpSearchView::requestShowLink(const QUrl &link) { HelpPluginActivator::linkActivated(this->GetSite()->GetPage(), link); } bool HelpSearchView::eventFilter(QObject* o, QEvent *e) { QTextBrowser* browser = m_ResultWidget->findChild<QTextBrowser*>(); if (browser && o == browser->viewport() && e->type() == QEvent::MouseButtonRelease) { QMouseEvent* me = static_cast<QMouseEvent*>(e); QUrl link = m_ResultWidget->linkAt(me->pos()); if (!link.isEmpty() || link.isValid()) { bool controlPressed = me->modifiers() & Qt::ControlModifier; if((me->button() == Qt::LeftButton && controlPressed) || (me->button() == Qt::MidButton)) { IEditorInput::Pointer input(new HelpEditorInput(link)); this->GetSite()->GetPage()->OpenEditor(input, HelpEditor::EDITOR_ID); } } } return QObject::eventFilter(o,e); } void HelpSearchView::showContextMenu(const QPoint& point) { QMenu menu; QTextBrowser* browser = m_ResultWidget->findChild<QTextBrowser*>(); if (!browser) return; // QPoint point = browser->mapFromGlobal(pos); // if (!browser->rect().contains(point, true)) // return; QUrl link = browser->anchorAt(point); QKeySequence keySeq(QKeySequence::Copy); QAction *copyAction = menu.addAction(tr("&Copy") + QLatin1String("\t") + keySeq.toString(QKeySequence::NativeText)); copyAction->setEnabled(QTextCursor(browser->textCursor()).hasSelection()); QAction *copyAnchorAction = menu.addAction(tr("Copy &Link Location")); copyAnchorAction->setEnabled(!link.isEmpty() && link.isValid()); keySeq = QKeySequence(Qt::CTRL); QAction *newTabAction = menu.addAction(tr("Open Link in New Tab") + QLatin1String("\t") + keySeq.toString(QKeySequence::NativeText) + QLatin1String("LMB")); newTabAction->setEnabled(!link.isEmpty() && link.isValid()); menu.addSeparator(); keySeq = QKeySequence::SelectAll; QAction *selectAllAction = menu.addAction(tr("Select All") + QLatin1String("\t") + keySeq.toString(QKeySequence::NativeText)); QAction *usedAction = menu.exec(browser->mapToGlobal(point)); if (usedAction == copyAction) { QTextCursor cursor = browser->textCursor(); if (!cursor.isNull() && cursor.hasSelection()) { QString selectedText = cursor.selectedText(); QMimeData *data = new QMimeData(); data->setText(selectedText); QApplication::clipboard()->setMimeData(data); } } else if (usedAction == copyAnchorAction) { QApplication::clipboard()->setText(link.toString()); } else if (usedAction == newTabAction) { IEditorInput::Pointer input(new HelpEditorInput(link)); this->GetSite()->GetPage()->OpenEditor(input, HelpEditor::EDITOR_ID); } else if (usedAction == selectAllAction) { browser->selectAll(); } } } <|endoftext|>
<commit_before>/* * Copyright (c) 2008-2016 the MRtrix3 contributors * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/ * * MRtrix 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. * * For more details, see www.mrtrix.org * */ #include "command.h" #include "memory.h" #include "dwi/fmls.h" #include "dwi/tractography/file.h" #include "dwi/tractography/properties.h" #include "dwi/tractography/mapping/loader.h" #include "dwi/tractography/mapping/mapper.h" #include "dwi/tractography/mapping/mapping.h" #include "dwi/tractography/SIFT/model_base.h" using namespace MR; using namespace MR::DWI; using namespace App; void usage () { AUTHOR = "David Raffelt (david.raffelt@florey.edu.au) and Robert E. Smith (robert.smith@florey.edu.au)"; DESCRIPTION + "obtain an estimate of fibre connectivity between two regions using AFD and streamlines tractography" + "This estimate is obtained by determining a fibre volume (AFD) occupied by the pathway " "of interest, and dividing by the streamline length." + "If only the streamlines belonging to the pathway of interest are provided, then " "ALL of the fibre volume within each fixel selected will contribute to the result. " "If the -wbft option is used to provide whole-brain fibre-tracking (of which the pathway of " "interest should contain a subset), only the fraction of the fibre volume in each fixel " "estiamted to belong to the pathway of interest will contribute to the result." + "Use -quiet to suppress progress messages and output fibre connectivity value only." + "For valid comparisons of AFD connectivity across scans, images MUST be intensity " "normalised and bias field corrected, and a common response function for all subjects " "must be used." + "Note that the sum of the AFD is normalised by streamline length to " "account for subject differences in fibre bundle length. This normalisation results in a measure " "that is more related to the cross-sectional volume of the tract (and therefore 'connectivity'). " "Note that SIFT-ed tract count is a superior measure because it is unaffected by tangential yet unrelated " "fibres. However, AFD connectivity may be used as a substitute when Anatomically Constrained Tractography " "is not possible due to uncorrectable EPI distortions, and SIFT may therefore not be as effective."; ARGUMENTS + Argument ("image", "the input FOD image.").type_image_in() + Argument ("tracks", "the input track file defining the bundle of interest.").type_tracks_in(); OPTIONS + Option ("wbft", "provide a whole-brain fibre-tracking data set (of which the input track file " "should be a subset), to improve the estimate of fibre bundle volume in the " "presence of partial volume") + Argument ("tracks").type_tracks_in() + Option ("afd_map", "output a 3D image containing the AFD estimated for each voxel.") + Argument ("image").type_image_out() + Option ("all_fixels", "if whole-brain fibre-tracking is NOT provided, then if multiple fixels within " "a voxel are traversed by the pathway of interest, by default the fixel with the " "greatest streamlines density is selected to contribute to the AFD in that voxel. " "If this option is provided, then ALL fixels with non-zero streamlines density " "will contribute to the result, even if multiple fixels per voxel are selected."); } typedef float value_type; typedef DWI::Tractography::Mapping::SetDixel SetDixel; typedef DWI::Tractography::SIFT::FixelBase FixelBase; class Fixel : public FixelBase { public: Fixel () : FixelBase (), length (0.0) { } Fixel (const FMLS::FOD_lobe& lobe) : FixelBase (lobe), length (0.0) { } Fixel (const Fixel& that) : FixelBase (that), length (that.length) { } void add_to_selection (const value_type l) { length += l; } value_type get_selected_volume (const value_type l) const { return get_TD() ? (get_FOD() * (l / get_TD())) : 0.0; } value_type get_selected_volume () const { return get_TD() ? (get_FOD() * (length / get_TD())) : 0.0; } value_type get_selected_length() const { return length; } bool is_selected() const { return length; } private: value_type length; }; class AFDConnectivity : public DWI::Tractography::SIFT::ModelBase<Fixel> { public: AFDConnectivity (Image<value_type>& fod_buffer, const DWI::Directions::FastLookupSet& dirs, const std::string& tck_path, const std::string& wbft_path) : DWI::Tractography::SIFT::ModelBase<Fixel> (fod_buffer, dirs), have_wbft (wbft_path.size()), all_fixels (false), mapper (fod_buffer, dirs), v_fod (fod_buffer) { if (have_wbft) { perform_FOD_segmentation (fod_buffer); map_streamlines (wbft_path); } else { fmls.reset (new DWI::FMLS::Segmenter (dirs, Math::SH::LforN (fod_buffer.size (3)))); } mapper.set_upsample_ratio (DWI::Tractography::Mapping::determine_upsample_ratio (fod_buffer, tck_path, 0.1)); mapper.set_use_precise_mapping (true); } void set_all_fixels (const bool i) { all_fixels = i; } value_type get (const std::string& path); void save (const std::string& path); private: const bool have_wbft; bool all_fixels; DWI::Tractography::Mapping::TrackMapperBase mapper; Image<value_type> v_fod; copy_ptr<DWI::FMLS::Segmenter> fmls; using Fixel_map<Fixel>::accessor; }; value_type AFDConnectivity::get (const std::string& path) { Tractography::Properties properties; Tractography::Reader<value_type> reader (path, properties); const size_t track_count = (properties.find ("count") == properties.end() ? 0 : to<size_t>(properties["count"])); DWI::Tractography::Mapping::TrackLoader loader (reader, track_count, "summing apparent fibre density within track"); // If WBFT is provided, this is the sum of (volume/length) across streamlines // Otherwise, it's a sum of lengths of all streamlines (for later scaling by mean streamline length) double sum_contributions = 0.0; size_t count = 0; Tractography::Streamline<value_type> tck; while (loader (tck)) { ++count; SetDixel dixels; mapper (tck, dixels); double this_length = 0.0, this_volume = 0.0; for (SetDixel::const_iterator i = dixels.begin(); i != dixels.end(); ++i) { this_length += i->get_length(); // If wbft has not been provided (i.e. FODs have not been pre-segmented), need to // check to see if any data have been provided for this voxel; and if not yet, // run the segmenter if (!have_wbft) { VoxelAccessor v (accessor()); assign_pos_of (*i, 0, 3).to (v); if (!v.value()) { assign_pos_of (*i, 0, 3).to (v_fod); DWI::FMLS::SH_coefs fod_data; DWI::FMLS::FOD_lobes fod_lobes; fod_data.vox[0] = v_fod.index (0); fod_data.vox[1] = v_fod.index (1); fod_data.vox[2] = v_fod.index (2); fod_data.resize (v_fod.size (3)); for (auto i = Loop(3) (v_fod); i; ++i) fod_data[v_fod.index (3)] = v_fod.value(); (*fmls) (fod_data, fod_lobes); (*this) (fod_lobes); } } const size_t fixel_index = dixel2fixel (*i); Fixel& fixel = fixels[fixel_index]; fixel.add_to_selection (i->get_length()); if (have_wbft) this_volume += fixel.get_selected_volume (i->get_length()); } if (have_wbft) sum_contributions += (this_volume / this_length); else sum_contributions += this_length; } if (!have_wbft) { // Streamlines define a fixel mask; go through and get all the fibre volumes double sum_volumes = 0.0; if (all_fixels) { // All fixels contribute to the result for (std::vector<Fixel>::const_iterator i = fixels.begin(); i != fixels.end(); ++i) { if (i->is_selected()) sum_volumes += i->get_FOD(); } } else { // Only allow one fixel per voxel to contribute to the result VoxelAccessor v (accessor()); for (auto l = Loop(v) (v); l; ++l) { if (v.value()) { value_type voxel_afd = 0.0, max_td = 0.0; for (Fixel_map<Fixel>::Iterator i = begin (v); i; ++i) { if (i().get_selected_length() > max_td) { max_td = i().get_selected_length(); voxel_afd = i().get_FOD(); } } sum_volumes += voxel_afd; } } } // sum_contributions currently stores sum of streamline lengths; // turn into a mean length, then combine with volume to get a connectivity value const double mean_length = sum_contributions / double(count); sum_contributions = sum_volumes / mean_length; } return sum_contributions; } void AFDConnectivity::save (const std::string& path) { auto out = Image<value_type>::create (path, original_header()); VoxelAccessor v (accessor()); for (auto l = Loop(v) (v, out); l; ++l) { value_type value = 0.0; if (have_wbft) { for (Fixel_map<Fixel>::Iterator i = begin (v); i; ++i) value += i().get_selected_volume(); } else if (all_fixels) { for (Fixel_map<Fixel>::Iterator i = begin (v); i; ++i) value += (i().is_selected() ? i().get_FOD() : 0.0); } else { value_type max_td = 0.0; for (Fixel_map<Fixel>::Iterator i = begin (v); i; ++i) { if (i().get_selected_length() > max_td) { max_td = i().get_selected_length(); value = i().get_FOD(); } } } out.value() = value; } } void run () { auto opt = get_options ("wbft"); const std::string wbft_path = opt.size() ? str(opt[0][0]) : ""; DWI::Directions::FastLookupSet dirs (1281); auto fod = Image<value_type>::open (argument[0]); Math::SH::check (fod); AFDConnectivity model (fod, dirs, argument[1], wbft_path); opt = get_options ("all_fixels"); model.set_all_fixels (opt.size()); const value_type connectivity_value = model.get (argument[1]); // output the AFD sum using std::cout. This enables output to be redirected to a file without the console output. std::cout << connectivity_value << std::endl; opt = get_options ("afd_map"); if (opt.size()) model.save (opt[0][0]); } <commit_msg>estiamted -> estimated<commit_after>/* * Copyright (c) 2008-2016 the MRtrix3 contributors * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/ * * MRtrix 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. * * For more details, see www.mrtrix.org * */ #include "command.h" #include "memory.h" #include "dwi/fmls.h" #include "dwi/tractography/file.h" #include "dwi/tractography/properties.h" #include "dwi/tractography/mapping/loader.h" #include "dwi/tractography/mapping/mapper.h" #include "dwi/tractography/mapping/mapping.h" #include "dwi/tractography/SIFT/model_base.h" using namespace MR; using namespace MR::DWI; using namespace App; void usage () { AUTHOR = "David Raffelt (david.raffelt@florey.edu.au) and Robert E. Smith (robert.smith@florey.edu.au)"; DESCRIPTION + "obtain an estimate of fibre connectivity between two regions using AFD and streamlines tractography" + "This estimate is obtained by determining a fibre volume (AFD) occupied by the pathway " "of interest, and dividing by the streamline length." + "If only the streamlines belonging to the pathway of interest are provided, then " "ALL of the fibre volume within each fixel selected will contribute to the result. " "If the -wbft option is used to provide whole-brain fibre-tracking (of which the pathway of " "interest should contain a subset), only the fraction of the fibre volume in each fixel " "estimated to belong to the pathway of interest will contribute to the result." + "Use -quiet to suppress progress messages and output fibre connectivity value only." + "For valid comparisons of AFD connectivity across scans, images MUST be intensity " "normalised and bias field corrected, and a common response function for all subjects " "must be used." + "Note that the sum of the AFD is normalised by streamline length to " "account for subject differences in fibre bundle length. This normalisation results in a measure " "that is more related to the cross-sectional volume of the tract (and therefore 'connectivity'). " "Note that SIFT-ed tract count is a superior measure because it is unaffected by tangential yet unrelated " "fibres. However, AFD connectivity may be used as a substitute when Anatomically Constrained Tractography " "is not possible due to uncorrectable EPI distortions, and SIFT may therefore not be as effective."; ARGUMENTS + Argument ("image", "the input FOD image.").type_image_in() + Argument ("tracks", "the input track file defining the bundle of interest.").type_tracks_in(); OPTIONS + Option ("wbft", "provide a whole-brain fibre-tracking data set (of which the input track file " "should be a subset), to improve the estimate of fibre bundle volume in the " "presence of partial volume") + Argument ("tracks").type_tracks_in() + Option ("afd_map", "output a 3D image containing the AFD estimated for each voxel.") + Argument ("image").type_image_out() + Option ("all_fixels", "if whole-brain fibre-tracking is NOT provided, then if multiple fixels within " "a voxel are traversed by the pathway of interest, by default the fixel with the " "greatest streamlines density is selected to contribute to the AFD in that voxel. " "If this option is provided, then ALL fixels with non-zero streamlines density " "will contribute to the result, even if multiple fixels per voxel are selected."); } typedef float value_type; typedef DWI::Tractography::Mapping::SetDixel SetDixel; typedef DWI::Tractography::SIFT::FixelBase FixelBase; class Fixel : public FixelBase { public: Fixel () : FixelBase (), length (0.0) { } Fixel (const FMLS::FOD_lobe& lobe) : FixelBase (lobe), length (0.0) { } Fixel (const Fixel& that) : FixelBase (that), length (that.length) { } void add_to_selection (const value_type l) { length += l; } value_type get_selected_volume (const value_type l) const { return get_TD() ? (get_FOD() * (l / get_TD())) : 0.0; } value_type get_selected_volume () const { return get_TD() ? (get_FOD() * (length / get_TD())) : 0.0; } value_type get_selected_length() const { return length; } bool is_selected() const { return length; } private: value_type length; }; class AFDConnectivity : public DWI::Tractography::SIFT::ModelBase<Fixel> { public: AFDConnectivity (Image<value_type>& fod_buffer, const DWI::Directions::FastLookupSet& dirs, const std::string& tck_path, const std::string& wbft_path) : DWI::Tractography::SIFT::ModelBase<Fixel> (fod_buffer, dirs), have_wbft (wbft_path.size()), all_fixels (false), mapper (fod_buffer, dirs), v_fod (fod_buffer) { if (have_wbft) { perform_FOD_segmentation (fod_buffer); map_streamlines (wbft_path); } else { fmls.reset (new DWI::FMLS::Segmenter (dirs, Math::SH::LforN (fod_buffer.size (3)))); } mapper.set_upsample_ratio (DWI::Tractography::Mapping::determine_upsample_ratio (fod_buffer, tck_path, 0.1)); mapper.set_use_precise_mapping (true); } void set_all_fixels (const bool i) { all_fixels = i; } value_type get (const std::string& path); void save (const std::string& path); private: const bool have_wbft; bool all_fixels; DWI::Tractography::Mapping::TrackMapperBase mapper; Image<value_type> v_fod; copy_ptr<DWI::FMLS::Segmenter> fmls; using Fixel_map<Fixel>::accessor; }; value_type AFDConnectivity::get (const std::string& path) { Tractography::Properties properties; Tractography::Reader<value_type> reader (path, properties); const size_t track_count = (properties.find ("count") == properties.end() ? 0 : to<size_t>(properties["count"])); DWI::Tractography::Mapping::TrackLoader loader (reader, track_count, "summing apparent fibre density within track"); // If WBFT is provided, this is the sum of (volume/length) across streamlines // Otherwise, it's a sum of lengths of all streamlines (for later scaling by mean streamline length) double sum_contributions = 0.0; size_t count = 0; Tractography::Streamline<value_type> tck; while (loader (tck)) { ++count; SetDixel dixels; mapper (tck, dixels); double this_length = 0.0, this_volume = 0.0; for (SetDixel::const_iterator i = dixels.begin(); i != dixels.end(); ++i) { this_length += i->get_length(); // If wbft has not been provided (i.e. FODs have not been pre-segmented), need to // check to see if any data have been provided for this voxel; and if not yet, // run the segmenter if (!have_wbft) { VoxelAccessor v (accessor()); assign_pos_of (*i, 0, 3).to (v); if (!v.value()) { assign_pos_of (*i, 0, 3).to (v_fod); DWI::FMLS::SH_coefs fod_data; DWI::FMLS::FOD_lobes fod_lobes; fod_data.vox[0] = v_fod.index (0); fod_data.vox[1] = v_fod.index (1); fod_data.vox[2] = v_fod.index (2); fod_data.resize (v_fod.size (3)); for (auto i = Loop(3) (v_fod); i; ++i) fod_data[v_fod.index (3)] = v_fod.value(); (*fmls) (fod_data, fod_lobes); (*this) (fod_lobes); } } const size_t fixel_index = dixel2fixel (*i); Fixel& fixel = fixels[fixel_index]; fixel.add_to_selection (i->get_length()); if (have_wbft) this_volume += fixel.get_selected_volume (i->get_length()); } if (have_wbft) sum_contributions += (this_volume / this_length); else sum_contributions += this_length; } if (!have_wbft) { // Streamlines define a fixel mask; go through and get all the fibre volumes double sum_volumes = 0.0; if (all_fixels) { // All fixels contribute to the result for (std::vector<Fixel>::const_iterator i = fixels.begin(); i != fixels.end(); ++i) { if (i->is_selected()) sum_volumes += i->get_FOD(); } } else { // Only allow one fixel per voxel to contribute to the result VoxelAccessor v (accessor()); for (auto l = Loop(v) (v); l; ++l) { if (v.value()) { value_type voxel_afd = 0.0, max_td = 0.0; for (Fixel_map<Fixel>::Iterator i = begin (v); i; ++i) { if (i().get_selected_length() > max_td) { max_td = i().get_selected_length(); voxel_afd = i().get_FOD(); } } sum_volumes += voxel_afd; } } } // sum_contributions currently stores sum of streamline lengths; // turn into a mean length, then combine with volume to get a connectivity value const double mean_length = sum_contributions / double(count); sum_contributions = sum_volumes / mean_length; } return sum_contributions; } void AFDConnectivity::save (const std::string& path) { auto out = Image<value_type>::create (path, original_header()); VoxelAccessor v (accessor()); for (auto l = Loop(v) (v, out); l; ++l) { value_type value = 0.0; if (have_wbft) { for (Fixel_map<Fixel>::Iterator i = begin (v); i; ++i) value += i().get_selected_volume(); } else if (all_fixels) { for (Fixel_map<Fixel>::Iterator i = begin (v); i; ++i) value += (i().is_selected() ? i().get_FOD() : 0.0); } else { value_type max_td = 0.0; for (Fixel_map<Fixel>::Iterator i = begin (v); i; ++i) { if (i().get_selected_length() > max_td) { max_td = i().get_selected_length(); value = i().get_FOD(); } } } out.value() = value; } } void run () { auto opt = get_options ("wbft"); const std::string wbft_path = opt.size() ? str(opt[0][0]) : ""; DWI::Directions::FastLookupSet dirs (1281); auto fod = Image<value_type>::open (argument[0]); Math::SH::check (fod); AFDConnectivity model (fod, dirs, argument[1], wbft_path); opt = get_options ("all_fixels"); model.set_all_fixels (opt.size()); const value_type connectivity_value = model.get (argument[1]); // output the AFD sum using std::cout. This enables output to be redirected to a file without the console output. std::cout << connectivity_value << std::endl; opt = get_options ("afd_map"); if (opt.size()) model.save (opt[0][0]); } <|endoftext|>
<commit_before>/************************************************************************* * UrBackup - Client/Server backup system * Copyright (C) 2021 Martin Raiber * * 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/>. **************************************************************************/ #ifdef _WIN32 #define DLLEXPORT extern "C" __declspec (dllexport) #else #define DLLEXPORT extern "C" #endif #ifndef STATIC_PLUGIN #define DEF_SERVER #endif #include "../Interface/Server.h" #include "pluginmgr.h" #include "../stringtools.h" #include "../urbackupcommon/WalCheckpointThread.h" #include <aws/core/utils/logging/AWSLogging.h> #include <aws/core/utils/logging/FormattedLogSystem.h> #include <aws/core/Aws.h> #include "../urbackupcommon/os_functions.h" #ifndef STATIC_PLUGIN IServer* Server; #else #include "../StaticPluginRegistration.h" extern IServer* Server; #define LoadActions LoadActions_clouddrive #define UnloadActions UnloadActions_clouddrive #endif void init_compress_encrypt_factory(); bool is_automount_finished() { return false; } std::string getCdInterfacePath() { os_create_dir("urbackup/cd"); return "urbackup/cd"; } class ServerLogging : public Aws::Utils::Logging::FormattedLogSystem { public: ServerLogging(Aws::Utils::Logging::LogLevel loglevel) : Aws::Utils::Logging::FormattedLogSystem(loglevel) {} void Flush() {} protected: virtual void ProcessFormattedStatement(Aws::String&& statement) { Server->Log(trim(statement.c_str()), LL_INFO); } }; ClouddrivePluginMgr* clouddrivepluginmgr; DLLEXPORT void LoadActions(IServer* pServer) { Server = pServer; WalCheckpointThread::init_mutex(); clouddrivepluginmgr = new ClouddrivePluginMgr; init_compress_encrypt_factory(); Aws::SDKOptions options; Aws::InitAPI(options); Aws::Utils::Logging::InitializeAWSLogging(Aws::MakeShared<ServerLogging>("KvStoreBackend", Aws::Utils::Logging::LogLevel::Warn)); Server->RegisterPluginThreadsafeModel(clouddrivepluginmgr, "clouddriveplugin"); #ifndef STATIC_PLUGIN Server->Log("Loaded -btrfsplugin- plugin", LL_INFO); #endif } DLLEXPORT void UnloadActions(void) { if (Server->getServerParameter("leak_check") == "true") { Aws::SDKOptions options; Aws::ShutdownAPI(options); } } #ifdef STATIC_PLUGIN namespace { static RegisterPluginHelper register_plugin(LoadActions, UnloadActions, 10); } #endif<commit_msg>Fix initialization<commit_after>/************************************************************************* * UrBackup - Client/Server backup system * Copyright (C) 2021 Martin Raiber * * 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/>. **************************************************************************/ #ifdef _WIN32 #define DLLEXPORT extern "C" __declspec (dllexport) #else #define DLLEXPORT extern "C" #endif #ifndef STATIC_PLUGIN #define DEF_SERVER #endif #include "../Interface/Server.h" #include "pluginmgr.h" #include "../stringtools.h" #include "../urbackupcommon/WalCheckpointThread.h" #include <aws/core/utils/logging/AWSLogging.h> #include <aws/core/utils/logging/FormattedLogSystem.h> #include <aws/core/Aws.h> #include "../urbackupcommon/os_functions.h" #ifndef STATIC_PLUGIN IServer* Server; #else #include "../StaticPluginRegistration.h" extern IServer* Server; #define LoadActions LoadActions_clouddrive #define UnloadActions UnloadActions_clouddrive #endif #include "KvStoreBackendS3.h" void init_compress_encrypt_factory(); bool is_automount_finished() { return false; } std::string getCdInterfacePath() { os_create_dir("urbackup/cd"); return "urbackup/cd"; } class ServerLogging : public Aws::Utils::Logging::FormattedLogSystem { public: ServerLogging(Aws::Utils::Logging::LogLevel loglevel) : Aws::Utils::Logging::FormattedLogSystem(loglevel) {} void Flush() {} protected: virtual void ProcessFormattedStatement(Aws::String&& statement) { Server->Log(trim(statement.c_str()), LL_INFO); } }; ClouddrivePluginMgr* clouddrivepluginmgr; DLLEXPORT void LoadActions(IServer* pServer) { Server = pServer; WalCheckpointThread::init_mutex(); KvStoreBackendS3::init_mutex(); clouddrivepluginmgr = new ClouddrivePluginMgr; init_compress_encrypt_factory(); Aws::SDKOptions options = {}; Aws::InitAPI(options); Aws::Utils::Logging::InitializeAWSLogging(Aws::MakeShared<ServerLogging>("KvStoreBackend", Aws::Utils::Logging::LogLevel::Warn)); Server->RegisterPluginThreadsafeModel(clouddrivepluginmgr, "clouddriveplugin"); #ifndef STATIC_PLUGIN Server->Log("Loaded -btrfsplugin- plugin", LL_INFO); #endif } DLLEXPORT void UnloadActions(void) { if (Server->getServerParameter("leak_check") == "true") { Aws::SDKOptions options; Aws::ShutdownAPI(options); } } #ifdef STATIC_PLUGIN namespace { static RegisterPluginHelper register_plugin(LoadActions, UnloadActions, 10); } #endif<|endoftext|>
<commit_before>/*************************************************************** * * Copyright (C) 1990-2015, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI. * * Licensed under the Apache License, Version 2.0 (the "License"); you * may not use this file except in compliance with the License. You may * obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************/ #include "condor_common.h" #include "condor_attributes.h" #include "condor_classad.h" #include "condor_config.h" #include "condor_constants.h" #include "condor_uid.h" #include "condor_md.h" #include "directory_util.h" #include "filename_tools.h" #include "stat_wrapper.h" #include <string> #ifndef WIN32 #include <unistd.h> #endif #ifdef HAVE_HTTP_PUBLIC_FILES using namespace std; namespace { // Anonymous namespace to limit scope of names to this file const int HASHNAMELEN = 17; static string MakeHashName(const char* fileName, time_t fileModifiedTime) { unsigned char hashResult[HASHNAMELEN * 3]; // Allocate extra space for safety. // Convert the modified time to a string object std::string modifiedTimeStr = std::to_string((long long int) fileModifiedTime); // Create a new string which will be the source for our hash function. // This will append two strings: // 1. Full path to the file // 2. Modified time of the file unsigned char* hashSource = new unsigned char[strlen(fileName) + strlen(modifiedTimeStr.c_str()) + 1]; strcpy( (char*) hashSource, fileName ); strcat( (char*) hashSource, modifiedTimeStr.c_str() ); // Now calculate the hash memcpy(hashResult, Condor_MD_MAC::computeOnce(hashSource, strlen((const char*) hashSource)), HASHNAMELEN); char entryHashName[HASHNAMELEN * 2]; // 2 chars per hex byte entryHashName[0] = '\0'; char letter[3]; for (int i = 0; i < HASHNAMELEN - 1; ++i) { sprintf(letter, "%x", hashResult[i]); strcat(entryHashName, letter); } return entryHashName; } // WARNING! This code changes priv state. Be very careful if modifying it. // Do not return in the block of code where the priv has been set to either // condor or root. -zmiller static bool MakeLink(const char* srcFile, const string &newLink) { std::string webRootDir; param(webRootDir, "HTTP_PUBLIC_FILES_ROOT_DIR"); if(webRootDir.empty()) { dprintf(D_ALWAYS, "mk_cache_links.cpp: HTTP_PUBLIC_FILES_ROOT_DIR " "not set! Falling back to regular file transfer\n"); return (false); } char goodPath[PATH_MAX]; if (realpath(webRootDir.c_str(), goodPath) == NULL) { dprintf(D_ALWAYS, "mk_cache_links.cpp: HTTP_PUBLIC_FILES_ROOT_DIR " "not a valid path: %s. Falling back to regular file transfer.\n", webRootDir.c_str()); return (false); } StatWrapper fileMode; bool fileOK = false; if (fileMode.Stat(srcFile) == 0) { const StatStructType *statrec = fileMode.GetBuf(); if (statrec != NULL) fileOK = (statrec->st_mode & S_IROTH); // Verify readable by all } if (fileOK == false) { dprintf(D_ALWAYS, "Cannot transfer -- public input file not world readable: %s\n", srcFile); return (false); } // see how we should create the link. There are a few options. // 1) As the condor user. // 2) As root, and then chown to the user. // 3) As root, and then chown to some other user (like "httpd") std::string link_owner; param(link_owner, "HTTP_PUBLIC_FILES_USER"); uid_t link_uid = -1; gid_t link_gid = -1; bool create_as_root = false; priv_state priv = PRIV_UNKNOWN; if (strcasecmp(link_owner.c_str(), "<user>") == 0) { // we'll do everything in user priv except use root // to create and chown the link link_uid = get_user_uid(); link_gid = get_user_gid(); create_as_root = true; priv = set_user_priv(); } else if (strcasecmp(link_owner.c_str(), "<condor>") == 0) { // in this case we do everything as the condor user since they // own the directory priv = set_condor_priv(); } else { // in this case we need to determine what uid they requested // and then do everything as that user. we set root priv and // then temporarily assume the uid and gid of the specified // user. // has to be a username and not just a uid, since otherwise it // isn't clear what gid we should use (if they aren't in the passwd // file, for instance) and we also save on lookups. bool isname = pcache()->get_user_ids(link_owner.c_str(), link_uid, link_gid); if (!isname) { dprintf(D_ALWAYS, "ERROR: unable to look up HTTP_PUBLIC_FILES_USER (%s)" " in /etc/passwd.\n", link_owner.c_str()); // we ARE allowed to return here because we have not // yet switched priv state in this case. return false; } if (link_uid == 0 || link_gid == 0) { dprintf(D_ALWAYS, "ERROR: HTTP_PUBLIC_FILES_USER (%s)" " in /etc/passwd has UID 0. Aborting.\n", link_owner.c_str()); // we ARE allowed to return here because we have not // yet switched priv state in this case. return false; } // now become the specified user for this operation. priv = set_root_priv(); if (setegid(link_gid)) {} if (seteuid(link_uid)) {} } // STARTING HERE, DO NOT RETURN FROM THIS FUNCTION WITHOUT RESETTING // THE ORIGINAL PRIV STATE. // we will now create or update the link const char *const targetLink = dircat(goodPath, newLink.c_str()); // needs to be freed bool retVal = false; if (targetLink != NULL) { // Check if target already exists if (fileMode.Stat(targetLink, StatWrapper::STATOP_LSTAT) == 0) { // Good enough if link exists, ok if update fails retVal = true; // It is assumed that existing link points to srcFile. // // I don't like this assumption. I think we need to // add username or uid to filename to prevent // accidents/mischeif when two users happen to us the // same file. If user A then deletes or modifies the // file, user B is stuck with a link they probably // can't update. To be fixed ASAP. -zmiller const StatStructType *statrec = fileMode.GetBuf(); if (statrec != NULL) { time_t filemtime = statrec->st_mtime; // Must be careful to operate on link, not target file. // // This should be done AS THE OWNER OF THE FILE. if ((time(NULL) - filemtime) > 3600 && lutimes(targetLink, NULL) != 0) { // Update mod time, but only once an hour to avoid excess file access dprintf(D_ALWAYS, "Could not update modification date on %s," "error = %s\n", targetLink, strerror(errno)); } } else { dprintf(D_ALWAYS, "Could not stat file %s\n", targetLink); } } else { // now create the link. we may need to do this as root and chown // it, depending on the create_as_root flag. if that's false, just // stay in the priv state we are in for creation and there's no need // to chown. priv_state link_priv = PRIV_UNKNOWN; if (create_as_root) { link_priv = set_root_priv(); } if (symlink(srcFile, targetLink) == 0) { // so far, so good! retVal = true; } else { dprintf(D_ALWAYS, "Could not link %s to %s, error = %s\n", srcFile, targetLink, strerror(errno)); } if (create_as_root) { // if we succesfully created the link, now chown to the user if (retVal && lchown(targetLink, link_uid, link_gid) != 0) { // chown didn't actually succeed, so this operation is now a failure. retVal = false; // destroy the evidence? unlink(targetLink); dprintf(D_ALWAYS, "Could not change ownership of %s to %i:%i, error = %s\n", targetLink, link_uid, link_gid, strerror(errno)); } // either way, reset priv state set_priv(link_priv); } } delete [] targetLink; } // return to original privilege level, and exit set_priv(priv); return retVal; } static string MakeAbsolutePath(const char* path, const char* initialWorkingDir) { if (is_relative_to_cwd(path)) { string fullPath = initialWorkingDir; fullPath += DIR_DELIM_CHAR; fullPath += path; return (fullPath); } return (path); } } // end namespace void ProcessCachedInpFiles(ClassAd *const Ad, StringList *const InputFiles, StringList &PubInpFiles) { char *initialWorkingDir = NULL; const char *path; MyString remap; struct stat fileStat; time_t fileModifiedTime = time(NULL); if (PubInpFiles.isEmpty() == false) { const char *webServerAddress = param("HTTP_PUBLIC_FILES_ADDRESS"); // If a web server address is not defined, exit quickly. The file // transfer will go on using the regular CEDAR protocol. if(!webServerAddress) { dprintf(D_FULLDEBUG, "mk_cache_links.cpp: HTTP_PUBLIC_FILES_ADDRESS " "not set! Falling back to regular file transfer\n"); return; } // Build out the base URL for public files string url = "http://"; url += webServerAddress; url += "/"; PubInpFiles.rewind(); if (Ad->LookupString(ATTR_JOB_IWD, &initialWorkingDir) != 1) { dprintf(D_FULLDEBUG, "mk_cache_links.cpp: Job ad did not have an " "initialWorkingDir! Falling back to regular file transfer\n"); return; } while ((path = PubInpFiles.next()) != NULL) { // Determine the full path of the file to be transferred string fullPath = MakeAbsolutePath(path, initialWorkingDir); // Determine the time last modified of the file to be transferred if( stat( fullPath.c_str(), &fileStat ) == 0 ) { struct timespec fileTime = fileStat.st_mtim; fileModifiedTime = fileTime.tv_sec; } else { dprintf(D_FULLDEBUG, "mk_cache_links.cpp: Unable to access file " "%s. Falling back to regular file transfer\n", fullPath.c_str()); return; } string hashName = MakeHashName( fullPath.c_str(), fileModifiedTime ); if (MakeLink(fullPath.c_str(), hashName)) { InputFiles->remove(path); // Remove plain file name from InputFiles remap += hashName; remap += "="; remap += basename(path); remap += ";"; hashName = url + hashName; const char *const namePtr = hashName.c_str(); if ( !InputFiles->contains(namePtr) ) { InputFiles->append(namePtr); dprintf(D_FULLDEBUG, "mk_cache_links.cpp: Adding url to " "InputFiles: %s\n", namePtr); } else dprintf(D_FULLDEBUG, "mk_cache_links.cpp: url already " "in InputFiles: %s\n", namePtr); } else { dprintf(D_FULLDEBUG, "mk_cache_links.cpp: Failed to generate " " hash link for %s\n", fullPath.c_str()); } } free( initialWorkingDir ); if ( remap.Length() > 0 ) { MyString remapnew; char *buf = NULL; if (Ad->LookupString(ATTR_TRANSFER_INPUT_REMAPS, &buf) == 1) { remapnew = buf; free(buf); buf = NULL; remapnew += ";"; } remapnew += remap; if (Ad->Assign(ATTR_TRANSFER_INPUT_REMAPS, remap.Value()) == false) { dprintf(D_ALWAYS, "mk_cache_links.cpp: Could not add to jobAd: " "%s\n", remap.c_str()); } } } else dprintf(D_FULLDEBUG, "mk_cache_links.cpp: No public input files.\n"); } #endif <commit_msg>Fixed potential memory leak (#6356)<commit_after>/*************************************************************** * * Copyright (C) 1990-2015, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI. * * Licensed under the Apache License, Version 2.0 (the "License"); you * may not use this file except in compliance with the License. You may * obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************/ #include "condor_common.h" #include "condor_attributes.h" #include "condor_classad.h" #include "condor_config.h" #include "condor_constants.h" #include "condor_uid.h" #include "condor_md.h" #include "directory_util.h" #include "filename_tools.h" #include "stat_wrapper.h" #include <string> #ifndef WIN32 #include <unistd.h> #endif #ifdef HAVE_HTTP_PUBLIC_FILES using namespace std; namespace { // Anonymous namespace to limit scope of names to this file const int HASHNAMELEN = 17; static string MakeHashName(const char* fileName, time_t fileModifiedTime) { unsigned char hashResult[HASHNAMELEN * 3]; // Allocate extra space for safety. // Convert the modified time to a string object std::string modifiedTimeStr = std::to_string((long long int) fileModifiedTime); // Create a new string which will be the source for our hash function. // This will append two strings: // 1. Full path to the file // 2. Modified time of the file unsigned char* hashSource = new unsigned char[strlen(fileName) + strlen(modifiedTimeStr.c_str()) + 1]; strcpy( (char*) hashSource, fileName ); strcat( (char*) hashSource, modifiedTimeStr.c_str() ); // Now calculate the hash memcpy(hashResult, Condor_MD_MAC::computeOnce(hashSource, strlen((const char*) hashSource)), HASHNAMELEN); char entryHashName[HASHNAMELEN * 2]; // 2 chars per hex byte entryHashName[0] = '\0'; char letter[3]; for (int i = 0; i < HASHNAMELEN - 1; ++i) { sprintf(letter, "%x", hashResult[i]); strcat(entryHashName, letter); } return entryHashName; } // WARNING! This code changes priv state. Be very careful if modifying it. // Do not return in the block of code where the priv has been set to either // condor or root. -zmiller static bool MakeLink(const char* srcFile, const string &newLink) { std::string webRootDir; param(webRootDir, "HTTP_PUBLIC_FILES_ROOT_DIR"); if(webRootDir.empty()) { dprintf(D_ALWAYS, "mk_cache_links.cpp: HTTP_PUBLIC_FILES_ROOT_DIR " "not set! Falling back to regular file transfer\n"); return (false); } char goodPath[PATH_MAX]; if (realpath(webRootDir.c_str(), goodPath) == NULL) { dprintf(D_ALWAYS, "mk_cache_links.cpp: HTTP_PUBLIC_FILES_ROOT_DIR " "not a valid path: %s. Falling back to regular file transfer.\n", webRootDir.c_str()); return (false); } StatWrapper fileMode; bool fileOK = false; if (fileMode.Stat(srcFile) == 0) { const StatStructType *statrec = fileMode.GetBuf(); if (statrec != NULL) fileOK = (statrec->st_mode & S_IROTH); // Verify readable by all } if (fileOK == false) { dprintf(D_ALWAYS, "Cannot transfer -- public input file not world readable: %s\n", srcFile); return (false); } // see how we should create the link. There are a few options. // 1) As the condor user. // 2) As root, and then chown to the user. // 3) As root, and then chown to some other user (like "httpd") std::string link_owner; param(link_owner, "HTTP_PUBLIC_FILES_USER"); uid_t link_uid = -1; gid_t link_gid = -1; bool create_as_root = false; priv_state priv = PRIV_UNKNOWN; if (strcasecmp(link_owner.c_str(), "<user>") == 0) { // we'll do everything in user priv except use root // to create and chown the link link_uid = get_user_uid(); link_gid = get_user_gid(); create_as_root = true; priv = set_user_priv(); } else if (strcasecmp(link_owner.c_str(), "<condor>") == 0) { // in this case we do everything as the condor user since they // own the directory priv = set_condor_priv(); } else { // in this case we need to determine what uid they requested // and then do everything as that user. we set root priv and // then temporarily assume the uid and gid of the specified // user. // has to be a username and not just a uid, since otherwise it // isn't clear what gid we should use (if they aren't in the passwd // file, for instance) and we also save on lookups. bool isname = pcache()->get_user_ids(link_owner.c_str(), link_uid, link_gid); if (!isname) { dprintf(D_ALWAYS, "ERROR: unable to look up HTTP_PUBLIC_FILES_USER (%s)" " in /etc/passwd.\n", link_owner.c_str()); // we ARE allowed to return here because we have not // yet switched priv state in this case. return false; } if (link_uid == 0 || link_gid == 0) { dprintf(D_ALWAYS, "ERROR: HTTP_PUBLIC_FILES_USER (%s)" " in /etc/passwd has UID 0. Aborting.\n", link_owner.c_str()); // we ARE allowed to return here because we have not // yet switched priv state in this case. return false; } // now become the specified user for this operation. priv = set_root_priv(); if (setegid(link_gid)) {} if (seteuid(link_uid)) {} } // STARTING HERE, DO NOT RETURN FROM THIS FUNCTION WITHOUT RESETTING // THE ORIGINAL PRIV STATE. // we will now create or update the link const char *const targetLink = dircat(goodPath, newLink.c_str()); // needs to be freed bool retVal = false; if (targetLink != NULL) { // Check if target already exists if (fileMode.Stat(targetLink, StatWrapper::STATOP_LSTAT) == 0) { // Good enough if link exists, ok if update fails retVal = true; // It is assumed that existing link points to srcFile. // // I don't like this assumption. I think we need to // add username or uid to filename to prevent // accidents/mischeif when two users happen to us the // same file. If user A then deletes or modifies the // file, user B is stuck with a link they probably // can't update. To be fixed ASAP. -zmiller const StatStructType *statrec = fileMode.GetBuf(); if (statrec != NULL) { time_t filemtime = statrec->st_mtime; // Must be careful to operate on link, not target file. // // This should be done AS THE OWNER OF THE FILE. if ((time(NULL) - filemtime) > 3600 && lutimes(targetLink, NULL) != 0) { // Update mod time, but only once an hour to avoid excess file access dprintf(D_ALWAYS, "Could not update modification date on %s," "error = %s\n", targetLink, strerror(errno)); } } else { dprintf(D_ALWAYS, "Could not stat file %s\n", targetLink); } } else { // now create the link. we may need to do this as root and chown // it, depending on the create_as_root flag. if that's false, just // stay in the priv state we are in for creation and there's no need // to chown. priv_state link_priv = PRIV_UNKNOWN; if (create_as_root) { link_priv = set_root_priv(); } if (symlink(srcFile, targetLink) == 0) { // so far, so good! retVal = true; } else { dprintf(D_ALWAYS, "Could not link %s to %s, error = %s\n", srcFile, targetLink, strerror(errno)); } if (create_as_root) { // if we succesfully created the link, now chown to the user if (retVal && lchown(targetLink, link_uid, link_gid) != 0) { // chown didn't actually succeed, so this operation is now a failure. retVal = false; // destroy the evidence? unlink(targetLink); dprintf(D_ALWAYS, "Could not change ownership of %s to %i:%i, error = %s\n", targetLink, link_uid, link_gid, strerror(errno)); } // either way, reset priv state set_priv(link_priv); } } delete [] targetLink; } // return to original privilege level, and exit set_priv(priv); return retVal; } static string MakeAbsolutePath(const char* path, const char* initialWorkingDir) { if (is_relative_to_cwd(path)) { string fullPath = initialWorkingDir; fullPath += DIR_DELIM_CHAR; fullPath += path; return (fullPath); } return (path); } } // end namespace void ProcessCachedInpFiles(ClassAd *const Ad, StringList *const InputFiles, StringList &PubInpFiles) { char *initialWorkingDir = NULL; const char *path; MyString remap; struct stat fileStat; time_t fileModifiedTime = time(NULL); if (PubInpFiles.isEmpty() == false) { const char *webServerAddress = param("HTTP_PUBLIC_FILES_ADDRESS"); // If a web server address is not defined, exit quickly. The file // transfer will go on using the regular CEDAR protocol. if(!webServerAddress) { dprintf(D_FULLDEBUG, "mk_cache_links.cpp: HTTP_PUBLIC_FILES_ADDRESS " "not set! Falling back to regular file transfer\n"); return; } // Build out the base URL for public files string url = "http://"; url += webServerAddress; url += "/"; PubInpFiles.rewind(); if (Ad->LookupString(ATTR_JOB_IWD, &initialWorkingDir) != 1) { dprintf(D_FULLDEBUG, "mk_cache_links.cpp: Job ad did not have an " "initialWorkingDir! Falling back to regular file transfer\n"); return; } while ((path = PubInpFiles.next()) != NULL) { // Determine the full path of the file to be transferred string fullPath = MakeAbsolutePath(path, initialWorkingDir); // Determine the time last modified of the file to be transferred if( stat( fullPath.c_str(), &fileStat ) == 0 ) { struct timespec fileTime = fileStat.st_mtim; fileModifiedTime = fileTime.tv_sec; } else { dprintf(D_FULLDEBUG, "mk_cache_links.cpp: Unable to access file " "%s. Falling back to regular file transfer\n", fullPath.c_str()); free( initialWorkingDir ); return; } string hashName = MakeHashName( fullPath.c_str(), fileModifiedTime ); if (MakeLink(fullPath.c_str(), hashName)) { InputFiles->remove(path); // Remove plain file name from InputFiles remap += hashName; remap += "="; remap += basename(path); remap += ";"; hashName = url + hashName; const char *const namePtr = hashName.c_str(); if ( !InputFiles->contains(namePtr) ) { InputFiles->append(namePtr); dprintf(D_FULLDEBUG, "mk_cache_links.cpp: Adding url to " "InputFiles: %s\n", namePtr); } else dprintf(D_FULLDEBUG, "mk_cache_links.cpp: url already " "in InputFiles: %s\n", namePtr); } else { dprintf(D_FULLDEBUG, "mk_cache_links.cpp: Failed to generate " " hash link for %s\n", fullPath.c_str()); } } free( initialWorkingDir ); if ( remap.Length() > 0 ) { MyString remapnew; char *buf = NULL; if (Ad->LookupString(ATTR_TRANSFER_INPUT_REMAPS, &buf) == 1) { remapnew = buf; free(buf); buf = NULL; remapnew += ";"; } remapnew += remap; if (Ad->Assign(ATTR_TRANSFER_INPUT_REMAPS, remap.Value()) == false) { dprintf(D_ALWAYS, "mk_cache_links.cpp: Could not add to jobAd: " "%s\n", remap.c_str()); } } } else dprintf(D_FULLDEBUG, "mk_cache_links.cpp: No public input files.\n"); } #endif <|endoftext|>
<commit_before>#include "ConstantBitP_TransferFunctions.h" #include "ConstantBitP_Utility.h" namespace simplifier { namespace constantBitP { namespace BEEV { typedef unsigned int * CBV; } // Misc (easy) transfer functions. // Trevor Hansen. BSD License. // if the result is fixed to true. Then fix a==b. // if the result is fixed to false, there is a single unspecied value, and all the rest are the same. Fix it to the opposite. // if a==b then fix the result to true. // if a!=b then fix the result to false. Result bvEqualsBothWays(FixedBits& a, FixedBits& b, FixedBits& output) { assert(a.getWidth() == b.getWidth()); assert(1 == output.getWidth()); const int childWidth = a.getWidth(); Result r = NO_CHANGE; bool allSame = true; bool definatelyFalse = false; for (int i = 0; i < childWidth; i++) { // if both fixed if (a.isFixed(i) && b.isFixed(i)) { // And have different values. if (a.getValue(i) != b.getValue(i)) { definatelyFalse = true; } else { allSame &= true; continue; } } allSame &= false; } if (definatelyFalse) { if (output.isFixed(0) && output.getValue(0)) { return CONFLICT; } else if (!output.isFixed(0)) { output.setFixed(0, true); output.setValue(0, false); r = CHANGED; } } else if (allSame) { if (output.isFixed(0) && !output.getValue(0)) { return CONFLICT; } else if (!output.isFixed(0)) { output.setFixed(0, true); output.setValue(0, true); r = CHANGED; } } if (output.isFixed(0) && output.getValue(0)) // all should be the same. { for (int i = 0; i < childWidth; i++) { if (a.isFixed(i) && b.isFixed(i)) { if (a.getValue(i) != b.getValue(i)) { return CONFLICT; } } else if (a.isFixed(i) != b.isFixed(i)) // both same but only one is fixed. { if (a.isFixed(i)) { b.setFixed(i, true); b.setValue(i, a.getValue(i)); r = CHANGED; } else { a.setFixed(i, true); a.setValue(i, b.getValue(i)); r = CHANGED; } } } } // if the result is fixed to false, there is a single unspecied value, and all the rest are the same. Fix it to the opposite. if (output.isFixed(0) && !output.getValue(0)) { int unknown = 0; for (int i = 0; i < childWidth; i++) { if (!a.isFixed(i)) unknown++; if (!b.isFixed(i)) unknown++; else if (a.isFixed(i) && b.isFixed(i) && a.getValue(i) != b.getValue(i)) { unknown = 10; // hack, don't do the next loop. break; } } if (1 == unknown) { for (int i = 0; i < childWidth; i++) { if (!a.isFixed(i)) { a.setFixed(i, true); a.setValue(i, !b.getValue(i)); r = CHANGED; } if (!b.isFixed(i)) { b.setFixed(i, true); b.setValue(i, !a.getValue(i)); r = CHANGED; } } } } return r; } Result bvEqualsBothWays(vector<FixedBits*>& children, FixedBits& result) { return bvEqualsBothWays(*(children[0]), *(children[1]), result); } Result bvZeroExtendBothWays(vector<FixedBits*>& children, FixedBits& output) { assert(children.size() ==2 ); // The second argument is a junk size arugment. FixedBits& input = *children[0]; const int inputBitWidth = input.getWidth(); const int outputBitWidth = output.getWidth(); Result result = makeEqual(input, output, 0, inputBitWidth); if (CONFLICT == result) return CONFLICT; // Fix all the topmost bits of the output to zero. for (int i = inputBitWidth; i < outputBitWidth; i++) { if (output.isFixed(i) && output.getValue(i)) return CONFLICT; // set to one. Never right. else if (!output.isFixed(i)) { output.setFixed(i, true); output.setValue(i, false); result = CHANGED; } } return result; } Result bvSignExtendBothWays(vector<FixedBits*>& children, FixedBits& output) { assert(children.size() ==2 ); // The second argument is a junk size arugment. FixedBits& input = *children[0]; const int inputBitWidth = input.getWidth(); const int outputBitWidth = output.getWidth(); assert(inputBitWidth <= outputBitWidth); Result result = makeEqual(input, output, 0, inputBitWidth); if (CONFLICT == result) return CONFLICT; // If any of the topmost bits of the output are fixed. Then they all should be. // They should all be fixed to the same value. bool found = false; bool setTo; for (int i = inputBitWidth - /**/1 /**/; i < outputBitWidth; i++) { if (output.isFixed(i)) { setTo = output.getValue(i); found = true; break; } } if (found) { for (int i = inputBitWidth - 1; i < outputBitWidth; i++) { if (output.isFixed(i) && (output.getValue(i) != setTo)) return CONFLICT; // if any are set to the wrong value! bad. else if (!output.isFixed(i)) { output.setFixed(i, true); output.setValue(i, setTo); result = CHANGED; } } Result result2 = makeEqual(input, output, 0, inputBitWidth); if (CONFLICT == result2) return CONFLICT; } return result; } Result bvExtractBothWays(vector<FixedBits*>& children, FixedBits& output) { const int numberOfChildren = children.size(); const int outputBitWidth = output.getWidth(); Result result = NO_CHANGE; assert(3 == numberOfChildren); int top = children[1]->getUnsignedValue(); int bottom = children[2]->getUnsignedValue(); FixedBits& input = *(children[0]); assert(top >= bottom); assert(bottom >=0); assert(top - bottom + 1 == outputBitWidth); assert(top < input.getWidth()); for (int outputPosition = 0; outputPosition < outputBitWidth; outputPosition++) { int inputPosition = outputPosition + bottom; if (input.isFixed(inputPosition) && output.isFixed(outputPosition)) if (input.getValue(inputPosition) ^ output.getValue(outputPosition)) return CONFLICT; if (input.isFixed(inputPosition) ^ output.isFixed(outputPosition)) { if (input.isFixed(inputPosition)) { output.setFixed(outputPosition, true); output.setValue(outputPosition, input.getValue(inputPosition)); result = CHANGED; } else { input.setFixed(inputPosition, true); input.setValue(inputPosition, output.getValue(outputPosition)); result = CHANGED; } } } //cerr << "extract[" << top << ":" << bottom << "]" << input << "=" << output<< endl; return result; } // UMINUS, is NEG followed by +1 Result bvUnaryMinusBothWays(vector<FixedBits*>& children, FixedBits& output) { assert(children.size() == 1); const int bitWidth = children[0]->getWidth(); // If it's only one bit. This will be negative one. FixedBits one(bitWidth, false); one.fixToZero(); one.setFixed(0, true); one.setValue(0, true); FixedBits notted(bitWidth, false); vector<FixedBits*> args; args.push_back(&notted); args.push_back(&one); Result result = NO_CHANGE; while (true) // until it fixed points { FixedBits initialNot(notted); FixedBits initialIn(*children[0]); FixedBits initialOut(output); result = bvNotBothWays(*children[0], notted); if (CONFLICT == result) return CONFLICT; result = bvAddBothWays(args, output); if (CONFLICT == result) return CONFLICT; if (FixedBits::equals(initialNot, notted) && FixedBits::equals(initialIn, *children[0]) && FixedBits::equals(initialOut, output)) break; } return NOT_IMPLEMENTED; // don't set the status properly yet.. } Result bvConcatBothWays(vector<FixedBits*>& children, FixedBits& output) { Result r = NO_CHANGE; const int numberOfChildren = children.size(); int current = 0; for (int i = numberOfChildren - 1; i >= 0; i--) // least significant is last. { FixedBits& child = *children[i]; for (int j = 0; j < child.getWidth(); j++) { // values are different. Bad. if (output.isFixed(current) && child.isFixed(j) && (output.getValue(current) != child.getValue(j))) return CONFLICT; if (output.isFixed(current) && !child.isFixed(j)) { // only output is fixed. child.setFixed(j, true); child.setValue(j, output.getValue(current)); r = CHANGED; } else if (!output.isFixed(current) && child.isFixed(j)) { // only input is fixed. output.setFixed(current, true); output.setValue(current, child.getValue(j)); r = CHANGED; } current++; } } return r; } // If the guard is fixed, make equal the appropriate input and output. // If one input can not possibly be the output. Then set the guard to make it the other one. // If both values are the same. Set the output to that value. Result bvITEBothWays(vector<FixedBits*>& children, FixedBits& output) { Result result = NO_CHANGE; assert(3 == children.size()); const int bitWidth = output.getWidth(); FixedBits& guard = *children[0]; FixedBits& c1 = *children[1]; FixedBits& c2 = *children[2]; assert(c1.getWidth() == c2.getWidth()); assert(output.getWidth() == c2.getWidth()); if (guard.isFixed(0) && guard.getValue(0)) { // guard fixed to true. So make (first arg == output) result = makeEqual(output, c1, 0, bitWidth); if (CONFLICT == result) return CONFLICT; } else if (guard.isFixed(0) && !guard.getValue(0)) { result = makeEqual(output, c2, 0, bitWidth); if (CONFLICT == result) return CONFLICT; } else { for (int i = 0; i < bitWidth; i++) { if (c1.isFixed(i) && c2.isFixed(i) && (c1.getValue(i) == c2.getValue(i))) { if (output.isFixed(i) && (output.getValue(i) != c1.getValue(i))) return CONFLICT; if (!output.isFixed(i)) { output.setFixed(i, true); output.setValue(i, c1.getValue(i)); result = CHANGED; } } } } bool changed = false; if (CHANGED == result) changed = true; for (int i = 0; i < bitWidth; i++) { if (output.isFixed(i)) { if (c1.isFixed(i) && (c1.getValue(i) != output.getValue(i))) { //c1 is fixed to a value that's not the same as the output. if (!guard.isFixed(0)) { guard.setFixed(0, true); guard.setValue(0, false); result = bvITEBothWays(children, output); if (CONFLICT == result) return CONFLICT; changed = true; } else if (guard.getValue(0)) return CONFLICT; } if (c2.isFixed(i) && (c2.getValue(i) != output.getValue(i))) { //c2 is fixed to a value that's not the same as the output. if (!guard.isFixed(0)) { guard.setFixed(0, true); guard.setValue(0, true); result = bvITEBothWays(children, output); if (CONFLICT == result) return CONFLICT; changed = true; } else if (!guard.getValue(0)) return CONFLICT; } } } if (result == CONFLICT) return CONFLICT; if (changed) return CHANGED; return result; } } } <commit_msg>Slightly speed up the equals propagator.<commit_after>#include "ConstantBitP_TransferFunctions.h" #include "ConstantBitP_Utility.h" namespace simplifier { namespace constantBitP { namespace BEEV { typedef unsigned int * CBV; } // Misc (easy) transfer functions. // Trevor Hansen. BSD License. // if the result is fixed to true. Then fix a==b. // if the result is fixed to false, there is a single unspecied value, and all the rest are the same. Fix it to the opposite. // if a==b then fix the result to true. // if a!=b then fix the result to false. Result bvEqualsBothWays(FixedBits& a, FixedBits& b, FixedBits& output) { assert(a.getWidth() == b.getWidth()); assert(1 == output.getWidth()); const int childWidth = a.getWidth(); Result r = NO_CHANGE; bool allSame = true; bool definatelyFalse = false; for (int i = 0; i < childWidth; i++) { // if both fixed if (a.isFixed(i) && b.isFixed(i)) { // And have different values. if (a.getValue(i) != b.getValue(i)) { definatelyFalse = true; break; } else { allSame &= true; continue; } } allSame &= false; } if (definatelyFalse) { if (output.isFixed(0) && output.getValue(0)) { return CONFLICT; } else if (!output.isFixed(0)) { output.setFixed(0, true); output.setValue(0, false); r = CHANGED; } } else if (allSame) { if (output.isFixed(0) && !output.getValue(0)) { return CONFLICT; } else if (!output.isFixed(0)) { output.setFixed(0, true); output.setValue(0, true); r = CHANGED; } } if (output.isFixed(0) && output.getValue(0)) // all should be the same. { for (int i = 0; i < childWidth; i++) { if (a.isFixed(i) && b.isFixed(i)) { if (a.getValue(i) != b.getValue(i)) { return CONFLICT; } } else if (a.isFixed(i) != b.isFixed(i)) // both same but only one is fixed. { if (a.isFixed(i)) { b.setFixed(i, true); b.setValue(i, a.getValue(i)); r = CHANGED; } else { a.setFixed(i, true); a.setValue(i, b.getValue(i)); r = CHANGED; } } } } // if the result is fixed to false, there is a single unspecied value, and all the rest are the same. Fix it to the opposite. if (output.isFixed(0) && !output.getValue(0)) { int unknown = 0; for (int i = 0; i < childWidth && unknown < 2; i++) { if (!a.isFixed(i)) unknown++; if (!b.isFixed(i)) unknown++; else if (a.isFixed(i) && b.isFixed(i) && a.getValue(i) != b.getValue(i)) { unknown = 10; // hack, don't do the next loop. break; } } if (1 == unknown) { for (int i = 0; i < childWidth; i++) { if (!a.isFixed(i)) { a.setFixed(i, true); a.setValue(i, !b.getValue(i)); r = CHANGED; } if (!b.isFixed(i)) { b.setFixed(i, true); b.setValue(i, !a.getValue(i)); r = CHANGED; } } } } return r; } Result bvEqualsBothWays(vector<FixedBits*>& children, FixedBits& result) { return bvEqualsBothWays(*(children[0]), *(children[1]), result); } Result bvZeroExtendBothWays(vector<FixedBits*>& children, FixedBits& output) { assert(children.size() ==2 ); // The second argument is a junk size arugment. FixedBits& input = *children[0]; const int inputBitWidth = input.getWidth(); const int outputBitWidth = output.getWidth(); Result result = makeEqual(input, output, 0, inputBitWidth); if (CONFLICT == result) return CONFLICT; // Fix all the topmost bits of the output to zero. for (int i = inputBitWidth; i < outputBitWidth; i++) { if (output.isFixed(i) && output.getValue(i)) return CONFLICT; // set to one. Never right. else if (!output.isFixed(i)) { output.setFixed(i, true); output.setValue(i, false); result = CHANGED; } } return result; } Result bvSignExtendBothWays(vector<FixedBits*>& children, FixedBits& output) { assert(children.size() ==2 ); // The second argument is a junk size arugment. FixedBits& input = *children[0]; const int inputBitWidth = input.getWidth(); const int outputBitWidth = output.getWidth(); assert(inputBitWidth <= outputBitWidth); Result result = makeEqual(input, output, 0, inputBitWidth); if (CONFLICT == result) return CONFLICT; // If any of the topmost bits of the output are fixed. Then they all should be. // They should all be fixed to the same value. bool found = false; bool setTo; for (int i = inputBitWidth - /**/1 /**/; i < outputBitWidth; i++) { if (output.isFixed(i)) { setTo = output.getValue(i); found = true; break; } } if (found) { for (int i = inputBitWidth - 1; i < outputBitWidth; i++) { if (output.isFixed(i) && (output.getValue(i) != setTo)) return CONFLICT; // if any are set to the wrong value! bad. else if (!output.isFixed(i)) { output.setFixed(i, true); output.setValue(i, setTo); result = CHANGED; } } Result result2 = makeEqual(input, output, 0, inputBitWidth); if (CONFLICT == result2) return CONFLICT; } return result; } Result bvExtractBothWays(vector<FixedBits*>& children, FixedBits& output) { const int numberOfChildren = children.size(); const int outputBitWidth = output.getWidth(); Result result = NO_CHANGE; assert(3 == numberOfChildren); int top = children[1]->getUnsignedValue(); int bottom = children[2]->getUnsignedValue(); FixedBits& input = *(children[0]); assert(top >= bottom); assert(bottom >=0); assert(top - bottom + 1 == outputBitWidth); assert(top < input.getWidth()); for (int outputPosition = 0; outputPosition < outputBitWidth; outputPosition++) { int inputPosition = outputPosition + bottom; if (input.isFixed(inputPosition) && output.isFixed(outputPosition)) if (input.getValue(inputPosition) ^ output.getValue(outputPosition)) return CONFLICT; if (input.isFixed(inputPosition) ^ output.isFixed(outputPosition)) { if (input.isFixed(inputPosition)) { output.setFixed(outputPosition, true); output.setValue(outputPosition, input.getValue(inputPosition)); result = CHANGED; } else { input.setFixed(inputPosition, true); input.setValue(inputPosition, output.getValue(outputPosition)); result = CHANGED; } } } //cerr << "extract[" << top << ":" << bottom << "]" << input << "=" << output<< endl; return result; } // UMINUS, is NEG followed by +1 Result bvUnaryMinusBothWays(vector<FixedBits*>& children, FixedBits& output) { assert(children.size() == 1); const int bitWidth = children[0]->getWidth(); // If it's only one bit. This will be negative one. FixedBits one(bitWidth, false); one.fixToZero(); one.setFixed(0, true); one.setValue(0, true); FixedBits notted(bitWidth, false); vector<FixedBits*> args; args.push_back(&notted); args.push_back(&one); Result result = NO_CHANGE; while (true) // until it fixed points { FixedBits initialNot(notted); FixedBits initialIn(*children[0]); FixedBits initialOut(output); result = bvNotBothWays(*children[0], notted); if (CONFLICT == result) return CONFLICT; result = bvAddBothWays(args, output); if (CONFLICT == result) return CONFLICT; if (FixedBits::equals(initialNot, notted) && FixedBits::equals(initialIn, *children[0]) && FixedBits::equals(initialOut, output)) break; } return NOT_IMPLEMENTED; // don't set the status properly yet.. } Result bvConcatBothWays(vector<FixedBits*>& children, FixedBits& output) { Result r = NO_CHANGE; const int numberOfChildren = children.size(); int current = 0; for (int i = numberOfChildren - 1; i >= 0; i--) // least significant is last. { FixedBits& child = *children[i]; for (int j = 0; j < child.getWidth(); j++) { // values are different. Bad. if (output.isFixed(current) && child.isFixed(j) && (output.getValue(current) != child.getValue(j))) return CONFLICT; if (output.isFixed(current) && !child.isFixed(j)) { // only output is fixed. child.setFixed(j, true); child.setValue(j, output.getValue(current)); r = CHANGED; } else if (!output.isFixed(current) && child.isFixed(j)) { // only input is fixed. output.setFixed(current, true); output.setValue(current, child.getValue(j)); r = CHANGED; } current++; } } return r; } // If the guard is fixed, make equal the appropriate input and output. // If one input can not possibly be the output. Then set the guard to make it the other one. // If both values are the same. Set the output to that value. Result bvITEBothWays(vector<FixedBits*>& children, FixedBits& output) { Result result = NO_CHANGE; assert(3 == children.size()); const int bitWidth = output.getWidth(); FixedBits& guard = *children[0]; FixedBits& c1 = *children[1]; FixedBits& c2 = *children[2]; assert(c1.getWidth() == c2.getWidth()); assert(output.getWidth() == c2.getWidth()); if (guard.isFixed(0) && guard.getValue(0)) { // guard fixed to true. So make (first arg == output) result = makeEqual(output, c1, 0, bitWidth); if (CONFLICT == result) return CONFLICT; } else if (guard.isFixed(0) && !guard.getValue(0)) { result = makeEqual(output, c2, 0, bitWidth); if (CONFLICT == result) return CONFLICT; } else { for (int i = 0; i < bitWidth; i++) { if (c1.isFixed(i) && c2.isFixed(i) && (c1.getValue(i) == c2.getValue(i))) { if (output.isFixed(i) && (output.getValue(i) != c1.getValue(i))) return CONFLICT; if (!output.isFixed(i)) { output.setFixed(i, true); output.setValue(i, c1.getValue(i)); result = CHANGED; } } } } bool changed = false; if (CHANGED == result) changed = true; for (int i = 0; i < bitWidth; i++) { if (output.isFixed(i)) { if (c1.isFixed(i) && (c1.getValue(i) != output.getValue(i))) { //c1 is fixed to a value that's not the same as the output. if (!guard.isFixed(0)) { guard.setFixed(0, true); guard.setValue(0, false); result = bvITEBothWays(children, output); if (CONFLICT == result) return CONFLICT; changed = true; } else if (guard.getValue(0)) return CONFLICT; } if (c2.isFixed(i) && (c2.getValue(i) != output.getValue(i))) { //c2 is fixed to a value that's not the same as the output. if (!guard.isFixed(0)) { guard.setFixed(0, true); guard.setValue(0, true); result = bvITEBothWays(children, output); if (CONFLICT == result) return CONFLICT; changed = true; } else if (!guard.getValue(0)) return CONFLICT; } } } if (result == CONFLICT) return CONFLICT; if (changed) return CHANGED; return result; } } } <|endoftext|>
<commit_before>#ifndef FROMEVENT_HPP #define FROMEVENT_HPP #include "FlagStatus.hpp" #include "IOLogWrapper.hpp" #include "List.hpp" #include "Params.hpp" #include "Vector.hpp" #include "bridge.h" namespace org_pqrs_Karabiner { class FromEvent; class PressingFromEvents final { friend class FromEvent; public: class Item final : public List::Item { public: Item(const FromEvent* p) : fromEvent_(p) {} ~Item(void) {} const FromEvent* getFromEvent(void) const { return fromEvent_; } private: const FromEvent* fromEvent_; }; static Item* find(const FromEvent* p) { for (Item* q = static_cast<Item*>(list_.safe_front()); q; q = static_cast<Item*>(q->getnext())) { if (q->getFromEvent() == p) { return q; } } return nullptr; } static void clear(void) { list_.clear(); } static void push_back(const FromEvent* p) { list_.push_back(new Item(p)); } static bool erase(const FromEvent* p) { Item* q = find(p); if (q) { list_.erase_and_delete(q); return true; } return false; } static void erase_all(const FromEvent* p) { for (;;) { if (!erase(p)) { break; } } } private: static List list_; }; class FromEvent final { public: class Type final { public: enum Value { NONE, KEY, CONSUMER_KEY, // Mute, VolumeIncrement, VolumeDecrement, etcetc. POINTING_BUTTON, }; }; FromEvent(void) : type_(Type::NONE) {} explicit FromEvent(KeyCode v) : type_(Type::KEY), key_(v) {} explicit FromEvent(ConsumerKeyCode v) : type_(Type::CONSUMER_KEY), consumer_(v) {} explicit FromEvent(PointingButton v) : type_(Type::POINTING_BUTTON), button_(v) {} explicit FromEvent(const Params_Base& paramsBase) { type_ = Type::NONE; { auto p = paramsBase.get_Params_KeyboardEventCallBack(); if (p) { type_ = Type::KEY; key_ = p->key; return; } } { auto p = paramsBase.get_Params_KeyboardSpecialEventCallback(); if (p) { type_ = Type::CONSUMER_KEY; consumer_ = p->key; return; } } { auto p = paramsBase.get_Params_RelativePointerEventCallback(); if (p) { type_ = Type::POINTING_BUTTON; button_ = p->ex_button; return; } } } FromEvent(AddDataType datatype, AddValue v) { switch (datatype) { case BRIDGE_DATATYPE_KEYCODE: type_ = Type::KEY; key_ = KeyCode(v); break; case BRIDGE_DATATYPE_CONSUMERKEYCODE: type_ = Type::CONSUMER_KEY; consumer_ = ConsumerKeyCode(v); break; case BRIDGE_DATATYPE_POINTINGBUTTON: type_ = Type::POINTING_BUTTON; button_ = PointingButton(v); break; default: IOLOG_ERROR("Unknown datatype: %u\n", static_cast<unsigned int>(datatype)); type_ = Type::NONE; break; } } ~FromEvent(void) { PressingFromEvents::erase_all(this); } Type::Value getType(void) const { return type_; } // Return whether pressing state is changed. bool changePressingState(const Params_Base& paramsBase, const FlagStatus& currentFlags, const Vector_ModifierFlag& fromFlags); bool isPressing(void) const { return PressingFromEvents::find(this); } // Primitive functions: // These functions do not treat Flags. // Use changePressingState in general. bool isTargetEvent(const Params_Base& paramsBase) const; bool isTargetDownEvent(const Params_Base& paramsBase) const; bool isTargetUpEvent(const Params_Base& paramsBase) const; // Get ModifierFlag from KeyCode. ModifierFlag getModifierFlag(void) const { if (type_ != Type::KEY) return ModifierFlag::ZERO; return key_.getModifierFlag(); } PointingButton getPointingButton(void) const { if (type_ != Type::POINTING_BUTTON) return PointingButton::NONE; return button_; } private: bool isTargetEvent(bool& isDown, const Params_Base& paramsBase) const; // Do not store Flags in FromEvent because SimultaneousKeyPresses uses multiple FromEvents. Type::Value type_; KeyCode key_; ConsumerKeyCode consumer_; PointingButton button_; }; DECLARE_VECTOR(FromEvent); } #endif <commit_msg>add comment<commit_after>#ifndef FROMEVENT_HPP #define FROMEVENT_HPP #include "FlagStatus.hpp" #include "IOLogWrapper.hpp" #include "List.hpp" #include "Params.hpp" #include "Vector.hpp" #include "bridge.h" namespace org_pqrs_Karabiner { class FromEvent; class PressingFromEvents final { friend class FromEvent; public: class Item final : public List::Item { public: Item(const FromEvent* p) : fromEvent_(p) {} ~Item(void) {} const FromEvent* getFromEvent(void) const { return fromEvent_; } private: const FromEvent* fromEvent_; }; static Item* find(const FromEvent* p) { for (Item* q = static_cast<Item*>(list_.safe_front()); q; q = static_cast<Item*>(q->getnext())) { if (q->getFromEvent() == p) { return q; } } return nullptr; } static void clear(void) { list_.clear(); } static void push_back(const FromEvent* p) { list_.push_back(new Item(p)); } static bool erase(const FromEvent* p) { Item* q = find(p); if (q) { list_.erase_and_delete(q); return true; } return false; } static void erase_all(const FromEvent* p) { for (;;) { if (!erase(p)) { break; } } } private: static List list_; }; class FromEvent final { public: class Type final { public: enum Value { NONE, KEY, CONSUMER_KEY, // Mute, VolumeIncrement, VolumeDecrement, etcetc. POINTING_BUTTON, }; }; FromEvent(void) : type_(Type::NONE) {} explicit FromEvent(KeyCode v) : type_(Type::KEY), key_(v) {} explicit FromEvent(ConsumerKeyCode v) : type_(Type::CONSUMER_KEY), consumer_(v) {} explicit FromEvent(PointingButton v) : type_(Type::POINTING_BUTTON), button_(v) {} explicit FromEvent(const Params_Base& paramsBase) { type_ = Type::NONE; { auto p = paramsBase.get_Params_KeyboardEventCallBack(); if (p) { type_ = Type::KEY; key_ = p->key; return; } } { auto p = paramsBase.get_Params_KeyboardSpecialEventCallback(); if (p) { type_ = Type::CONSUMER_KEY; consumer_ = p->key; return; } } { auto p = paramsBase.get_Params_RelativePointerEventCallback(); if (p) { type_ = Type::POINTING_BUTTON; button_ = p->ex_button; return; } } } FromEvent(AddDataType datatype, AddValue v) { switch (datatype) { case BRIDGE_DATATYPE_KEYCODE: type_ = Type::KEY; key_ = KeyCode(v); break; case BRIDGE_DATATYPE_CONSUMERKEYCODE: type_ = Type::CONSUMER_KEY; consumer_ = ConsumerKeyCode(v); break; case BRIDGE_DATATYPE_POINTINGBUTTON: type_ = Type::POINTING_BUTTON; button_ = PointingButton(v); break; default: IOLOG_ERROR("Unknown datatype: %u\n", static_cast<unsigned int>(datatype)); type_ = Type::NONE; break; } } ~FromEvent(void) { PressingFromEvents::erase_all(this); } Type::Value getType(void) const { return type_; } // Return whether pressing state is changed. bool changePressingState(const Params_Base& paramsBase, const FlagStatus& currentFlags, const Vector_ModifierFlag& fromFlags); // Caution: // `isPressing` may return true at key up event if you connected multiple keyboards and pressing the same key. // // For example, // 1. Press the return key in keyboard1. (isPressing == true) // 2. Press the return key in keyboard2. (isPressing == true) // 3. Release the return key in keyboard1. (isPressing == true) // 4. Release the return key in keyboard2. (isPressing == false) // // So you must not use `isPressing` to detect the input event is key down or key up. // (You should use `Params_Base::iskeydown` to determine key down or key up.) bool isPressing(void) const { return PressingFromEvents::find(this); } // Primitive functions: // These functions do not treat Flags. // Use changePressingState in general. bool isTargetEvent(const Params_Base& paramsBase) const; bool isTargetDownEvent(const Params_Base& paramsBase) const; bool isTargetUpEvent(const Params_Base& paramsBase) const; // Get ModifierFlag from KeyCode. ModifierFlag getModifierFlag(void) const { if (type_ != Type::KEY) return ModifierFlag::ZERO; return key_.getModifierFlag(); } PointingButton getPointingButton(void) const { if (type_ != Type::POINTING_BUTTON) return PointingButton::NONE; return button_; } private: bool isTargetEvent(bool& isDown, const Params_Base& paramsBase) const; // Do not store Flags in FromEvent because SimultaneousKeyPresses uses multiple FromEvents. Type::Value type_; KeyCode key_; ConsumerKeyCode consumer_; PointingButton button_; }; DECLARE_VECTOR(FromEvent); } #endif <|endoftext|>
<commit_before> // $Id: Cache.cpp 3456 2013-06-14 02:11:13Z jiaying $ /* * The Software is made available solely for use according to the License Agreement. Any reproduction * or redistribution of the Software not in accordance with the License Agreement is expressly prohibited * by law, and may result in severe civil and criminal penalties. Violators will be prosecuted to the * maximum extent possible. * * THE SOFTWARE IS WARRANTED, IF AT ALL, ONLY ACCORDING TO THE TERMS OF THE LICENSE AGREEMENT. EXCEPT * AS WARRANTED IN THE LICENSE AGREEMENT, SRCH2 INC. HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS WITH * REGARD TO THE SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL SRCH2 INC. BE LIABLE FOR ANY * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA * OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER ACTION, ARISING OUT OF OR IN CONNECTION * WITH THE USE OR PERFORMANCE OF SOFTWARE. * Copyright © 2010 SRCH2 Inc. All rights reserved */ #include "CacheManager.h" #include "util/Assert.h" #include "util/Logger.h" #include "operation/physical_plan/PhysicalPlan.h" #include <string> #include <map> #include <stddef.h> #include <iostream> #include <sstream> using std::vector; using std::map; namespace srch2 { namespace instantsearch { bool PhysicalOperatorsCache::getPhysicalOperatorsInfo(string & key, boost::shared_ptr<PhysicalOperatorCacheObject> & in){ return this->cacheContainer->get(key , in); } void PhysicalOperatorsCache::setPhysicalOperatosInfo(string & key , boost::shared_ptr<PhysicalOperatorCacheObject> object){ this->cacheContainer->put(key , object); } int PhysicalOperatorsCache::clear(){ return this->cacheContainer->clear(); } int ActiveNodesCache::findLongestPrefixActiveNodes(Term *term, boost::shared_ptr<PrefixActiveNodeSet> &in){ /*// find the longest prefix with active nodes in the cache unsigned termThreshold = term->getThreshold(); string *keyword = term->getKeyword(); for (int i = keyword->size(); i >= 2; i --) { string prefix = keyword->substr(0, i); std::string exactOrFuzzy = termThreshold == 0?"0":"1"; string key = prefix + "$" + exactOrFuzzy; // Cache key is : keyword+0 (for exact) or keyword+1 (for fuzzy) // for example: terminator => "terminator$0" // and terminator~0.5 => "terminator$1" boost::shared_ptr<PrefixActiveNodeSet> cacheHit; if(this->cacheContainer->get(key , cacheHit) == true && cacheHit->getEditDistanceThreshold() >= termThreshold){ in = cacheHit; return 1; } }*/ // no prefix has a cached PrefixActiveNodeSet return 0; } int ActiveNodesCache::setPrefixActiveNodeSet(boost::shared_ptr<PrefixActiveNodeSet> &prefixActiveNodeSet){ vector<CharType> *prefix = prefixActiveNodeSet->getPrefix(); std::stringstream ss ; ss << prefixActiveNodeSet->getEditDistanceThreshold(); std::string exactOrFuzzy = ss.str(); // std::string exactOrFuzzy = prefixActiveNodeSet->getEditDistanceThreshold() == 0?"0":"1"; string key = getUtf8String(*prefix) + "$" + exactOrFuzzy; this->cacheContainer->put(key , prefixActiveNodeSet); return 1; } int ActiveNodesCache::clear(){ return this->cacheContainer->clear(); } ActiveNodesCache * CacheManager::getActiveNodesCache(){ return this->aCache; } QueryResultsCache * CacheManager::getQueryResultsCache(){ return this->qCache; } PhysicalOperatorsCache * CacheManager::getPhysicalOperatorsCache(){ return this->pCache; } PhysicalPlanRecordItemFactory * CacheManager::getPhysicalPlanRecordItemFactory(){ return this->physicalPlanRecordItemFactory; } bool QueryResultsCache::getQueryResults(string & key, boost::shared_ptr<QueryResultsCacheEntry> & in){ return this->cacheContainer->get(key , in); } void QueryResultsCache::setQueryResults(string & key , boost::shared_ptr<QueryResultsCacheEntry> object){ this->cacheContainer->put(key , object); } int QueryResultsCache::clear(){ return this->cacheContainer->clear(); } int CacheManager::clear(){ return this->aCache->clear() && this->qCache->clear() && this->pCache->clear() && this->physicalPlanRecordItemFactory->clear(); } }} <commit_msg>Active node cache was disabled mistakenly. Now enabled again.<commit_after> // $Id: Cache.cpp 3456 2013-06-14 02:11:13Z jiaying $ /* * The Software is made available solely for use according to the License Agreement. Any reproduction * or redistribution of the Software not in accordance with the License Agreement is expressly prohibited * by law, and may result in severe civil and criminal penalties. Violators will be prosecuted to the * maximum extent possible. * * THE SOFTWARE IS WARRANTED, IF AT ALL, ONLY ACCORDING TO THE TERMS OF THE LICENSE AGREEMENT. EXCEPT * AS WARRANTED IN THE LICENSE AGREEMENT, SRCH2 INC. HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS WITH * REGARD TO THE SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL SRCH2 INC. BE LIABLE FOR ANY * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA * OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER ACTION, ARISING OUT OF OR IN CONNECTION * WITH THE USE OR PERFORMANCE OF SOFTWARE. * Copyright © 2010 SRCH2 Inc. All rights reserved */ #include "CacheManager.h" #include "util/Assert.h" #include "util/Logger.h" #include "operation/physical_plan/PhysicalPlan.h" #include <string> #include <map> #include <stddef.h> #include <iostream> #include <sstream> using std::vector; using std::map; namespace srch2 { namespace instantsearch { bool PhysicalOperatorsCache::getPhysicalOperatorsInfo(string & key, boost::shared_ptr<PhysicalOperatorCacheObject> & in){ return this->cacheContainer->get(key , in); } void PhysicalOperatorsCache::setPhysicalOperatosInfo(string & key , boost::shared_ptr<PhysicalOperatorCacheObject> object){ this->cacheContainer->put(key , object); } int PhysicalOperatorsCache::clear(){ return this->cacheContainer->clear(); } int ActiveNodesCache::findLongestPrefixActiveNodes(Term *term, boost::shared_ptr<PrefixActiveNodeSet> &in){ // find the longest prefix with active nodes in the cache unsigned termThreshold = term->getThreshold(); string *keyword = term->getKeyword(); for (int i = keyword->size(); i >= 2; i --) { string prefix = keyword->substr(0, i); std::string exactOrFuzzy = termThreshold == 0?"0":"1"; string key = prefix + "$" + exactOrFuzzy; // Cache key is : keyword+0 (for exact) or keyword+1 (for fuzzy) // for example: terminator => "terminator$0" // and terminator~0.5 => "terminator$1" boost::shared_ptr<PrefixActiveNodeSet> cacheHit; if(this->cacheContainer->get(key , cacheHit) == true && cacheHit->getEditDistanceThreshold() >= termThreshold){ in = cacheHit; return 1; } } // no prefix has a cached PrefixActiveNodeSet return 0; } int ActiveNodesCache::setPrefixActiveNodeSet(boost::shared_ptr<PrefixActiveNodeSet> &prefixActiveNodeSet){ vector<CharType> *prefix = prefixActiveNodeSet->getPrefix(); std::stringstream ss ; ss << prefixActiveNodeSet->getEditDistanceThreshold(); std::string exactOrFuzzy = ss.str(); // std::string exactOrFuzzy = prefixActiveNodeSet->getEditDistanceThreshold() == 0?"0":"1"; string key = getUtf8String(*prefix) + "$" + exactOrFuzzy; this->cacheContainer->put(key , prefixActiveNodeSet); return 1; } int ActiveNodesCache::clear(){ return this->cacheContainer->clear(); } ActiveNodesCache * CacheManager::getActiveNodesCache(){ return this->aCache; } QueryResultsCache * CacheManager::getQueryResultsCache(){ return this->qCache; } PhysicalOperatorsCache * CacheManager::getPhysicalOperatorsCache(){ return this->pCache; } PhysicalPlanRecordItemFactory * CacheManager::getPhysicalPlanRecordItemFactory(){ return this->physicalPlanRecordItemFactory; } bool QueryResultsCache::getQueryResults(string & key, boost::shared_ptr<QueryResultsCacheEntry> & in){ return this->cacheContainer->get(key , in); } void QueryResultsCache::setQueryResults(string & key , boost::shared_ptr<QueryResultsCacheEntry> object){ this->cacheContainer->put(key , object); } int QueryResultsCache::clear(){ return this->cacheContainer->clear(); } int CacheManager::clear(){ return this->aCache->clear() && this->qCache->clear() && this->pCache->clear() && this->physicalPlanRecordItemFactory->clear(); } }} <|endoftext|>
<commit_before>/* * Copyright (C) 2007-2013 German Aerospace Center (DLR/SC) * * Created: 2010-08-13 Markus Litz <Markus.Litz@dlr.de> * Changed: $Id$ * * Version: $Revision$ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @file * @brief Implementation of the TIGL UID manager. */ #include "CTiglUIDManager.h" #include "CTiglError.h" #include "CTiglLogging.h" #include "to_string.h" namespace tigl { // Constructor CTiglUIDManager::CTiglUIDManager() : invalidated(true), rootComponent(NULL) {} void CTiglUIDManager::RegisterObject(const std::string& uid, void* object, const std::type_info& typeInfo) { if (uid.empty()) { throw CTiglError("Tried to register an empty uid for type " + std::string(typeInfo.name())); } // check existence const CPACSObjectMap::iterator it = cpacsObjects.find(uid); if (it != cpacsObjects.end()) { throw CTiglError("Tried to register uid " + uid + " for type " + std::string(typeInfo.name()) + " which is already registered to an instance of " + std::string(it->second.type->name())); } // insert cpacsObjects.insert(it, std::make_pair(uid, TypedPtr( object, &typeInfo ))); } CTiglUIDManager::TypedPtr CTiglUIDManager::ResolveObject(const std::string& uid, const std::type_info& typeInfo) const { const TypedPtr object = ResolveObject(uid); // check type if (&typeInfo != object.type) { throw CTiglError("Object with uid \"" + uid + "\" is not a " + std::string(typeInfo.name()) + " but a " + std::string(object.type->name()), TIGL_UID_ERROR); } return object; } CTiglUIDManager::TypedPtr CTiglUIDManager::ResolveObject(const std::string& uid) const { // check existence const CPACSObjectMap::const_iterator it = cpacsObjects.find(uid); if (it == cpacsObjects.end()) { throw CTiglError("No object is registered for uid \"" + uid + "\"", TIGL_UID_ERROR); } return it->second; } bool CTiglUIDManager::TryUnregisterObject(const std::string& uid) { const CPACSObjectMap::iterator it = cpacsObjects.find(uid); if (it == cpacsObjects.end()) { return false; } cpacsObjects.erase(it); return true; } void CTiglUIDManager::UnregisterObject(const std::string& uid) { if (!TryUnregisterObject(uid)) { throw CTiglError("No object is registered for uid \"" + uid + "\"", TIGL_UID_ERROR); } } namespace { void writeComponent(CTiglRelativelyPositionedComponent* c, int level = 0) { std::string indentation; for (int i = 0; i < level; i++) { indentation += '\t'; } const auto uid = c->GetDefaultedUID(); LOG(INFO) << indentation << (uid.empty() ? "<no uid>" : uid) << std::endl; const CTiglRelativelyPositionedComponent::ChildContainerType& children = c->GetChildren(false); for (CTiglRelativelyPositionedComponent::ChildContainerType::const_iterator it = children.begin(); it != children.end(); ++it) { writeComponent(*it, level + 1); } } } // Update internal UID manager data. void CTiglUIDManager::Update() { if (!invalidated) { return; } BuildTree(); invalidated = false; LOG(INFO) << "Relative component trees:" << std::endl; for (RelativeComponentContainerType::const_iterator it = rootComponents.begin(); it != rootComponents.end(); ++it) { writeComponent(it->second); } } // Function to add a UID and a geometric component to the uid store. void CTiglUIDManager::AddGeometricComponent(const std::string& uid, ITiglGeometricComponent* componentPtr) { if (uid.empty()) { throw CTiglError("Empty UID in CTiglUIDManager::AddGeometricComponent", TIGL_XML_ERROR); } if (HasGeometricComponent(uid)) { throw CTiglError("Duplicate UID " + uid + " in CPACS file (CTiglUIDManager::AddGeometricComponent)", TIGL_XML_ERROR); } if (componentPtr == NULL) { throw CTiglError("Null pointer for component in CTiglUIDManager::AddGeometricComponent", TIGL_NULL_POINTER); } CTiglRelativelyPositionedComponent* tmp = dynamic_cast<CTiglRelativelyPositionedComponent*>(componentPtr); if (tmp && (componentPtr->GetComponentType() & TIGL_COMPONENT_PHYSICAL) ) { relativeComponents[uid] = tmp; } allShapes[uid] = componentPtr; invalidated = true; } void CTiglUIDManager::RemoveGeometricComponent(const std::string &uid) { const ShapeContainerType::iterator it = allShapes.find(uid); if (it == allShapes.end()) { throw CTiglError("No shape is registered for uid \"" + uid + "\""); } allShapes.erase(it); } // Checks if a UID already exists. bool CTiglUIDManager::HasGeometricComponent(const std::string& uid) const { if (uid.empty()) { throw CTiglError("Empty UID in CTiglUIDManager::HasGeometricComponent", TIGL_XML_ERROR); } return (allShapes.find(uid) != allShapes.end()); } // Returns a pointer to the geometric component for the given unique id. ITiglGeometricComponent& CTiglUIDManager::GetGeometricComponent(const std::string& uid) const { if (uid.empty()) { throw CTiglError("Empty UID in CTiglUIDManager::GetGeometricComponent", TIGL_UID_ERROR); } if (!HasGeometricComponent(uid)) { throw CTiglError("UID " + std_to_string(uid) + " not found in CTiglUIDManager::GetGeometricComponent", TIGL_UID_ERROR); } return *allShapes.find(uid)->second; } // Returns a pointer to the geometric component for the given unique id. CTiglRelativelyPositionedComponent& CTiglUIDManager::GetRelativeComponent(const std::string& uid) const { if (uid.empty()) { throw CTiglError("Empty UID in CTiglUIDManager::GetGeometricComponent", TIGL_XML_ERROR); } const RelativeComponentContainerType::const_iterator it = relativeComponents.find(uid); if (it == relativeComponents.end()) { throw CTiglError("UID '"+uid+"' not found in CTiglUIDManager::GetGeometricComponent", TIGL_XML_ERROR); } return *it->second; } // Clears the uid store void CTiglUIDManager::Clear() { relativeComponents.clear(); allShapes.clear(); rootComponents.clear(); cpacsObjects.clear(); invalidated = true; } // Returns the parent component for a component or a null pointer // if there is no parent. CTiglRelativelyPositionedComponent* CTiglUIDManager::GetParentGeometricComponent(const std::string& uid) const { CTiglRelativelyPositionedComponent& component = GetRelativeComponent(uid); const boost::optional<const std::string&> parentUID = component.GetParentUID(); return parentUID ? NULL : &GetRelativeComponent(*parentUID); } // Returns the container with all root components of the geometric topology that have children. const RelativeComponentContainerType& CTiglUIDManager::GetRootGeometricComponents() const { const_cast<CTiglUIDManager&>(*this).Update(); // TODO(bgruber): hack to keep up logical constness, think about mutable members return rootComponents; } // Builds the parent child relationships. void CTiglUIDManager::BuildTree() { // clear all relations for (RelativeComponentContainerType::iterator it = relativeComponents.begin(); it != relativeComponents.end(); ++it) { it->second->ClearChildren(); } // build relations for (RelativeComponentContainerType::iterator it = relativeComponents.begin(); it != relativeComponents.end(); ++it) { CTiglRelativelyPositionedComponent& c = *it->second; const boost::optional<const std::string&> parentUid = c.GetParentUID(); if (parentUid) { if (parentUid->empty()) { throw CTiglError("geometric component with uid " + c.GetDefaultedUID() + " has empty parentUid"); } CTiglRelativelyPositionedComponent& p = GetRelativeComponent(*parentUid); p.AddChild(c); c.SetParent(p); } } // find all components without a parent uid and find component with most children std::size_t count = 0; for (RelativeComponentContainerType::iterator it = relativeComponents.begin(); it != relativeComponents.end(); ++it) { CTiglRelativelyPositionedComponent* c = it->second; if (!c->GetParentUID()) { rootComponents[it->first] = c; } const std::size_t childCount = c->GetChildren(true).size(); if (childCount > count) { count = childCount; rootComponent = c; } } } const ShapeContainerType& CTiglUIDManager::GetShapeContainer() const { return allShapes; } } // end namespace tigl <commit_msg>Fixed invalid auto in pre c++11 code<commit_after>/* * Copyright (C) 2007-2013 German Aerospace Center (DLR/SC) * * Created: 2010-08-13 Markus Litz <Markus.Litz@dlr.de> * Changed: $Id$ * * Version: $Revision$ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @file * @brief Implementation of the TIGL UID manager. */ #include "CTiglUIDManager.h" #include "CTiglError.h" #include "CTiglLogging.h" #include "to_string.h" namespace tigl { // Constructor CTiglUIDManager::CTiglUIDManager() : invalidated(true), rootComponent(NULL) {} void CTiglUIDManager::RegisterObject(const std::string& uid, void* object, const std::type_info& typeInfo) { if (uid.empty()) { throw CTiglError("Tried to register an empty uid for type " + std::string(typeInfo.name())); } // check existence const CPACSObjectMap::iterator it = cpacsObjects.find(uid); if (it != cpacsObjects.end()) { throw CTiglError("Tried to register uid " + uid + " for type " + std::string(typeInfo.name()) + " which is already registered to an instance of " + std::string(it->second.type->name())); } // insert cpacsObjects.insert(it, std::make_pair(uid, TypedPtr( object, &typeInfo ))); } CTiglUIDManager::TypedPtr CTiglUIDManager::ResolveObject(const std::string& uid, const std::type_info& typeInfo) const { const TypedPtr object = ResolveObject(uid); // check type if (&typeInfo != object.type) { throw CTiglError("Object with uid \"" + uid + "\" is not a " + std::string(typeInfo.name()) + " but a " + std::string(object.type->name()), TIGL_UID_ERROR); } return object; } CTiglUIDManager::TypedPtr CTiglUIDManager::ResolveObject(const std::string& uid) const { // check existence const CPACSObjectMap::const_iterator it = cpacsObjects.find(uid); if (it == cpacsObjects.end()) { throw CTiglError("No object is registered for uid \"" + uid + "\"", TIGL_UID_ERROR); } return it->second; } bool CTiglUIDManager::TryUnregisterObject(const std::string& uid) { const CPACSObjectMap::iterator it = cpacsObjects.find(uid); if (it == cpacsObjects.end()) { return false; } cpacsObjects.erase(it); return true; } void CTiglUIDManager::UnregisterObject(const std::string& uid) { if (!TryUnregisterObject(uid)) { throw CTiglError("No object is registered for uid \"" + uid + "\"", TIGL_UID_ERROR); } } namespace { void writeComponent(CTiglRelativelyPositionedComponent* c, int level = 0) { std::string indentation; for (int i = 0; i < level; i++) { indentation += '\t'; } const std::string uid = c->GetDefaultedUID(); LOG(INFO) << indentation << (uid.empty() ? "<no uid>" : uid) << std::endl; const CTiglRelativelyPositionedComponent::ChildContainerType& children = c->GetChildren(false); for (CTiglRelativelyPositionedComponent::ChildContainerType::const_iterator it = children.begin(); it != children.end(); ++it) { writeComponent(*it, level + 1); } } } // Update internal UID manager data. void CTiglUIDManager::Update() { if (!invalidated) { return; } BuildTree(); invalidated = false; LOG(INFO) << "Relative component trees:" << std::endl; for (RelativeComponentContainerType::const_iterator it = rootComponents.begin(); it != rootComponents.end(); ++it) { writeComponent(it->second); } } // Function to add a UID and a geometric component to the uid store. void CTiglUIDManager::AddGeometricComponent(const std::string& uid, ITiglGeometricComponent* componentPtr) { if (uid.empty()) { throw CTiglError("Empty UID in CTiglUIDManager::AddGeometricComponent", TIGL_XML_ERROR); } if (HasGeometricComponent(uid)) { throw CTiglError("Duplicate UID " + uid + " in CPACS file (CTiglUIDManager::AddGeometricComponent)", TIGL_XML_ERROR); } if (componentPtr == NULL) { throw CTiglError("Null pointer for component in CTiglUIDManager::AddGeometricComponent", TIGL_NULL_POINTER); } CTiglRelativelyPositionedComponent* tmp = dynamic_cast<CTiglRelativelyPositionedComponent*>(componentPtr); if (tmp && (componentPtr->GetComponentType() & TIGL_COMPONENT_PHYSICAL) ) { relativeComponents[uid] = tmp; } allShapes[uid] = componentPtr; invalidated = true; } void CTiglUIDManager::RemoveGeometricComponent(const std::string &uid) { const ShapeContainerType::iterator it = allShapes.find(uid); if (it == allShapes.end()) { throw CTiglError("No shape is registered for uid \"" + uid + "\""); } allShapes.erase(it); } // Checks if a UID already exists. bool CTiglUIDManager::HasGeometricComponent(const std::string& uid) const { if (uid.empty()) { throw CTiglError("Empty UID in CTiglUIDManager::HasGeometricComponent", TIGL_XML_ERROR); } return (allShapes.find(uid) != allShapes.end()); } // Returns a pointer to the geometric component for the given unique id. ITiglGeometricComponent& CTiglUIDManager::GetGeometricComponent(const std::string& uid) const { if (uid.empty()) { throw CTiglError("Empty UID in CTiglUIDManager::GetGeometricComponent", TIGL_UID_ERROR); } if (!HasGeometricComponent(uid)) { throw CTiglError("UID " + std_to_string(uid) + " not found in CTiglUIDManager::GetGeometricComponent", TIGL_UID_ERROR); } return *allShapes.find(uid)->second; } // Returns a pointer to the geometric component for the given unique id. CTiglRelativelyPositionedComponent& CTiglUIDManager::GetRelativeComponent(const std::string& uid) const { if (uid.empty()) { throw CTiglError("Empty UID in CTiglUIDManager::GetGeometricComponent", TIGL_XML_ERROR); } const RelativeComponentContainerType::const_iterator it = relativeComponents.find(uid); if (it == relativeComponents.end()) { throw CTiglError("UID '"+uid+"' not found in CTiglUIDManager::GetGeometricComponent", TIGL_XML_ERROR); } return *it->second; } // Clears the uid store void CTiglUIDManager::Clear() { relativeComponents.clear(); allShapes.clear(); rootComponents.clear(); cpacsObjects.clear(); invalidated = true; } // Returns the parent component for a component or a null pointer // if there is no parent. CTiglRelativelyPositionedComponent* CTiglUIDManager::GetParentGeometricComponent(const std::string& uid) const { CTiglRelativelyPositionedComponent& component = GetRelativeComponent(uid); const boost::optional<const std::string&> parentUID = component.GetParentUID(); return parentUID ? NULL : &GetRelativeComponent(*parentUID); } // Returns the container with all root components of the geometric topology that have children. const RelativeComponentContainerType& CTiglUIDManager::GetRootGeometricComponents() const { const_cast<CTiglUIDManager&>(*this).Update(); // TODO(bgruber): hack to keep up logical constness, think about mutable members return rootComponents; } // Builds the parent child relationships. void CTiglUIDManager::BuildTree() { // clear all relations for (RelativeComponentContainerType::iterator it = relativeComponents.begin(); it != relativeComponents.end(); ++it) { it->second->ClearChildren(); } // build relations for (RelativeComponentContainerType::iterator it = relativeComponents.begin(); it != relativeComponents.end(); ++it) { CTiglRelativelyPositionedComponent& c = *it->second; const boost::optional<const std::string&> parentUid = c.GetParentUID(); if (parentUid) { if (parentUid->empty()) { throw CTiglError("geometric component with uid " + c.GetDefaultedUID() + " has empty parentUid"); } CTiglRelativelyPositionedComponent& p = GetRelativeComponent(*parentUid); p.AddChild(c); c.SetParent(p); } } // find all components without a parent uid and find component with most children std::size_t count = 0; for (RelativeComponentContainerType::iterator it = relativeComponents.begin(); it != relativeComponents.end(); ++it) { CTiglRelativelyPositionedComponent* c = it->second; if (!c->GetParentUID()) { rootComponents[it->first] = c; } const std::size_t childCount = c->GetChildren(true).size(); if (childCount > count) { count = childCount; rootComponent = c; } } } const ShapeContainerType& CTiglUIDManager::GetShapeContainer() const { return allShapes; } } // end namespace tigl <|endoftext|>
<commit_before>/** * @file src/dataLoggers/SaveImageLogger.cpp * @date Jan. 2017 * @author PhRG - opticalp.fr */ /* Copyright (c) 2017 Ph. Renaud-Goud / Opticalp 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. */ #ifdef HAVE_OPENCV #include "SaveImageLogger.h" #include "core/DataItem.h" #include "Poco/NumberFormatter.h" #include "opencv2/opencv.hpp" size_t SaveImageLogger::refCount = 0; SaveImageLogger::SaveImageLogger(): DataLogger("SaveImageLogger"), nextIndex(1), extension(".png"), prefix("img_"), digits(2) { setName(refCount); setParameterCount(paramCnt); addParameter(paramDirectory, "directory", "Directory in which to store the images", ParamItem::typeString, ""); addParameter(paramPrefix, "prefix", "Prefix to be used to build the image file name", ParamItem::typeString, "img_"); addParameter(paramDigits, "digits", "Count of digits to be used to build the image file name. " "Those digits will follow the prefix", ParamItem::typeInteger, "2"); addParameter(paramExtension, "extension", "Image file extension, including the dot. E.g. \".png\"", ParamItem::typeString, ".png"); addParameter(paramNextIndex, "nextIndex", "Next index to be used to generate the image file name", ParamItem::typeInteger, "1"); refCount++; } void SaveImageLogger::log() { cv::Mat img = *(getDataSource()->getData<cv::Mat>()); if (img.data) { Poco::Path imgPath(directory); if (digits) { std::string fullIndex = Poco::NumberFormatter::format(nextIndex, digits); std::string index(fullIndex.end()-digits, fullIndex.end()); // cheap modulo imgPath.append(prefix + index + extension); } else { imgPath.append(prefix + extension); } // write image. cv::imwrite(imgPath.toString(), img); // increment parameters nextIndex++; } else { throw Poco::RuntimeException(name(),"empty image, nothing to save"); } } bool SaveImageLogger::isSupportedInputDataType(int datatype) { return (datatype == (DataItem::typeCvMat | DataItem::contScalar)); } std::set<int> SaveImageLogger::supportedInputDataType() { std::set<int> ret; ret.insert(DataItem::typeCvMat); return ret; } Poco::Int64 SaveImageLogger::getIntParameterValue(size_t paramIndex) { switch (paramIndex) { case paramDigits: return digits; case paramNextIndex: return nextIndex; default: poco_bugcheck_msg("wrong parameter index"); throw Poco::BugcheckException(); } } std::string SaveImageLogger::getStrParameterValue(size_t paramIndex) { switch (paramIndex) { case paramDirectory: return directory.toString(); case paramPrefix: return prefix; case paramExtension: return extension; default: poco_bugcheck_msg("wrong parameter index"); throw Poco::BugcheckException(); } } void SaveImageLogger::setIntParameterValue(size_t paramIndex, Poco::Int64 value) { switch (paramIndex) { case paramDigits: if (digits < 0) throw Poco::RangeException("setParameterValue", "parameter digits has to be positive"); digits = value; break; case paramNextIndex: nextIndex = value; break; default: poco_bugcheck_msg("wrong parameter index"); throw Poco::BugcheckException(); } } void SaveImageLogger::setStrParameterValue(size_t paramIndex, std::string value) { switch (paramIndex) { case paramDirectory: directory = value; directory.makeAbsolute(); break; case paramPrefix: prefix = value; break; case paramExtension: extension = value; break; default: poco_bugcheck_msg("wrong parameter index"); throw Poco::BugcheckException(); } } #endif /* HAVE_OPENCV */ <commit_msg>Add simple image type conversion while saving<commit_after>/** * @file src/dataLoggers/SaveImageLogger.cpp * @date Jan. 2017 * @author PhRG - opticalp.fr */ /* Copyright (c) 2017 Ph. Renaud-Goud / Opticalp 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. */ #ifdef HAVE_OPENCV #include "SaveImageLogger.h" #include "core/DataItem.h" #include "Poco/NumberFormatter.h" #include "opencv2/opencv.hpp" size_t SaveImageLogger::refCount = 0; SaveImageLogger::SaveImageLogger(): DataLogger("SaveImageLogger"), nextIndex(1), extension(".png"), prefix("img_"), digits(2) { setName(refCount); setParameterCount(paramCnt); addParameter(paramDirectory, "directory", "Directory in which to store the images", ParamItem::typeString, ""); addParameter(paramPrefix, "prefix", "Prefix to be used to build the image file name", ParamItem::typeString, "img_"); addParameter(paramDigits, "digits", "Count of digits to be used to build the image file name. " "Those digits will follow the prefix", ParamItem::typeInteger, "2"); addParameter(paramExtension, "extension", "Image file extension, including the dot. E.g. \".png\"", ParamItem::typeString, ".png"); addParameter(paramNextIndex, "nextIndex", "Next index to be used to generate the image file name", ParamItem::typeInteger, "1"); refCount++; } void SaveImageLogger::log() { cv::Mat img = *(getDataSource()->getData<cv::Mat>()); if (img.data) { Poco::Path imgPath(directory); if (digits) { std::string fullIndex = Poco::NumberFormatter::format(nextIndex, digits); std::string index(fullIndex.end()-digits, fullIndex.end()); // cheap modulo imgPath.append(prefix + index + extension); } else { imgPath.append(prefix + extension); } if (img.type()!=CV_8U && img.type()!=CV_16U) { double min,max; cv::minMaxLoc(img,&min,&max); cv::Mat tmpImg; // temporary image img.convertTo( tmpImg, // output image CV_8U, // depth 255.0/max ); // scale factor // save image cv::imwrite(imgPath.toString(), tmpImg); } else { cv::imwrite(imgPath.toString(), img); } // increment parameters nextIndex++; } else { throw Poco::RuntimeException(name(),"empty image, nothing to save"); } } bool SaveImageLogger::isSupportedInputDataType(int datatype) { return (datatype == (DataItem::typeCvMat | DataItem::contScalar)); } std::set<int> SaveImageLogger::supportedInputDataType() { std::set<int> ret; ret.insert(DataItem::typeCvMat); return ret; } Poco::Int64 SaveImageLogger::getIntParameterValue(size_t paramIndex) { switch (paramIndex) { case paramDigits: return digits; case paramNextIndex: return nextIndex; default: poco_bugcheck_msg("wrong parameter index"); throw Poco::BugcheckException(); } } std::string SaveImageLogger::getStrParameterValue(size_t paramIndex) { switch (paramIndex) { case paramDirectory: return directory.toString(); case paramPrefix: return prefix; case paramExtension: return extension; default: poco_bugcheck_msg("wrong parameter index"); throw Poco::BugcheckException(); } } void SaveImageLogger::setIntParameterValue(size_t paramIndex, Poco::Int64 value) { switch (paramIndex) { case paramDigits: if (digits < 0) throw Poco::RangeException("setParameterValue", "parameter digits has to be positive"); digits = value; break; case paramNextIndex: nextIndex = value; break; default: poco_bugcheck_msg("wrong parameter index"); throw Poco::BugcheckException(); } } void SaveImageLogger::setStrParameterValue(size_t paramIndex, std::string value) { switch (paramIndex) { case paramDirectory: directory = value; directory.makeAbsolute(); break; case paramPrefix: prefix = value; break; case paramExtension: extension = value; break; default: poco_bugcheck_msg("wrong parameter index"); throw Poco::BugcheckException(); } } #endif /* HAVE_OPENCV */ <|endoftext|>
<commit_before>#include <mesos_sched.hpp> #include <libgen.h> #include <cstdlib> #include <iostream> #include <sstream> #include <boost/lexical_cast.hpp> #include "foreach.hpp" using namespace std; using namespace mesos; using boost::lexical_cast; class MyScheduler : public Scheduler { string executor; int tasksLaunched; int tasksFinished; int totalTasks; public: MyScheduler(const string& exec) : executor(exec), tasksLaunched(0), tasksFinished(0), totalTasks(5) {} virtual ~MyScheduler() {} virtual string getFrameworkName(SchedulerDriver*) { return "C++ Test Framework"; } virtual ExecutorInfo getExecutorInfo(SchedulerDriver*) { return ExecutorInfo(executor, ""); } virtual void registered(SchedulerDriver*, FrameworkID fid) { cout << "Registered!" << endl; } virtual void resourceOffer(SchedulerDriver* d, OfferID id, const std::vector<SlaveOffer>& offers) { cout << "." << flush; vector<TaskDescription> tasks; foreach (const SlaveOffer &offer, offers) { // This is kind of ugly because operator[] isn't a const function int32_t cpus = lexical_cast<int32_t>(offer.params.find("cpus")->second); int32_t mem = lexical_cast<int64_t>(offer.params.find("mem")->second); if ((tasksLaunched < totalTasks) && (cpus >= 1 && mem >= 32)) { TaskID tid = tasksLaunched++; cout << endl << "Starting task " << tid << endl; string name = "Task " + lexical_cast<string>(tid); map<string, string> taskParams; taskParams["cpus"] = "1"; taskParams["mem"] = "32"; TaskDescription desc(tid, offer.slaveId, name, taskParams, ""); tasks.push_back(desc); } } map<string, string> params; params["timeout"] = "-1"; d->replyToOffer(id, tasks, params); } virtual void statusUpdate(SchedulerDriver* d, const TaskStatus& status) { cout << endl; cout << "Task " << status.taskId << " is in state " << status.state << endl; if (status.state == TASK_FINISHED) tasksFinished++; if (tasksFinished == totalTasks) d->stop(); } }; int main(int argc, char ** argv) { if (argc != 2) { cerr << "Usage: " << argv[0] << " <masterPid>" << endl; return -1; } // Find this executable's directory to locate executor char buf[4096]; realpath(dirname(argv[0]), buf); string executor = string(buf) + "/test-executor"; // Run a Mesos scheduler MyScheduler sched(executor); MesosSchedulerDriver driver(&sched, argv[1]); driver.run(); return 0; } <commit_msg>Use the correct executor for the C++ test framework<commit_after>#include <mesos_sched.hpp> #include <libgen.h> #include <cstdlib> #include <iostream> #include <sstream> #include <boost/lexical_cast.hpp> #include "foreach.hpp" using namespace std; using namespace mesos; using boost::lexical_cast; class MyScheduler : public Scheduler { string executor; int tasksLaunched; int tasksFinished; int totalTasks; public: MyScheduler(const string& exec) : executor(exec), tasksLaunched(0), tasksFinished(0), totalTasks(5) {} virtual ~MyScheduler() {} virtual string getFrameworkName(SchedulerDriver*) { return "C++ Test Framework"; } virtual ExecutorInfo getExecutorInfo(SchedulerDriver*) { return ExecutorInfo(executor, ""); } virtual void registered(SchedulerDriver*, FrameworkID fid) { cout << "Registered!" << endl; } virtual void resourceOffer(SchedulerDriver* d, OfferID id, const std::vector<SlaveOffer>& offers) { cout << "." << flush; vector<TaskDescription> tasks; foreach (const SlaveOffer &offer, offers) { // This is kind of ugly because operator[] isn't a const function int32_t cpus = lexical_cast<int32_t>(offer.params.find("cpus")->second); int32_t mem = lexical_cast<int64_t>(offer.params.find("mem")->second); if ((tasksLaunched < totalTasks) && (cpus >= 1 && mem >= 32)) { TaskID tid = tasksLaunched++; cout << endl << "Starting task " << tid << endl; string name = "Task " + lexical_cast<string>(tid); map<string, string> taskParams; taskParams["cpus"] = "1"; taskParams["mem"] = "32"; TaskDescription desc(tid, offer.slaveId, name, taskParams, ""); tasks.push_back(desc); } } map<string, string> params; params["timeout"] = "-1"; d->replyToOffer(id, tasks, params); } virtual void statusUpdate(SchedulerDriver* d, const TaskStatus& status) { cout << endl; cout << "Task " << status.taskId << " is in state " << status.state << endl; if (status.state == TASK_FINISHED) tasksFinished++; if (tasksFinished == totalTasks) d->stop(); } }; int main(int argc, char ** argv) { if (argc != 2) { cerr << "Usage: " << argv[0] << " <masterPid>" << endl; return -1; } // Find this executable's directory to locate executor char buf[4096]; realpath(dirname(argv[0]), buf); string executor = string(buf) + "/cpp-test-executor"; // Run a Mesos scheduler MyScheduler sched(executor); MesosSchedulerDriver driver(&sched, argv[1]); driver.run(); return 0; } <|endoftext|>
<commit_before>/* Copyright 2019 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 "tensorflow/lite/kernels/internal/reference/pooling.h" #include "arm_nnfunctions.h" #include "scratch_buffer.h" #include "tensorflow/lite/c/builtin_op_data.h" #include "tensorflow/lite/kernels/internal/reference/integer_ops/pooling.h" #include "tensorflow/lite/kernels/internal/tensor_ctypes.h" #include "tensorflow/lite/kernels/kernel_util.h" #include "tensorflow/lite/kernels/padding.h" namespace tflite { namespace ops { namespace micro { namespace pooling { namespace { constexpr int kInputTensor = 0; constexpr int kOutputTensor = 0; struct OpData { TfLitePaddingValues padding; }; TfLiteStatus CalculateOpData(const TfLiteContext* context, const TfLitePoolParams* params, const TfLiteTensor* input, const TfLiteTensor* output, OpData* data) { // input: batch, height, width, channel int height = SizeOfDimension(input, 1); int width = SizeOfDimension(input, 2); int out_height, out_width; data->padding = ComputePaddingHeightWidth( params->stride_height, params->stride_width, /*dilation_rate_height=*/1, /*dilation_rate_width=*/1, height, width, params->filter_height, params->filter_width, params->padding, &out_height, &out_width); return kTfLiteOk; } void AverageEvalFloat(const TfLiteContext* context, const TfLiteNode* node, const TfLitePoolParams* params, const OpData* data, const TfLiteTensor* input, TfLiteTensor* output) { float activation_min, activation_max; CalculateActivationRange(params->activation, &activation_min, &activation_max); PoolParams op_params; op_params.stride_height = params->stride_height; op_params.stride_width = params->stride_width; op_params.filter_height = params->filter_height; op_params.filter_width = params->filter_width; op_params.padding_values.height = data->padding.height; op_params.padding_values.width = data->padding.width; op_params.float_activation_min = activation_min; op_params.float_activation_max = activation_max; reference_ops::AveragePool( op_params, GetTensorShape(input), GetTensorData<float>(input), GetTensorShape(output), GetTensorData<float>(output)); } void AverageEvalUint8(const TfLiteContext* context, const TfLiteNode* node, const TfLitePoolParams* params, const OpData* data, const TfLiteTensor* input, TfLiteTensor* output) { int32_t activation_min, activation_max; CalculateActivationRangeUint8(params->activation, output, &activation_min, &activation_max); PoolParams op_params; op_params.stride_height = params->stride_height; op_params.stride_width = params->stride_width; op_params.filter_height = params->filter_height; op_params.filter_width = params->filter_width; op_params.padding_values.height = data->padding.height; op_params.padding_values.width = data->padding.width; op_params.quantized_activation_min = activation_min; op_params.quantized_activation_max = activation_max; reference_ops::AveragePool( op_params, GetTensorShape(input), GetTensorData<uint8_t>(input), GetTensorShape(output), GetTensorData<uint8_t>(output)); } TfLiteStatus AverageEvalInt8(const TfLiteContext* context, const TfLiteNode* node, const TfLitePoolParams* params, const OpData* data, const TfLiteTensor* input, TfLiteTensor* output) { int32_t activation_min, activation_max; CalculateActivationRangeInt8(params->activation, output, &activation_min, &activation_max); TFLITE_DCHECK_LE(params->quantized_activation_min, params->quantized_activation_max); RuntimeShape input_shape = GetTensorShape(input); TFLITE_DCHECK_EQ(input_shape.DimensionsCount(), 4); RuntimeShape output_shape = GetTensorShape(output); TFLITE_DCHECK_EQ(output_shape.DimensionsCount(), 4); const int batches = MatchingDim(input_shape, 0, output_shape, 0); const int depth = MatchingDim(input_shape, 3, output_shape, 3); const int input_height = input_shape.Dims(1); const int input_width = input_shape.Dims(2); const int output_height = output_shape.Dims(1); const int output_width = output_shape.Dims(2); const int stride_height = params->stride_height; const int stride_width = params->stride_width; const int filter_height = params->filter_height; const int filter_width = params->filter_width; const int padding_height = data->padding.height; const int padding_width = data->padding.width; #if defined(ARM_MATH_DSP) && defined(ARM_MATH_LOOPUNROLL) int16_t* scratch_buffer = nullptr; const int32_t buffer_size = arm_avgpool_s8_get_buffer_size(output_width, depth); TF_LITE_ENSURE_OK( context, get_cmsis_scratch_buffer(context, &scratch_buffer, buffer_size)); TF_LITE_ENSURE_EQ( context, arm_avgpool_s8(input_height, input_width, output_height, output_width, stride_height, stride_width, filter_height, filter_width, padding_height, padding_width, activation_min, activation_max, depth, GetTensorData<int8_t>(input), scratch_buffer, GetTensorData<int8_t>(output)), ARM_MATH_SUCCESS); #else #error ARM_MATH_DSP and ARM_MATH_LOOPUNROLL must be set #endif return kTfLiteOk; } void MaxEvalFloat(TfLiteContext* context, TfLiteNode* node, TfLitePoolParams* params, OpData* data, const TfLiteTensor* input, TfLiteTensor* output) { float activation_min, activation_max; CalculateActivationRange(params->activation, &activation_min, &activation_max); tflite::PoolParams op_params; op_params.stride_height = params->stride_height; op_params.stride_width = params->stride_width; op_params.filter_height = params->filter_height; op_params.filter_width = params->filter_width; op_params.padding_values.height = data->padding.height; op_params.padding_values.width = data->padding.width; op_params.float_activation_min = activation_min; op_params.float_activation_max = activation_max; reference_ops::MaxPool(op_params, GetTensorShape(input), GetTensorData<float>(input), GetTensorShape(output), GetTensorData<float>(output)); } void MaxEvalQuantizedUInt8(TfLiteContext* context, TfLiteNode* node, TfLitePoolParams* params, OpData* data, const TfLiteTensor* input, TfLiteTensor* output) { int32_t activation_min, activation_max; CalculateActivationRangeUint8(params->activation, output, &activation_min, &activation_max); tflite::PoolParams op_params; op_params.stride_height = params->stride_height; op_params.stride_width = params->stride_width; op_params.filter_height = params->filter_height; op_params.filter_width = params->filter_width; op_params.padding_values.height = data->padding.height; op_params.padding_values.width = data->padding.width; op_params.quantized_activation_min = activation_min; op_params.quantized_activation_max = activation_max; reference_ops::MaxPool(op_params, GetTensorShape(input), GetTensorData<uint8_t>(input), GetTensorShape(output), GetTensorData<uint8_t>(output)); } } // namespace void* Init(TfLiteContext* context, const char* buffer, size_t length) { return nullptr; } void Free(TfLiteContext* context, void* buffer) {} TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) { return kTfLiteOk; } TfLiteStatus AverageEval(TfLiteContext* context, TfLiteNode* node) { auto* params = reinterpret_cast<TfLitePoolParams*>(node->builtin_data); OpData data; const TfLiteTensor* input = GetInput(context, node, kInputTensor); TfLiteTensor* output = GetOutput(context, node, kOutputTensor); TF_LITE_ENSURE_STATUS(CalculateOpData(context, params, input, output, &data)); // Inputs and outputs share the same type, guarenteed by the converter. switch (input->type) { case kTfLiteFloat32: AverageEvalFloat(context, node, params, &data, input, output); break; case kTfLiteUInt8: AverageEvalUint8(context, node, params, &data, input, output); break; case kTfLiteInt8: return AverageEvalInt8(context, node, params, &data, input, output); break; default: context->ReportError(context, "Input type %s is not currently supported", TfLiteTypeGetName(input->type)); return kTfLiteError; } return kTfLiteOk; } TfLiteStatus MaxEval(TfLiteContext* context, TfLiteNode* node) { auto* params = reinterpret_cast<TfLitePoolParams*>(node->builtin_data); OpData data; const TfLiteTensor* input = GetInput(context, node, kInputTensor); TfLiteTensor* output = GetOutput(context, node, kOutputTensor); TF_LITE_ENSURE_STATUS(CalculateOpData(context, params, input, output, &data)); switch (input->type) { case kTfLiteFloat32: MaxEvalFloat(context, node, params, &data, input, output); break; case kTfLiteUInt8: MaxEvalQuantizedUInt8(context, node, params, &data, input, output); break; default: context->ReportError(context, "Type %s not currently supported.", TfLiteTypeGetName(input->type)); return kTfLiteError; } return kTfLiteOk; } } // namespace pooling TfLiteRegistration* Register_AVERAGE_POOL_2D() { static TfLiteRegistration r = { pooling::Init, pooling::Free, pooling::Prepare, pooling::AverageEval, }; return &r; } TfLiteRegistration* Register_MAX_POOL_2D() { static TfLiteRegistration r = {pooling::Init, pooling::Free, pooling::Prepare, pooling::MaxEval}; return &r; } } // namespace micro } // namespace ops } // namespace tflite <commit_msg>Added reference average pooling kernel fallback<commit_after>/* Copyright 2019 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 "tensorflow/lite/kernels/internal/reference/pooling.h" #include "arm_nnfunctions.h" #include "scratch_buffer.h" #include "tensorflow/lite/c/builtin_op_data.h" #include "tensorflow/lite/kernels/internal/reference/integer_ops/pooling.h" #include "tensorflow/lite/kernels/internal/tensor_ctypes.h" #include "tensorflow/lite/kernels/kernel_util.h" #include "tensorflow/lite/kernels/padding.h" namespace tflite { namespace ops { namespace micro { namespace pooling { namespace { constexpr int kInputTensor = 0; constexpr int kOutputTensor = 0; struct OpData { TfLitePaddingValues padding; }; TfLiteStatus CalculateOpData(const TfLiteContext* context, const TfLitePoolParams* params, const TfLiteTensor* input, const TfLiteTensor* output, OpData* data) { // input: batch, height, width, channel int height = SizeOfDimension(input, 1); int width = SizeOfDimension(input, 2); int out_height, out_width; data->padding = ComputePaddingHeightWidth( params->stride_height, params->stride_width, /*dilation_rate_height=*/1, /*dilation_rate_width=*/1, height, width, params->filter_height, params->filter_width, params->padding, &out_height, &out_width); return kTfLiteOk; } void AverageEvalFloat(const TfLiteContext* context, const TfLiteNode* node, const TfLitePoolParams* params, const OpData* data, const TfLiteTensor* input, TfLiteTensor* output) { float activation_min, activation_max; CalculateActivationRange(params->activation, &activation_min, &activation_max); PoolParams op_params; op_params.stride_height = params->stride_height; op_params.stride_width = params->stride_width; op_params.filter_height = params->filter_height; op_params.filter_width = params->filter_width; op_params.padding_values.height = data->padding.height; op_params.padding_values.width = data->padding.width; op_params.float_activation_min = activation_min; op_params.float_activation_max = activation_max; reference_ops::AveragePool( op_params, GetTensorShape(input), GetTensorData<float>(input), GetTensorShape(output), GetTensorData<float>(output)); } void AverageEvalUint8(const TfLiteContext* context, const TfLiteNode* node, const TfLitePoolParams* params, const OpData* data, const TfLiteTensor* input, TfLiteTensor* output) { int32_t activation_min, activation_max; CalculateActivationRangeUint8(params->activation, output, &activation_min, &activation_max); PoolParams op_params; op_params.stride_height = params->stride_height; op_params.stride_width = params->stride_width; op_params.filter_height = params->filter_height; op_params.filter_width = params->filter_width; op_params.padding_values.height = data->padding.height; op_params.padding_values.width = data->padding.width; op_params.quantized_activation_min = activation_min; op_params.quantized_activation_max = activation_max; reference_ops::AveragePool( op_params, GetTensorShape(input), GetTensorData<uint8_t>(input), GetTensorShape(output), GetTensorData<uint8_t>(output)); } TfLiteStatus AverageEvalInt8(const TfLiteContext* context, const TfLiteNode* node, const TfLitePoolParams* params, const OpData* data, const TfLiteTensor* input, TfLiteTensor* output) { int32_t activation_min, activation_max; CalculateActivationRangeInt8(params->activation, output, &activation_min, &activation_max); TFLITE_DCHECK_LE(params->quantized_activation_min, params->quantized_activation_max); RuntimeShape input_shape = GetTensorShape(input); TFLITE_DCHECK_EQ(input_shape.DimensionsCount(), 4); RuntimeShape output_shape = GetTensorShape(output); TFLITE_DCHECK_EQ(output_shape.DimensionsCount(), 4); const int batches = MatchingDim(input_shape, 0, output_shape, 0); const int depth = MatchingDim(input_shape, 3, output_shape, 3); const int input_height = input_shape.Dims(1); const int input_width = input_shape.Dims(2); const int output_height = output_shape.Dims(1); const int output_width = output_shape.Dims(2); const int stride_height = params->stride_height; const int stride_width = params->stride_width; const int filter_height = params->filter_height; const int filter_width = params->filter_width; const int padding_height = data->padding.height; const int padding_width = data->padding.width; #if defined(ARM_MATH_DSP) && defined(ARM_MATH_LOOPUNROLL) int16_t* scratch_buffer = nullptr; const int32_t buffer_size = arm_avgpool_s8_get_buffer_size(output_width, depth); TF_LITE_ENSURE_OK( context, get_cmsis_scratch_buffer(context, &scratch_buffer, buffer_size)); TF_LITE_ENSURE_EQ( context, arm_avgpool_s8(input_height, input_width, output_height, output_width, stride_height, stride_width, filter_height, filter_width, padding_height, padding_width, activation_min, activation_max, depth, GetTensorData<int8_t>(input), scratch_buffer, GetTensorData<int8_t>(output)), ARM_MATH_SUCCESS); #else reference_integer_ops::AveragePool( op_params, GetTensorShape(input), GetTensorData<int8_t>(input), GetTensorShape(output), GetTensorData<int8_t>(output)); #endif return kTfLiteOk; } void MaxEvalFloat(TfLiteContext* context, TfLiteNode* node, TfLitePoolParams* params, OpData* data, const TfLiteTensor* input, TfLiteTensor* output) { float activation_min, activation_max; CalculateActivationRange(params->activation, &activation_min, &activation_max); tflite::PoolParams op_params; op_params.stride_height = params->stride_height; op_params.stride_width = params->stride_width; op_params.filter_height = params->filter_height; op_params.filter_width = params->filter_width; op_params.padding_values.height = data->padding.height; op_params.padding_values.width = data->padding.width; op_params.float_activation_min = activation_min; op_params.float_activation_max = activation_max; reference_ops::MaxPool(op_params, GetTensorShape(input), GetTensorData<float>(input), GetTensorShape(output), GetTensorData<float>(output)); } void MaxEvalQuantizedUInt8(TfLiteContext* context, TfLiteNode* node, TfLitePoolParams* params, OpData* data, const TfLiteTensor* input, TfLiteTensor* output) { int32_t activation_min, activation_max; CalculateActivationRangeUint8(params->activation, output, &activation_min, &activation_max); tflite::PoolParams op_params; op_params.stride_height = params->stride_height; op_params.stride_width = params->stride_width; op_params.filter_height = params->filter_height; op_params.filter_width = params->filter_width; op_params.padding_values.height = data->padding.height; op_params.padding_values.width = data->padding.width; op_params.quantized_activation_min = activation_min; op_params.quantized_activation_max = activation_max; reference_ops::MaxPool(op_params, GetTensorShape(input), GetTensorData<uint8_t>(input), GetTensorShape(output), GetTensorData<uint8_t>(output)); } } // namespace void* Init(TfLiteContext* context, const char* buffer, size_t length) { return nullptr; } void Free(TfLiteContext* context, void* buffer) {} TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) { return kTfLiteOk; } TfLiteStatus AverageEval(TfLiteContext* context, TfLiteNode* node) { auto* params = reinterpret_cast<TfLitePoolParams*>(node->builtin_data); OpData data; const TfLiteTensor* input = GetInput(context, node, kInputTensor); TfLiteTensor* output = GetOutput(context, node, kOutputTensor); TF_LITE_ENSURE_STATUS(CalculateOpData(context, params, input, output, &data)); // Inputs and outputs share the same type, guarenteed by the converter. switch (input->type) { case kTfLiteFloat32: AverageEvalFloat(context, node, params, &data, input, output); break; case kTfLiteUInt8: AverageEvalUint8(context, node, params, &data, input, output); break; case kTfLiteInt8: return AverageEvalInt8(context, node, params, &data, input, output); break; default: context->ReportError(context, "Input type %s is not currently supported", TfLiteTypeGetName(input->type)); return kTfLiteError; } return kTfLiteOk; } TfLiteStatus MaxEval(TfLiteContext* context, TfLiteNode* node) { auto* params = reinterpret_cast<TfLitePoolParams*>(node->builtin_data); OpData data; const TfLiteTensor* input = GetInput(context, node, kInputTensor); TfLiteTensor* output = GetOutput(context, node, kOutputTensor); TF_LITE_ENSURE_STATUS(CalculateOpData(context, params, input, output, &data)); switch (input->type) { case kTfLiteFloat32: MaxEvalFloat(context, node, params, &data, input, output); break; case kTfLiteUInt8: MaxEvalQuantizedUInt8(context, node, params, &data, input, output); break; default: context->ReportError(context, "Type %s not currently supported.", TfLiteTypeGetName(input->type)); return kTfLiteError; } return kTfLiteOk; } } // namespace pooling TfLiteRegistration* Register_AVERAGE_POOL_2D() { static TfLiteRegistration r = { pooling::Init, pooling::Free, pooling::Prepare, pooling::AverageEval, }; return &r; } TfLiteRegistration* Register_MAX_POOL_2D() { static TfLiteRegistration r = {pooling::Init, pooling::Free, pooling::Prepare, pooling::MaxEval}; return &r; } } // namespace micro } // namespace ops } // namespace tflite <|endoftext|>
<commit_before>#include <iostream> #include <string> #include <vector> #include <algorithm> using namespace std; bool IsPalindrome(const string& s) { if (s == "") { return true; } int n = s.size(); if (s[0] != s[n-1]) { return false; } else { return IsPalindrome(s.substr(1, n-2)); } } bool IsTolerable(const string& s, int p) { char maxChar = p - 1 + 'a'; for (size_t i = 0; i < s.size(); ++i) { if (s[i] > maxChar) { return false; } } int n = s.size(); for (int k = 2; k <= n; ++k) { for (int i = 0; i <= n-k; ++i) { if (IsPalindrome(s.substr(i, k))) { return false; } } } return true; } string StrAddOne(const string& s, int p) { char maxChar = p - 1 + 'a'; string ans(s); int n = ans.size(); ans[n-1] += 1; if (ans[n-1] <= maxChar) { return ans; } for (int i = n-1; i >= 0; --i) { if (ans[i] > maxChar) { ans[i] = 'a'; if (i-1 >= 0) { ans[i-1] += 1; } } } return ans; } int main() { int n, p; cin >> n >> p; string s; cin >> s; char maxChar = p - 1 + 'a'; string maxStr(n, maxChar); string ans; do { ans = StrAddOne(s, p); if (ans >= maxStr) { cout << "NO" << endl; return 0; } if (IsTolerable(ans, p)) { cout << ans << endl; return 0; } s = ans; }while(true); return 0; } <commit_msg>A, B, easy good; C, too complicated, TLE<commit_after>#include <iostream> #include <string> #include <vector> #include <algorithm> using namespace std; bool IsPalindrome(const string& s) { if (s == "") { return true; } int n = s.size(); if (s[0] != s[n-1]) { return false; } else { return IsPalindrome(s.substr(1, n-2)); } } bool IsTolerable(const string& s, int p) { char maxChar = p - 1 + 'a'; for (size_t i = 0; i < s.size(); ++i) { if (s[i] > maxChar) { return false; } } int n = s.size(); for (int k = 2; k <= n; ++k) { for (int i = 0; i <= n-k; ++i) { if (IsPalindrome(s.substr(i, k))) { return false; } } } return true; } string StrAddOne(const string& s, int p) { char maxChar = p - 1 + 'a'; string ans(s); int n = ans.size(); ans[n-1] += 1; if (ans[n-1] <= maxChar) { return ans; } for (int i = n-1; i >= 1; --i) { if (ans[i] > maxChar) { ans[i] = 'a'; ans[i-1] += 1; } } if (ans[0] > maxChar) { ans[0] = 'a'; ans = "a" + ans; } return ans; } int main() { int n, p; cin >> n >> p; string s; cin >> s; char maxChar = p - 1 + 'a'; string maxStr(n, maxChar); string ans; do { ans = StrAddOne(s, p); if (ans.size() > maxStr.size()) { cout << "NO" << endl; return 0; } if (IsTolerable(ans, p)) { cout << ans << endl; return 0; } s = ans; }while(true); return 0; } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtTest/QtTest> #include <QDebug> #include <multimedia/qmediaserviceprovider.h> #include <multimedia/qmediaserviceproviderplugin.h> #include <multimedia/qmediapluginloader_p.h> #include <multimedia/qmediaobject.h> #include <multimedia/qmediaservice.h> #include <multimedia/qmediaplayer.h> class MockMediaService : public QMediaService { Q_OBJECT public: MockMediaService(const QString& name, QObject *parent = 0) : QMediaService(parent) { setObjectName(name); } ~MockMediaService() {} QMediaControl* control(const char *) const {return 0;} }; class MockServicePlugin1 : public QMediaServiceProviderPlugin, public QMediaServiceSupportedFormatsInterface, public QMediaServiceSupportedDevicesInterface { Q_OBJECT Q_INTERFACES(QMediaServiceSupportedFormatsInterface) Q_INTERFACES(QMediaServiceSupportedDevicesInterface) public: QStringList keys() const { return QStringList() << QLatin1String(Q_MEDIASERVICE_MEDIAPLAYER) << QLatin1String(Q_MEDIASERVICE_CAMERA); } QMediaService* create(QString const& key) { if (keys().contains(key)) return new MockMediaService("MockServicePlugin1"); else return 0; } void release(QMediaService *service) { delete service; } QtMedia::SupportEstimate hasSupport(const QString &mimeType, const QStringList& codecs) const { if (codecs.contains(QLatin1String("mpeg4"))) return QtMedia::NotSupported; if (mimeType == "audio/ogg") { return QtMedia::ProbablySupported; } return QtMedia::MaybeSupported; } QList<QByteArray> devices(const QByteArray &service) const { QList<QByteArray> res; if (service == QByteArray(Q_MEDIASERVICE_CAMERA)) res << "camera1" << "camera2"; return res; } QString deviceDescription(const QByteArray &service, const QByteArray &device) { if (devices(service).contains(device)) return QString(device)+" description"; else return QString(); } }; class MockServicePlugin2 : public QMediaServiceProviderPlugin, public QMediaServiceSupportedFormatsInterface { Q_OBJECT Q_INTERFACES(QMediaServiceSupportedFormatsInterface) public: QStringList keys() const { return QStringList() << QLatin1String(Q_MEDIASERVICE_MEDIAPLAYER); } QMediaService* create(QString const& key) { if (keys().contains(key)) return new MockMediaService("MockServicePlugin2"); else return 0; } void release(QMediaService *service) { delete service; } QtMedia::SupportEstimate hasSupport(const QString &mimeType, const QStringList& codecs) const { Q_UNUSED(codecs); if (mimeType == "audio/wav") return QtMedia::PreferedService; return QtMedia::NotSupported; } }; class MockServicePlugin3 : public QMediaServiceProviderPlugin, public QMediaServiceSupportedDevicesInterface { Q_OBJECT Q_INTERFACES(QMediaServiceSupportedDevicesInterface) public: QStringList keys() const { return QStringList() << QLatin1String(Q_MEDIASERVICE_MEDIAPLAYER) << QLatin1String(Q_MEDIASERVICE_CAMERA) << QLatin1String(Q_MEDIASERVICE_AUDIOSOURCE); } QMediaService* create(QString const& key) { if (keys().contains(key)) return new MockMediaService("MockServicePlugin3"); else return 0; } void release(QMediaService *service) { delete service; } QList<QByteArray> devices(const QByteArray &service) const { QList<QByteArray> res; if (service == QByteArray(Q_MEDIASERVICE_CAMERA)) res << "camera3" << "camera4"; else if (service == QByteArray(Q_MEDIASERVICE_AUDIOSOURCE)) res << "audiosource1" << "audiosource2"; return res; } QString deviceDescription(const QByteArray &service, const QByteArray &device) { if (devices(service).contains(device)) return QString(device)+" description"; else return QString(); } }; class MockMediaServiceProvider : public QMediaServiceProvider { QMediaService* requestService(const QByteArray &type, const QMediaServiceProviderHint &) { Q_UNUSED(type); return 0; } void releaseService(QMediaService *service) { Q_UNUSED(service); } }; class tst_QMediaServiceProvider : public QObject { Q_OBJECT public slots: void initTestCase(); private slots: void testDefaultProviderAvailable(); void testObtainService(); void testHasSupport(); void testDevices(); void testProviderHints(); private: QObjectList plugins; }; void tst_QMediaServiceProvider::initTestCase() { plugins << new MockServicePlugin1; plugins << new MockServicePlugin2; plugins << new MockServicePlugin3; QMediaPluginLoader::setStaticPlugins(QLatin1String("/mediaservice"), plugins); } void tst_QMediaServiceProvider::testDefaultProviderAvailable() { // Must always be a default provider available QVERIFY(QMediaServiceProvider::defaultServiceProvider() != 0); } void tst_QMediaServiceProvider::testObtainService() { QMediaServiceProvider *provider = QMediaServiceProvider::defaultServiceProvider(); if (provider == 0) QSKIP("No default provider", SkipSingle); QMediaService *service = 0; QTest::ignoreMessage(QtWarningMsg, "Load static plugins for \"/mediaservice/\" "); // Player service = provider->requestService(Q_MEDIASERVICE_MEDIAPLAYER); QVERIFY(service != 0); provider->releaseService(service); } void tst_QMediaServiceProvider::testHasSupport() { MockMediaServiceProvider mockProvider; QCOMPARE(mockProvider.hasSupport(QByteArray(Q_MEDIASERVICE_MEDIAPLAYER), "video/ogv", QStringList()), QtMedia::MaybeSupported); QMediaServiceProvider *provider = QMediaServiceProvider::defaultServiceProvider(); if (provider == 0) QSKIP("No default provider", SkipSingle); QCOMPARE(provider->hasSupport(QByteArray(Q_MEDIASERVICE_MEDIAPLAYER), "video/ogv", QStringList()), QtMedia::MaybeSupported); QCOMPARE(provider->hasSupport(QByteArray(Q_MEDIASERVICE_MEDIAPLAYER), "audio/ogg", QStringList()), QtMedia::ProbablySupported); //while the service returns PreferredService, provider should return ProbablySupported QCOMPARE(provider->hasSupport(QByteArray(Q_MEDIASERVICE_MEDIAPLAYER), "audio/wav", QStringList()), QtMedia::ProbablySupported); //even while all the plugins with "hasSupport" returned NotSupported, //MockServicePlugin3 has no "hasSupport" interface, so MaybeSupported QCOMPARE(provider->hasSupport(QByteArray(Q_MEDIASERVICE_MEDIAPLAYER), "video/avi", QStringList() << "mpeg4"), QtMedia::MaybeSupported); QCOMPARE(provider->hasSupport(QByteArray("non existing service"), "video/ogv", QStringList()), QtMedia::NotSupported); QCOMPARE(QMediaPlayer::hasSupport("video/ogv"), QtMedia::MaybeSupported); QCOMPARE(QMediaPlayer::hasSupport("audio/ogg"), QtMedia::ProbablySupported); QCOMPARE(QMediaPlayer::hasSupport("audio/wav"), QtMedia::ProbablySupported); } void tst_QMediaServiceProvider::testDevices() { MockMediaServiceProvider mockProvider; QVERIFY(mockProvider.devices(QByteArray(Q_MEDIASERVICE_CAMERA)).isEmpty()); QVERIFY(mockProvider.deviceDescription(QByteArray(Q_MEDIASERVICE_CAMERA), QByteArray()).isEmpty()); QMediaServiceProvider *provider = QMediaServiceProvider::defaultServiceProvider(); QVERIFY(!provider->devices(QByteArray(Q_MEDIASERVICE_CAMERA)).isEmpty()); QVERIFY(provider->devices(QByteArray("non existing service")).isEmpty()); } void tst_QMediaServiceProvider::testProviderHints() { { QMediaServiceProviderHint hint; QVERIFY(hint.isNull()); QCOMPARE(hint.type(), QMediaServiceProviderHint::Null); QVERIFY(hint.device().isEmpty()); QVERIFY(hint.mimeType().isEmpty()); QVERIFY(hint.codecs().isEmpty()); QCOMPARE(hint.features(), 0); } { QByteArray deviceName(QByteArray("testDevice")); QMediaServiceProviderHint hint(deviceName); QVERIFY(!hint.isNull()); QCOMPARE(hint.type(), QMediaServiceProviderHint::Device); QCOMPARE(hint.device(), deviceName); QVERIFY(hint.mimeType().isEmpty()); QVERIFY(hint.codecs().isEmpty()); QCOMPARE(hint.features(), 0); } { QMediaServiceProviderHint hint(QMediaServiceProviderHint::LowLatencyPlayback); QVERIFY(!hint.isNull()); QCOMPARE(hint.type(), QMediaServiceProviderHint::SupportedFeatures); QVERIFY(hint.device().isEmpty()); QVERIFY(hint.mimeType().isEmpty()); QVERIFY(hint.codecs().isEmpty()); QCOMPARE(hint.features(), QMediaServiceProviderHint::LowLatencyPlayback); } { QString mimeType(QLatin1String("video/ogg")); QStringList codecs; codecs << "theora" << "vorbis"; QMediaServiceProviderHint hint(mimeType,codecs); QVERIFY(!hint.isNull()); QCOMPARE(hint.type(), QMediaServiceProviderHint::ContentType); QVERIFY(hint.device().isEmpty()); QCOMPARE(hint.mimeType(), mimeType); QCOMPARE(hint.codecs(), codecs); QMediaServiceProviderHint hint2(hint); QVERIFY(!hint2.isNull()); QCOMPARE(hint2.type(), QMediaServiceProviderHint::ContentType); QVERIFY(hint2.device().isEmpty()); QCOMPARE(hint2.mimeType(), mimeType); QCOMPARE(hint2.codecs(), codecs); QMediaServiceProviderHint hint3; QVERIFY(hint3.isNull()); hint3 = hint; QVERIFY(!hint3.isNull()); QCOMPARE(hint3.type(), QMediaServiceProviderHint::ContentType); QVERIFY(hint3.device().isEmpty()); QCOMPARE(hint3.mimeType(), mimeType); QCOMPARE(hint3.codecs(), codecs); QCOMPARE(hint, hint2); QCOMPARE(hint3, hint2); QMediaServiceProviderHint hint4(mimeType,codecs); QCOMPARE(hint, hint4); QMediaServiceProviderHint hint5(mimeType,QStringList()); QVERIFY(hint != hint5); } } QTEST_MAIN(tst_QMediaServiceProvider) #include "tst_qmediaserviceprovider.moc" <commit_msg>Added tests for camera service selection by device name and player by supported low latency playback feature.<commit_after>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtTest/QtTest> #include <QDebug> #include <multimedia/qmediaserviceprovider.h> #include <multimedia/qmediaserviceproviderplugin.h> #include <multimedia/qmediapluginloader_p.h> #include <multimedia/qmediaobject.h> #include <multimedia/qmediaservice.h> #include <multimedia/qmediaplayer.h> #include <multimedia/experimental/qcamera.h> #include <multimedia/qaudiocapturesource.h> class MockMediaService : public QMediaService { Q_OBJECT public: MockMediaService(const QString& name, QObject *parent = 0) : QMediaService(parent) { setObjectName(name); } ~MockMediaService() {} QMediaControl* control(const char *) const {return 0;} }; class MockServicePlugin1 : public QMediaServiceProviderPlugin, public QMediaServiceSupportedFormatsInterface, public QMediaServiceSupportedDevicesInterface { Q_OBJECT Q_INTERFACES(QMediaServiceSupportedFormatsInterface) Q_INTERFACES(QMediaServiceSupportedDevicesInterface) public: QStringList keys() const { return QStringList() << QLatin1String(Q_MEDIASERVICE_MEDIAPLAYER) << QLatin1String(Q_MEDIASERVICE_CAMERA); } QMediaService* create(QString const& key) { if (keys().contains(key)) return new MockMediaService("MockServicePlugin1"); else return 0; } void release(QMediaService *service) { delete service; } QtMedia::SupportEstimate hasSupport(const QString &mimeType, const QStringList& codecs) const { if (codecs.contains(QLatin1String("mpeg4"))) return QtMedia::NotSupported; if (mimeType == "audio/ogg") { return QtMedia::ProbablySupported; } return QtMedia::MaybeSupported; } QList<QByteArray> devices(const QByteArray &service) const { QList<QByteArray> res; if (service == QByteArray(Q_MEDIASERVICE_CAMERA)) res << "camera1" << "camera2"; return res; } QString deviceDescription(const QByteArray &service, const QByteArray &device) { if (devices(service).contains(device)) return QString(device)+" description"; else return QString(); } }; class MockServicePlugin2 : public QMediaServiceProviderPlugin, public QMediaServiceSupportedFormatsInterface, public QMediaServiceFeaturesInterface { Q_OBJECT Q_INTERFACES(QMediaServiceSupportedFormatsInterface) Q_INTERFACES(QMediaServiceFeaturesInterface) public: QStringList keys() const { return QStringList() << QLatin1String(Q_MEDIASERVICE_MEDIAPLAYER); } QMediaService* create(QString const& key) { if (keys().contains(key)) return new MockMediaService("MockServicePlugin2"); else return 0; } void release(QMediaService *service) { delete service; } QtMedia::SupportEstimate hasSupport(const QString &mimeType, const QStringList& codecs) const { Q_UNUSED(codecs); if (mimeType == "audio/wav") return QtMedia::PreferedService; return QtMedia::NotSupported; } QMediaServiceProviderHint::Features supportedFeatures(const QByteArray &service) const { if (service == QByteArray(Q_MEDIASERVICE_MEDIAPLAYER)) return QMediaServiceProviderHint::LowLatencyPlayback; else return 0; } }; class MockServicePlugin3 : public QMediaServiceProviderPlugin, public QMediaServiceSupportedDevicesInterface { Q_OBJECT Q_INTERFACES(QMediaServiceSupportedDevicesInterface) public: QStringList keys() const { return QStringList() << QLatin1String(Q_MEDIASERVICE_MEDIAPLAYER) << QLatin1String(Q_MEDIASERVICE_CAMERA) << QLatin1String(Q_MEDIASERVICE_AUDIOSOURCE); } QMediaService* create(QString const& key) { if (keys().contains(key)) return new MockMediaService("MockServicePlugin3"); else return 0; } void release(QMediaService *service) { delete service; } QList<QByteArray> devices(const QByteArray &service) const { QList<QByteArray> res; if (service == QByteArray(Q_MEDIASERVICE_CAMERA)) res << "camera3" << "camera4"; else if (service == QByteArray(Q_MEDIASERVICE_AUDIOSOURCE)) res << "audiosource1" << "audiosource2"; return res; } QString deviceDescription(const QByteArray &service, const QByteArray &device) { if (devices(service).contains(device)) return QString(device)+" description"; else return QString(); } }; class MockMediaServiceProvider : public QMediaServiceProvider { QMediaService* requestService(const QByteArray &type, const QMediaServiceProviderHint &) { Q_UNUSED(type); return 0; } void releaseService(QMediaService *service) { Q_UNUSED(service); } }; class tst_QMediaServiceProvider : public QObject { Q_OBJECT public slots: void initTestCase(); private slots: void testDefaultProviderAvailable(); void testObtainService(); void testHasSupport(); void testDevices(); void testProviderHints(); private: QObjectList plugins; }; void tst_QMediaServiceProvider::initTestCase() { plugins << new MockServicePlugin1; plugins << new MockServicePlugin2; plugins << new MockServicePlugin3; QMediaPluginLoader::setStaticPlugins(QLatin1String("/mediaservice"), plugins); } void tst_QMediaServiceProvider::testDefaultProviderAvailable() { // Must always be a default provider available QVERIFY(QMediaServiceProvider::defaultServiceProvider() != 0); } void tst_QMediaServiceProvider::testObtainService() { QMediaServiceProvider *provider = QMediaServiceProvider::defaultServiceProvider(); if (provider == 0) QSKIP("No default provider", SkipSingle); QMediaService *service = 0; QTest::ignoreMessage(QtWarningMsg, "Load static plugins for \"/mediaservice/\" "); // Player service = provider->requestService(Q_MEDIASERVICE_MEDIAPLAYER); QVERIFY(service != 0); provider->releaseService(service); } void tst_QMediaServiceProvider::testHasSupport() { MockMediaServiceProvider mockProvider; QCOMPARE(mockProvider.hasSupport(QByteArray(Q_MEDIASERVICE_MEDIAPLAYER), "video/ogv", QStringList()), QtMedia::MaybeSupported); QMediaServiceProvider *provider = QMediaServiceProvider::defaultServiceProvider(); if (provider == 0) QSKIP("No default provider", SkipSingle); QCOMPARE(provider->hasSupport(QByteArray(Q_MEDIASERVICE_MEDIAPLAYER), "video/ogv", QStringList()), QtMedia::MaybeSupported); QCOMPARE(provider->hasSupport(QByteArray(Q_MEDIASERVICE_MEDIAPLAYER), "audio/ogg", QStringList()), QtMedia::ProbablySupported); //while the service returns PreferredService, provider should return ProbablySupported QCOMPARE(provider->hasSupport(QByteArray(Q_MEDIASERVICE_MEDIAPLAYER), "audio/wav", QStringList()), QtMedia::ProbablySupported); //even while all the plugins with "hasSupport" returned NotSupported, //MockServicePlugin3 has no "hasSupport" interface, so MaybeSupported QCOMPARE(provider->hasSupport(QByteArray(Q_MEDIASERVICE_MEDIAPLAYER), "video/avi", QStringList() << "mpeg4"), QtMedia::MaybeSupported); QCOMPARE(provider->hasSupport(QByteArray("non existing service"), "video/ogv", QStringList()), QtMedia::NotSupported); QCOMPARE(QMediaPlayer::hasSupport("video/ogv"), QtMedia::MaybeSupported); QCOMPARE(QMediaPlayer::hasSupport("audio/ogg"), QtMedia::ProbablySupported); QCOMPARE(QMediaPlayer::hasSupport("audio/wav"), QtMedia::ProbablySupported); //ensure the correct media player plugin is choosen for mime type QMediaPlayer simplePlayer(0, QMediaPlayer::LowLatency); QCOMPARE(simplePlayer.service()->objectName(), QLatin1String("MockServicePlugin2")); QMediaPlayer mediaPlayer; QVERIFY(mediaPlayer.service()->objectName() != QLatin1String("MockServicePlugin2")); } void tst_QMediaServiceProvider::testDevices() { MockMediaServiceProvider mockProvider; QVERIFY(mockProvider.devices(QByteArray(Q_MEDIASERVICE_CAMERA)).isEmpty()); QVERIFY(mockProvider.deviceDescription(QByteArray(Q_MEDIASERVICE_CAMERA), QByteArray()).isEmpty()); QMediaServiceProvider *provider = QMediaServiceProvider::defaultServiceProvider(); QList<QByteArray> cameraDevices = provider->devices(QByteArray(Q_MEDIASERVICE_CAMERA)); QCOMPARE(cameraDevices.count(), 4); QVERIFY(cameraDevices.contains(QByteArray("camera1"))); QVERIFY(cameraDevices.contains(QByteArray("camera2"))); QVERIFY(cameraDevices.contains(QByteArray("camera3"))); QVERIFY(cameraDevices.contains(QByteArray("camera4"))); //ensure the right plugin is choosen for a device QCamera camera1(QByteArray("camera1")); QCOMPARE( camera1.service()->objectName(), QLatin1String("MockServicePlugin1") ); QCamera camera2(QByteArray("camera2")); QCOMPARE( camera2.service()->objectName(), QLatin1String("MockServicePlugin1") ); QCamera camera3(QByteArray("camera3")); QCOMPARE( camera3.service()->objectName(), QLatin1String("MockServicePlugin3") ); QCamera camera4(QByteArray("camera4")); QCOMPARE( camera4.service()->objectName(), QLatin1String("MockServicePlugin3") ); QList<QByteArray> audioSourceDevices = provider->devices(QByteArray(Q_MEDIASERVICE_AUDIOSOURCE)); QCOMPARE(audioSourceDevices.count(), 2); QVERIFY(audioSourceDevices.contains(QByteArray("audiosource1"))); QVERIFY(audioSourceDevices.contains(QByteArray("audiosource2"))); QVERIFY(provider->devices(QByteArray("non existing service")).isEmpty()); } void tst_QMediaServiceProvider::testProviderHints() { { QMediaServiceProviderHint hint; QVERIFY(hint.isNull()); QCOMPARE(hint.type(), QMediaServiceProviderHint::Null); QVERIFY(hint.device().isEmpty()); QVERIFY(hint.mimeType().isEmpty()); QVERIFY(hint.codecs().isEmpty()); QCOMPARE(hint.features(), 0); } { QByteArray deviceName(QByteArray("testDevice")); QMediaServiceProviderHint hint(deviceName); QVERIFY(!hint.isNull()); QCOMPARE(hint.type(), QMediaServiceProviderHint::Device); QCOMPARE(hint.device(), deviceName); QVERIFY(hint.mimeType().isEmpty()); QVERIFY(hint.codecs().isEmpty()); QCOMPARE(hint.features(), 0); } { QMediaServiceProviderHint hint(QMediaServiceProviderHint::LowLatencyPlayback); QVERIFY(!hint.isNull()); QCOMPARE(hint.type(), QMediaServiceProviderHint::SupportedFeatures); QVERIFY(hint.device().isEmpty()); QVERIFY(hint.mimeType().isEmpty()); QVERIFY(hint.codecs().isEmpty()); QCOMPARE(hint.features(), QMediaServiceProviderHint::LowLatencyPlayback); } { QString mimeType(QLatin1String("video/ogg")); QStringList codecs; codecs << "theora" << "vorbis"; QMediaServiceProviderHint hint(mimeType,codecs); QVERIFY(!hint.isNull()); QCOMPARE(hint.type(), QMediaServiceProviderHint::ContentType); QVERIFY(hint.device().isEmpty()); QCOMPARE(hint.mimeType(), mimeType); QCOMPARE(hint.codecs(), codecs); QMediaServiceProviderHint hint2(hint); QVERIFY(!hint2.isNull()); QCOMPARE(hint2.type(), QMediaServiceProviderHint::ContentType); QVERIFY(hint2.device().isEmpty()); QCOMPARE(hint2.mimeType(), mimeType); QCOMPARE(hint2.codecs(), codecs); QMediaServiceProviderHint hint3; QVERIFY(hint3.isNull()); hint3 = hint; QVERIFY(!hint3.isNull()); QCOMPARE(hint3.type(), QMediaServiceProviderHint::ContentType); QVERIFY(hint3.device().isEmpty()); QCOMPARE(hint3.mimeType(), mimeType); QCOMPARE(hint3.codecs(), codecs); QCOMPARE(hint, hint2); QCOMPARE(hint3, hint2); QMediaServiceProviderHint hint4(mimeType,codecs); QCOMPARE(hint, hint4); QMediaServiceProviderHint hint5(mimeType,QStringList()); QVERIFY(hint != hint5); } } QTEST_MAIN(tst_QMediaServiceProvider) #include "tst_qmediaserviceprovider.moc" <|endoftext|>
<commit_before>/* * Copyright 2008-2010 NVIDIA Corporation * * 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 <thrust/copy.h> #include <thrust/gather.h> #include <thrust/sequence.h> #include <thrust/iterator/iterator_traits.h> #include <thrust/detail/raw_buffer.h> #include <thrust/detail/type_traits.h> #include <thrust/detail/util/align.h> #include <thrust/detail/device/cuda/detail/b40c/radixsort_api.h> namespace thrust { namespace detail { namespace device { namespace cuda { namespace detail { template<typename RandomAccessIterator> void stable_radix_sort(RandomAccessIterator first, RandomAccessIterator last) { typedef typename thrust::iterator_value<RandomAccessIterator>::type K; unsigned int num_elements = last - first; // ensure data is properly aligned if (!thrust::detail::util::is_aligned(thrust::raw_pointer_cast(&*first), 2*sizeof(K))) { thrust::detail::raw_cuda_device_buffer<K> aligned_keys(first, last); stable_radix_sort(aligned_keys.begin(), aligned_keys.end()); thrust::copy(aligned_keys.begin(), aligned_keys.end(), first); return; } b40c::RadixSortingEnactor<K> sorter(num_elements); b40c::RadixSortStorage<K> storage; // allocate temporary buffers thrust::detail::raw_cuda_device_buffer<K> temp_keys(num_elements); thrust::detail::raw_cuda_device_buffer<unsigned int> temp_spine(sorter.SpineElements()); thrust::detail::raw_cuda_device_buffer<bool> temp_from_alt(2); // define storage storage.d_keys = thrust::raw_pointer_cast(&*first); storage.d_alt_keys = thrust::raw_pointer_cast(&temp_keys[0]); storage.d_spine = thrust::raw_pointer_cast(&temp_spine[0]); storage.d_from_alt_storage = thrust::raw_pointer_cast(&temp_from_alt[0]); // perform the sort sorter.EnactSort(storage); // radix sort sometimes leaves results in the alternate buffers if (storage.using_alternate_storage) { thrust::copy(temp_keys.begin(), temp_keys.end(), first); } // temporary storage automatically freed } /////////////////////// // Key-Value Sorting // /////////////////////// // sort values directly template<typename RandomAccessIterator1, typename RandomAccessIterator2> void stable_radix_sort_by_key(RandomAccessIterator1 first1, RandomAccessIterator1 last1, RandomAccessIterator2 first2, thrust::detail::true_type) { typedef typename thrust::iterator_value<RandomAccessIterator1>::type K; typedef typename thrust::iterator_value<RandomAccessIterator2>::type V; unsigned int num_elements = last1 - first1; // ensure data is properly aligned if (!thrust::detail::util::is_aligned(thrust::raw_pointer_cast(&*first1), 2*sizeof(K))) { thrust::detail::raw_cuda_device_buffer<K> aligned_keys(first1, last1); stable_radix_sort_by_key(aligned_keys.begin(), aligned_keys.end(), first2); thrust::copy(aligned_keys.begin(), aligned_keys.end(), first1); return; } if (!thrust::detail::util::is_aligned(thrust::raw_pointer_cast(&*first2), 2*sizeof(V))) { thrust::detail::raw_cuda_device_buffer<V> aligned_values(first2, first2 + num_elements); stable_radix_sort_by_key(first1, last1, aligned_values.begin()); thrust::copy(aligned_values.begin(), aligned_values.end(), first2); return; } b40c::RadixSortingEnactor<K,V> sorter(num_elements); b40c::RadixSortStorage<K,V> storage; // allocate temporary buffers thrust::detail::raw_cuda_device_buffer<K> temp_keys(num_elements); thrust::detail::raw_cuda_device_buffer<V> temp_values(num_elements); thrust::detail::raw_cuda_device_buffer<unsigned int> temp_spine(sorter.SpineElements()); thrust::detail::raw_cuda_device_buffer<bool> temp_from_alt(2); // define storage storage.d_keys = thrust::raw_pointer_cast(&*first1); storage.d_values = thrust::raw_pointer_cast(&*first2); storage.d_alt_keys = thrust::raw_pointer_cast(&temp_keys[0]); storage.d_alt_values = thrust::raw_pointer_cast(&temp_values[0]); storage.d_spine = thrust::raw_pointer_cast(&temp_spine[0]); storage.d_from_alt_storage = thrust::raw_pointer_cast(&temp_from_alt[0]); // perform the sort sorter.EnactSort(storage); // radix sort sometimes leaves results in the alternate buffers if (storage.using_alternate_storage) { thrust::copy( temp_keys.begin(), temp_keys.end(), first1); thrust::copy(temp_values.begin(), temp_values.end(), first2); } // temporary storage automatically freed } // sort values indirectly template<typename RandomAccessIterator1, typename RandomAccessIterator2> void stable_radix_sort_by_key(RandomAccessIterator1 first1, RandomAccessIterator1 last1, RandomAccessIterator2 first2, thrust::detail::false_type) { typedef typename thrust::iterator_value<RandomAccessIterator2>::type V; unsigned int num_elements = last1 - first1; // sort with integer values and then permute the real values accordingly thrust::detail::raw_cuda_device_buffer<unsigned int> permutation(num_elements); thrust::sequence(permutation.begin(), permutation.end()); stable_radix_sort_by_key(first1, last1, permutation.begin()); // copy values into temp vector and then permute thrust::detail::raw_cuda_device_buffer<V> temp_values(first2, first2 + num_elements); // permute values thrust::gather(permutation.begin(), permutation.end(), temp_values.begin(), first2); } template<typename RandomAccessIterator1, typename RandomAccessIterator2> void stable_radix_sort_by_key(RandomAccessIterator1 first1, RandomAccessIterator1 last1, RandomAccessIterator2 first2) { typedef typename thrust::iterator_value<RandomAccessIterator2>::type V; // decide how to handle values static const bool sort_values_directly = thrust::detail::is_trivial_iterator<RandomAccessIterator2>::value && thrust::detail::is_arithmetic<V>::value && sizeof(V) <= 8; // TODO profile this // XXX WAR nvcc 3.0 unused variable warning (void) sort_values_directly; stable_radix_sort_by_key(first1, last1, first2, thrust::detail::integral_constant<bool, sort_values_directly>()); } } // end namespace detail } // end namespace cuda } // end namespace device } // end namespace detail } // end namespace thrust <commit_msg>access b40c namespace via full path<commit_after>/* * Copyright 2008-2010 NVIDIA Corporation * * 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 <thrust/copy.h> #include <thrust/gather.h> #include <thrust/sequence.h> #include <thrust/iterator/iterator_traits.h> #include <thrust/detail/raw_buffer.h> #include <thrust/detail/type_traits.h> #include <thrust/detail/util/align.h> #include <thrust/detail/device/cuda/detail/b40c/radixsort_api.h> namespace thrust { namespace detail { namespace device { namespace cuda { namespace detail { template<typename RandomAccessIterator> void stable_radix_sort(RandomAccessIterator first, RandomAccessIterator last) { typedef typename thrust::iterator_value<RandomAccessIterator>::type K; unsigned int num_elements = last - first; // ensure data is properly aligned if (!thrust::detail::util::is_aligned(thrust::raw_pointer_cast(&*first), 2*sizeof(K))) { thrust::detail::raw_cuda_device_buffer<K> aligned_keys(first, last); stable_radix_sort(aligned_keys.begin(), aligned_keys.end()); thrust::copy(aligned_keys.begin(), aligned_keys.end(), first); return; } thrust::detail::device::cuda::detail::b40c::RadixSortingEnactor<K> sorter(num_elements); thrust::detail::device::cuda::detail::b40c::RadixSortStorage<K> storage; // allocate temporary buffers thrust::detail::raw_cuda_device_buffer<K> temp_keys(num_elements); thrust::detail::raw_cuda_device_buffer<unsigned int> temp_spine(sorter.SpineElements()); thrust::detail::raw_cuda_device_buffer<bool> temp_from_alt(2); // define storage storage.d_keys = thrust::raw_pointer_cast(&*first); storage.d_alt_keys = thrust::raw_pointer_cast(&temp_keys[0]); storage.d_spine = thrust::raw_pointer_cast(&temp_spine[0]); storage.d_from_alt_storage = thrust::raw_pointer_cast(&temp_from_alt[0]); // perform the sort sorter.EnactSort(storage); // radix sort sometimes leaves results in the alternate buffers if (storage.using_alternate_storage) { thrust::copy(temp_keys.begin(), temp_keys.end(), first); } // temporary storage automatically freed } /////////////////////// // Key-Value Sorting // /////////////////////// // sort values directly template<typename RandomAccessIterator1, typename RandomAccessIterator2> void stable_radix_sort_by_key(RandomAccessIterator1 first1, RandomAccessIterator1 last1, RandomAccessIterator2 first2, thrust::detail::true_type) { typedef typename thrust::iterator_value<RandomAccessIterator1>::type K; typedef typename thrust::iterator_value<RandomAccessIterator2>::type V; unsigned int num_elements = last1 - first1; // ensure data is properly aligned if (!thrust::detail::util::is_aligned(thrust::raw_pointer_cast(&*first1), 2*sizeof(K))) { thrust::detail::raw_cuda_device_buffer<K> aligned_keys(first1, last1); stable_radix_sort_by_key(aligned_keys.begin(), aligned_keys.end(), first2); thrust::copy(aligned_keys.begin(), aligned_keys.end(), first1); return; } if (!thrust::detail::util::is_aligned(thrust::raw_pointer_cast(&*first2), 2*sizeof(V))) { thrust::detail::raw_cuda_device_buffer<V> aligned_values(first2, first2 + num_elements); stable_radix_sort_by_key(first1, last1, aligned_values.begin()); thrust::copy(aligned_values.begin(), aligned_values.end(), first2); return; } thrust::detail::device::cuda::detail::b40c::RadixSortingEnactor<K,V> sorter(num_elements); thrust::detail::device::cuda::detail::b40c::RadixSortStorage<K,V> storage; // allocate temporary buffers thrust::detail::raw_cuda_device_buffer<K> temp_keys(num_elements); thrust::detail::raw_cuda_device_buffer<V> temp_values(num_elements); thrust::detail::raw_cuda_device_buffer<unsigned int> temp_spine(sorter.SpineElements()); thrust::detail::raw_cuda_device_buffer<bool> temp_from_alt(2); // define storage storage.d_keys = thrust::raw_pointer_cast(&*first1); storage.d_values = thrust::raw_pointer_cast(&*first2); storage.d_alt_keys = thrust::raw_pointer_cast(&temp_keys[0]); storage.d_alt_values = thrust::raw_pointer_cast(&temp_values[0]); storage.d_spine = thrust::raw_pointer_cast(&temp_spine[0]); storage.d_from_alt_storage = thrust::raw_pointer_cast(&temp_from_alt[0]); // perform the sort sorter.EnactSort(storage); // radix sort sometimes leaves results in the alternate buffers if (storage.using_alternate_storage) { thrust::copy( temp_keys.begin(), temp_keys.end(), first1); thrust::copy(temp_values.begin(), temp_values.end(), first2); } // temporary storage automatically freed } // sort values indirectly template<typename RandomAccessIterator1, typename RandomAccessIterator2> void stable_radix_sort_by_key(RandomAccessIterator1 first1, RandomAccessIterator1 last1, RandomAccessIterator2 first2, thrust::detail::false_type) { typedef typename thrust::iterator_value<RandomAccessIterator2>::type V; unsigned int num_elements = last1 - first1; // sort with integer values and then permute the real values accordingly thrust::detail::raw_cuda_device_buffer<unsigned int> permutation(num_elements); thrust::sequence(permutation.begin(), permutation.end()); stable_radix_sort_by_key(first1, last1, permutation.begin()); // copy values into temp vector and then permute thrust::detail::raw_cuda_device_buffer<V> temp_values(first2, first2 + num_elements); // permute values thrust::gather(permutation.begin(), permutation.end(), temp_values.begin(), first2); } template<typename RandomAccessIterator1, typename RandomAccessIterator2> void stable_radix_sort_by_key(RandomAccessIterator1 first1, RandomAccessIterator1 last1, RandomAccessIterator2 first2) { typedef typename thrust::iterator_value<RandomAccessIterator2>::type V; // decide how to handle values static const bool sort_values_directly = thrust::detail::is_trivial_iterator<RandomAccessIterator2>::value && thrust::detail::is_arithmetic<V>::value && sizeof(V) <= 8; // TODO profile this // XXX WAR nvcc 3.0 unused variable warning (void) sort_values_directly; stable_radix_sort_by_key(first1, last1, first2, thrust::detail::integral_constant<bool, sort_values_directly>()); } } // end namespace detail } // end namespace cuda } // end namespace device } // end namespace detail } // end namespace thrust <|endoftext|>
<commit_before>#ifndef STAN_MATH_REV_FUN_QUAD_FORM_SYM_HPP #define STAN_MATH_REV_FUN_QUAD_FORM_SYM_HPP #include <stan/math/rev/meta.hpp> #include <stan/math/rev/core.hpp> #include <stan/math/prim/err.hpp> #include <stan/math/prim/fun/Eigen.hpp> #include <stan/math/prim/fun/to_ref.hpp> #include <stan/math/rev/fun/quad_form.hpp> #include <type_traits> namespace stan { namespace math { /** * Return the quadratic form \f$ B^T A B \f$ of a symmetric matrix. * * Symmetry of the resulting matrix is guaranteed. * * @tparam EigMat1 type of the first (symmetric) matrix * @tparam EigMat2 type of the second matrix * * @param A symmetric matrix * @param B second matrix * @return The quadratic form, which is a symmetric matrix of size Cb. * If \c B is a column vector returns a scalar. * @throws std::invalid_argument if A is not symmetric, or if A cannot be * multiplied by B */ template <typename EigMat1, typename EigMat2, require_all_eigen_t<EigMat1, EigMat2>* = nullptr, require_any_vt_var<EigMat1, EigMat2>* = nullptr> inline auto quad_form_sym(const EigMat1& A, const EigMat2& B) { check_multiplicable("quad_form_sym", "A", A, "B", B); const auto& A_ref = to_ref(A); check_symmetric("quad_form_sym", "A", A_ref); return quad_form(A_ref, B); } } // namespace math } // namespace stan #endif <commit_msg>fixes #2095; using the symmetric version of quad_form<commit_after>#ifndef STAN_MATH_REV_FUN_QUAD_FORM_SYM_HPP #define STAN_MATH_REV_FUN_QUAD_FORM_SYM_HPP #include <stan/math/rev/meta.hpp> #include <stan/math/rev/core.hpp> #include <stan/math/prim/err.hpp> #include <stan/math/prim/fun/Eigen.hpp> #include <stan/math/prim/fun/to_ref.hpp> #include <stan/math/rev/fun/quad_form.hpp> #include <type_traits> namespace stan { namespace math { /** * Return the quadratic form \f$ B^T A B \f$ of a symmetric matrix. * * Symmetry of the resulting matrix is guaranteed. * * @tparam EigMat1 type of the first (symmetric) matrix * @tparam EigMat2 type of the second matrix * * @param A symmetric matrix * @param B second matrix * @return The quadratic form, which is a symmetric matrix of size Cb. * If \c B is a column vector returns a scalar. * @throws std::invalid_argument if A is not symmetric, or if A cannot be * multiplied by B */ template <typename EigMat1, typename EigMat2, require_all_eigen_t<EigMat1, EigMat2>* = nullptr, require_any_vt_var<EigMat1, EigMat2>* = nullptr> inline auto quad_form_sym(const EigMat1& A, const EigMat2& B) { check_multiplicable("quad_form_sym", "A", A, "B", B); const auto& A_ref = to_ref(A); check_symmetric("quad_form_sym", "A", A_ref); return quad_form(A_ref, B, true); } } // namespace math } // namespace stan #endif <|endoftext|>
<commit_before>/* matrix.cpp Purpose: A Matrix implementation to ease future problems that could more efficiently be solved with Matrix abstraction. @author c650 @version 0.1 1/10/16 The MIT License (MIT) Copyright (c) 2016 c650 */ #include <iostream> #include <vector> #include <cstdlib> /* Begin the Matrix class: */ template <typename T> class Matrix { /* `elements` is a 2D array that is a vector of the rows of the matrix. */ std::vector< std::vector<T> > elements; public: /* Constructors: */ /* Makes a new instance of Matrix @param elem a 2D vector that represents what a Matrix actually is. @return a new instance of Matrix */ Matrix(std::vector< std::vector<T> > elem) : elements(elem) {} /* Makes a new instance of Matrix @param m another instance of Matrix to copy using func get_all_elements() @return a new instance of Matrix */ Matrix(Matrix &m) : elements(m.elements) {} /* Makes a new, empty instance of Matrix @param rows the number of rows desired @param cols the number of columns desired @return a new instance of Matrix */ Matrix(const int &rows, const int &cols) { std::vector< std::vector<T> > _elem(rows, std::vector<T>(cols)); elements = _elem; } /* REMEMBER THE DESTRUCTOR */ ~Matrix(); /* Column and Row Size Getters: */ /* Returns the number of columns in an instance of Matrix @return the number of columns */ int num_cols() { return elements[0].size(); } /* Returns the number of rows for an instance of Matrix @return the number of columns */ int num_rows() { return elements.size(); } /* Returns a vector representing a row in the Matrix */ std::vector<T> operator[](const int &rhs) { if (abs(rhs) > num_rows()) { throw "operator[] in Matrix out of bounds"; } if (rhs >= 0) { return elements[rhs]; } else { return elements[num_rows() + rhs]; } } /* Element Getter and Setter: */ /* Changes the value of a given position in the Matrix. @param row the row that holds the value to change @param col the column of the value to change @param val the value to set */ void set(const int &row, const int &col, T const &val) { if (this->num_cols() > col && this->num_rows() > row) elements[row][col] = val; } /* Gets the value held at a certain position in the Matrix. @param row the row to read from @param col the column to read from @return the value of type T held at the positon row,col in the Matrix */ T get(const int &row, const int &col) { if (this->num_cols() > col && this->num_rows() > row) return elements[row][col]; else return 0; } /* Matrix Arithmetic Methods */ /* ADDITION: Binary operator to add two matrices together. Does not modify either matrix. @param other the Matrix on the right side of + @return a Matrix, whose elements are the sums of the corresponding elements of `this` and `other` */ Matrix<T> operator+(Matrix<T> &other) { // Matrices must be same dimensions to // be addable if (this->num_rows() != other.num_rows() || this->num_cols() != other.num_cols()) return *this; // make matrix based on `this` Matrix<T> resultant(*this); for (int i = 0, n = this->num_rows(); i < n; i++) { for (int j = 0, o = this->num_cols(); j < o; j++) { // set each value in the resultant equal // to the sum of the corresponding values // in `this` and `other` resultant.set(i, j, this->get(i, j) + other.get(i, j)); } } return resultant; } /* SUBTRACTION: Binary operator to subtract two matrices. Does not modify either matrix. @param other the Matrix on the right side of - @return a Matrix, whose elements are the differences of the corresponding elements of `this` and `other` */ Matrix<T> operator-(Matrix<T> &other) { return (*this) + (other * -1); } /* MATRIX*MATRIX MULTIPLICATION Binary operator to multiple two matrices. Does not modify either matrix. @param other the Matrix on the right side of * @return a Matrix, whose elements are the products of the corresponding elements of `this` and `other`, following the accepted way of multiplying matrices. */ Matrix<T> operator*(Matrix<T> &other) { Matrix<T> resultant(this->num_rows(), other.num_cols()); if (this->num_cols() != other.num_rows()) return *this; // go through all rows of the left Matrix for (int i = 0, n = this->num_rows(); i < n; i++) { // go through all columns of right Matrix for each row // of the left Matrix for (int j = 0, o = other.num_cols(); j < o; j++) { T tmp = 0; int x = 0; while (x < n) { tmp += (this->get(i, x) * other.get(x, j)); x++; } resultant.set(i, j, tmp); // put the tmp into the resultant } } return resultant; } /* MATRIX*SCALAR MULTIPLICATION Multiplies a Matrix by a scalar value. @param other the scalar value @return the result of scaling `this` by `other` */ Matrix<T> operator*(T &other) { Matrix<T> resultant(*this); for (int i = 0, n = this->num_rows(); i < n; i++) { for (int j = 0, o = this->num_cols(); j < o; j++) { resultant.elements[i][j] *= other; } } return resultant; } /* Matrix Power Method Powers >= 1 only! @param p an unsigned integer >= 1 to which the Matrix will be raised. @return the Matrix raised to the `p` power */ Matrix power(const unsigned int &p) { if (p == 1) return *this; else if (p <= 0) // set for now to keep it safe return *this; Matrix m(*this); m = m.power(p / 2); m = m * m; if (p % 2 == 1) m = m * (*this); return m; } /* Matrix Printer Formats the Matrix for STDOUT */ std::ostream& operator<<(std::ostream& out) { for (int i = 0, n = this.num_rows(); i < n; i++) { out << "| "; for (int j = 0, o = this.num_cols(); j < o; j++) { out << this.elements[i][j] << " "; } out << "|" << std::endl; } return out; } }; int main() { return 0; }<commit_msg>fixing throw erros<commit_after>/* matrix.cpp Purpose: A Matrix implementation to ease future problems that could more efficiently be solved with Matrix abstraction. @author c650 @version 0.1 1/10/16 The MIT License (MIT) Copyright (c) 2016 c650 */ #include <iostream> #include <vector> #include <cstdlib> /* Begin the Matrix class: */ template <typename T> class Matrix { /* `elements` is a 2D array that is a vector of the rows of the matrix. */ std::vector< std::vector<T> > elements; public: /* Constructors: */ /* Makes a new instance of Matrix @param elem a 2D vector that represents what a Matrix actually is. @return a new instance of Matrix */ Matrix(std::vector< std::vector<T> > elem) : elements(elem) {} /* Makes a new instance of Matrix @param m another instance of Matrix to copy using func get_all_elements() @return a new instance of Matrix */ Matrix(Matrix &m) : elements(m.elements) {} /* Makes a new, empty instance of Matrix @param rows the number of rows desired @param cols the number of columns desired @return a new instance of Matrix */ Matrix(const int &rows, const int &cols) { std::vector< std::vector<T> > _elem(rows, std::vector<T>(cols)); elements = _elem; } /* REMEMBER THE DESTRUCTOR */ ~Matrix(); /* Column and Row Size Getters: */ /* Returns the number of columns in an instance of Matrix @return the number of columns */ int num_cols() { return elements[0].size(); } /* Returns the number of rows for an instance of Matrix @return the number of columns */ int num_rows() { return elements.size(); } /* Returns a vector representing a row in the Matrix */ std::vector<T> operator[](const int &rhs) { if (abs(rhs) > num_rows()) { throw std::invalid_argument("operator[] in Matrix out of bounds"); } if (rhs >= 0) { return elements[rhs]; } else { return elements[num_rows() + rhs]; } } /* Element Getter and Setter: */ /* Changes the value of a given position in the Matrix. @param row the row that holds the value to change @param col the column of the value to change @param val the value to set */ void set(const int &row, const int &col, T const &val) { if (this->num_cols() > col && this->num_rows() > row) elements[row][col] = val; } /* Gets the value held at a certain position in the Matrix. @param row the row to read from @param col the column to read from @return the value of type T held at the positon row,col in the Matrix */ T get(const int &row, const int &col) { if (this->num_cols() > col && this->num_rows() > row) return elements[row][col]; else return 0; } /* Matrix Arithmetic Methods */ /* ADDITION: Binary operator to add two matrices together. Does not modify either matrix. @param other the Matrix on the right side of + @return a Matrix, whose elements are the sums of the corresponding elements of `this` and `other` */ Matrix<T> operator+(Matrix<T> &other) { // Matrices must be same dimensions to // be addable if (this->num_rows() != other.num_rows() || this->num_cols() != other.num_cols()) throw std::invalid_argument("these Matrices cannot be added/subtracted"); // make matrix based on `this` Matrix<T> resultant(*this); for (int i = 0, n = this->num_rows(); i < n; i++) { for (int j = 0, o = this->num_cols(); j < o; j++) { // set each value in the resultant equal // to the sum of the corresponding values // in `this` and `other` resultant.set(i, j, this->get(i, j) + other.get(i, j)); } } return resultant; } /* SUBTRACTION: Binary operator to subtract two matrices. Does not modify either matrix. @param other the Matrix on the right side of - @return a Matrix, whose elements are the differences of the corresponding elements of `this` and `other` */ Matrix<T> operator-(Matrix<T> &other) { return (*this) + (other * -1); } /* MATRIX*MATRIX MULTIPLICATION Binary operator to multiple two matrices. Does not modify either matrix. @param other the Matrix on the right side of * @return a Matrix, whose elements are the products of the corresponding elements of `this` and `other`, following the accepted way of multiplying matrices. */ Matrix<T> operator*(Matrix<T> &other) { Matrix<T> resultant(this->num_rows(), other.num_cols()); if (this->num_cols() != other.num_rows()) throw std::invalid_argument("these Matrices cannot be multiplied"); // go through all rows of the left Matrix for (int i = 0, n = this->num_rows(); i < n; i++) { // go through all columns of right Matrix for each row // of the left Matrix for (int j = 0, o = other.num_cols(); j < o; j++) { T tmp = 0; int x = 0; while (x < n) { tmp += (this->get(i, x) * other.get(x, j)); x++; } resultant.set(i, j, tmp); // put the tmp into the resultant } } return resultant; } /* MATRIX*SCALAR MULTIPLICATION Multiplies a Matrix by a scalar value. @param other the scalar value @return the result of scaling `this` by `other` */ Matrix<T> operator*(T &other) { Matrix<T> resultant(*this); for (int i = 0, n = this->num_rows(); i < n; i++) { for (int j = 0, o = this->num_cols(); j < o; j++) { resultant.elements[i][j] *= other; } } return resultant; } /* Matrix Power Method Powers >= 1 only! @param p an unsigned integer >= 1 to which the Matrix will be raised. @return the Matrix raised to the `p` power */ Matrix power(const unsigned int &p) { if (p == 1) return *this; else if (p <= 0) // set for now to keep it safe return *this; Matrix m(*this); m = m.power(p / 2); m = m * m; if (p % 2 == 1) m = m * (*this); return m; } /* Matrix Printer Formats the Matrix for STDOUT */ std::ostream& operator<<(std::ostream& out) { for (int i = 0, n = this.num_rows(); i < n; i++) { out << "| "; for (int j = 0, o = this.num_cols(); j < o; j++) { out << this.elements[i][j] << " "; } out << "|" << std::endl; } return out; } }; int main() { return 0; }<|endoftext|>
<commit_before>#include "MechanicsFwd.hpp" #include "NewtonEulerDS.hpp" #include "RigidBody2dDS.hpp" #include "SiconosContactor.hpp" RigidBody2dDS::RigidBody2dDS(SP::SiconosVector position, SP::SiconosVector velocity, SP::SiconosMatrix mass) : LagrangianLinearTIDS(position, velocity, mass) , _contactors(std::make_shared<SiconosContactorSet>()) , _useContactorInertia(true) , _allowSelfCollide(true) { // Check size of positions, velocities and mass matrix _scalarMass = mass->getValue(0,0); } RigidBody2dDS::RigidBody2dDS(SP::SiconosVector position, SP::SiconosVector velocity, double mass, double inertia) : LagrangianLinearTIDS(position, velocity, SP::SimpleMatrix(new SimpleMatrix(3,3))) ,_scalarMass(mass) , _contactors(std::make_shared<SiconosContactorSet>()) , _useContactorInertia(true) , _allowSelfCollide(true) { _mass->setValue(0,0,mass); _mass->setValue(1,1,mass); _mass->setValue(2,2,inertia); // Check size of positions, velocities and mass matrix } RigidBody2dDS::~RigidBody2dDS() { } <commit_msg>[mechanics] check size of position and velocity<commit_after>#include "MechanicsFwd.hpp" #include "NewtonEulerDS.hpp" #include "RigidBody2dDS.hpp" #include "SiconosContactor.hpp" RigidBody2dDS::RigidBody2dDS(SP::SiconosVector position, SP::SiconosVector velocity, SP::SiconosMatrix mass) : LagrangianLinearTIDS(position, velocity, mass) , _contactors(std::make_shared<SiconosContactorSet>()) , _useContactorInertia(true) , _allowSelfCollide(true) { // Check size of positions, velocities and mass matrix if((position->size() !=3) or (velocity->size() !=3)) { THROW_EXCEPTION("RigidBody2dDS::RigidBody2dDS(...). The size of position and velocity must of size 3"); } _scalarMass = mass->getValue(0,0); } RigidBody2dDS::RigidBody2dDS(SP::SiconosVector position, SP::SiconosVector velocity, double mass, double inertia) : LagrangianLinearTIDS(position, velocity, SP::SimpleMatrix(new SimpleMatrix(3,3))) ,_scalarMass(mass) , _contactors(std::make_shared<SiconosContactorSet>()) , _useContactorInertia(true) , _allowSelfCollide(true) { _mass->setValue(0,0,mass); _mass->setValue(1,1,mass); _mass->setValue(2,2,inertia); // Check size of positions, velocities and mass matrix if((position->size() !=3) or (velocity->size() !=3)) { THROW_EXCEPTION("RigidBody2dDS::RigidBody2dDS(...). The size of position and velocity must of size 3"); } } RigidBody2dDS::~RigidBody2dDS() { } <|endoftext|>
<commit_before>// // HttpRequestSystem.cpp // Chilli Source // Created by Scott Downie on 23/05/2011. // // The MIT License (MIT) // // Copyright (c) 2011 Tag Games Limited // // 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. // #ifdef CS_TARGETPLATFORM_WINDOWS #include <CSBackend/Platform/Windows/Networking/Http/HttpRequestSystem.h> #include <CSBackend/Platform/Windows/Core/String/WindowsStringUtils.h> #include <ChilliSource/Core/Base/Application.h> #include <ChilliSource/Core/Threading/TaskScheduler.h> #include <Windows.h> #include <winhttp.h> #pragma comment(lib, "winhttp") namespace CSBackend { namespace Windows { namespace { //-------------------------------------------------------------------------------------------------- /// Setup the request to use SSL level 3 /// /// @author S Downie /// /// @param Request handle /// /// @return Success or failure //-------------------------------------------------------------------------------------------------- bool ApplySSLSettings(HINTERNET in_requestHandle) { DWORD requestOptions = SECURITY_FLAG_IGNORE_CERT_CN_INVALID | SECURITY_FLAG_IGNORE_CERT_DATE_INVALID | SECURITY_FLAG_IGNORE_UNKNOWN_CA | SECURITY_FLAG_IGNORE_CERT_WRONG_USAGE; if (!WinHttpSetOption(in_requestHandle, WINHTTP_OPTION_SECURITY_FLAGS, &requestOptions, sizeof(DWORD))) { CS_LOG_ERROR("Failed to set HTTP SSL security flag options"); return false; } return true; } //-------------------------------------------------------------------------------------------------- /// Convert param dictionary to header format required by WinHTTP /// /// @author S Downie /// /// @param Header dictionary /// /// @return Header blob //-------------------------------------------------------------------------------------------------- std::wstring ConvertHeaders(const ChilliSource::ParamDictionary& in_headers) { //The headers must be passed as a single string with each header except the last //terminated by a carraige return/line feed std::string headerBlob; for (auto it = in_headers.begin(); it != in_headers.end(); ++it) { headerBlob += it->first; headerBlob += ": "; headerBlob += it->second; headerBlob += '\r'; headerBlob += '\n'; } CS_ASSERT(headerBlob.length() > 2, "Http: Cannot convert empty headers"); std::wstring headerBlobWide(headerBlob.length() - 2, L' '); std::copy(headerBlob.begin(), headerBlob.end()-2, headerBlobWide.begin()); return headerBlobWide; } } CS_DEFINE_NAMEDTYPE(HttpRequestSystem); //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- void HttpRequestSystem::OnInit() { m_sessionHandle = ::WinHttpOpen(L"CSWinHttpClient", WINHTTP_ACCESS_TYPE_NO_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0); CS_ASSERT(m_sessionHandle != nullptr, "Failed to open WinHTTP session"); } //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- bool HttpRequestSystem::IsA(ChilliSource::InterfaceIDType in_interfaceId) const { return in_interfaceId == ChilliSource::HttpRequestSystem::InterfaceID || in_interfaceId == HttpRequestSystem::InterfaceID; } //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- HttpRequest* HttpRequestSystem::MakeGetRequest(const std::string& in_url, const HttpRequest::Delegate& in_delegate, u32 in_timeoutSecs) { return MakeRequest(HttpRequest::Type::k_get, in_url, "", ChilliSource::ParamDictionary(), in_delegate, in_timeoutSecs); } //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- HttpRequest* HttpRequestSystem::MakeGetRequest(const std::string& in_url, const ChilliSource::ParamDictionary& in_headers, const HttpRequest::Delegate& in_delegate, u32 in_timeoutSecs) { return MakeRequest(HttpRequest::Type::k_get, in_url, "", in_headers, in_delegate, in_timeoutSecs); } //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- HttpRequest* HttpRequestSystem::MakePostRequest(const std::string& in_url, const std::string& in_body, const HttpRequest::Delegate& in_delegate, u32 in_timeoutSecs) { return MakeRequest(HttpRequest::Type::k_post, in_url, in_body, ChilliSource::ParamDictionary(), in_delegate, in_timeoutSecs); } //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- HttpRequest* HttpRequestSystem::MakePostRequest(const std::string& in_url, const std::string& in_body, const ChilliSource::ParamDictionary& in_headers, const HttpRequest::Delegate& in_delegate, u32 in_timeoutSecs) { return MakeRequest(HttpRequest::Type::k_post, in_url, in_body, in_headers, in_delegate, in_timeoutSecs); } //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- HttpRequest* HttpRequestSystem::MakeRequest(HttpRequest::Type in_type, const std::string& in_url, const std::string& in_body, const ChilliSource::ParamDictionary& in_headers, const HttpRequest::Delegate& in_delegate, u32 in_timeoutSecs) { CS_ASSERT(ChilliSource::Application::Get()->GetTaskScheduler()->IsMainThread() == true, "Http requests can currently only be made on the main thread"); CS_ASSERT(in_delegate != nullptr, "Cannot make an http request with a null delegate"); CS_ASSERT(in_url.empty() == false, "Cannot make an http request to a blank url"); URL_COMPONENTS urlComps; //Initialize the URL_COMPONENTS structure. ZeroMemory(&urlComps, sizeof(URL_COMPONENTS)); urlComps.dwStructSize = sizeof(URL_COMPONENTS); //Set required component lengths to non-zero so that they are cracked. urlComps.dwSchemeLength = (DWORD)-1; urlComps.dwHostNameLength = (DWORD)-1; urlComps.dwUrlPathLength = (DWORD)-1; urlComps.dwExtraInfoLength = (DWORD)-1; //Change the URL to wide string std::wstring url(WindowsStringUtils::UTF8ToUTF16(in_url)); //Crack the URL. if (!WinHttpCrackUrl(url.c_str(), (DWORD)url.length(), 0, &urlComps)) { CS_LOG_FATAL("Cannot crack URL: " + in_url); return nullptr; } //Weirdly the cracked URL struct only gives you the ability to crack your own URL std::wstring hostName = urlComps.lpszHostName; hostName = hostName.substr(0, urlComps.dwHostNameLength); HINTERNET connectionHandle = ::WinHttpConnect(m_sessionHandle, hostName.c_str(), INTERNET_DEFAULT_PORT, 0); if (!connectionHandle) { CS_LOG_ERROR("Failed to connect to server: " + in_url); return nullptr; } //Set up the request based on whether it is POST or GET and whether it is SSL LPCWSTR type = (in_type == ChilliSource::HttpRequest::Type::k_get ? L"GET" : L"POST"); HINTERNET requestHandle = 0; std::wstring urlPath = urlComps.lpszUrlPath; urlPath = urlPath.substr(0, urlComps.dwUrlPathLength); if (urlComps.nScheme == INTERNET_SCHEME_HTTPS) { requestHandle = ::WinHttpOpenRequest(connectionHandle, type, urlPath.c_str(), L"HTTP/1.1", WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, WINHTTP_FLAG_SECURE); if (requestHandle == nullptr || ApplySSLSettings(requestHandle) == false) { CS_LOG_ERROR("Failed to open request: " + in_url); WinHttpCloseHandle(connectionHandle); return nullptr; } } else { requestHandle = ::WinHttpOpenRequest(connectionHandle, type, urlPath.c_str(), L"HTTP/1.1", WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, 0); if (requestHandle == nullptr) { CS_LOG_ERROR("Failed to open request: " + in_url); WinHttpCloseHandle(connectionHandle); return nullptr; } } if (in_headers.empty() == false) { std::wstring headerBlob = ConvertHeaders(in_headers); if (WinHttpAddRequestHeaders(requestHandle, headerBlob.c_str(), DWORD(headerBlob.length()), WINHTTP_ADDREQ_FLAG_ADD) == false) { CS_LOG_ERROR("Failed to add http headers: " + in_url); WinHttpCloseHandle(requestHandle); WinHttpCloseHandle(connectionHandle); return nullptr; } } HttpRequest* httpRequest = new HttpRequest(in_type, in_url, in_body, in_headers, in_timeoutSecs, requestHandle, connectionHandle, GetMaxBufferSize(), in_delegate); m_requests.push_back(httpRequest); return httpRequest; } //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- void HttpRequestSystem::CancelAllRequests() { CS_ASSERT(ChilliSource::Application::Get()->GetTaskScheduler()->IsMainThread() == true, "Http requests can currently only be made on the main thread"); for(u32 nRequest=0; nRequest<m_requests.size(); ++nRequest) { m_requests[nRequest]->Cancel(); } } //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- void HttpRequestSystem::CheckReachability(const ReachabilityResultDelegate& in_reachabilityDelegate) const { //TODO: Implement this functionality CS_ASSERT(in_reachabilityDelegate, "The reachability delegate should not be null."); in_reachabilityDelegate(true); } //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- void HttpRequestSystem::OnUpdate(f32 in_timeSinceLastUpdate) { //We should do this in two loops incase anyone tries to insert into the requests from the completion callback for (u32 i=0; i<m_requests.size(); ++i) { m_requests[i]->Update(in_timeSinceLastUpdate); } for (auto it = m_requests.begin(); it != m_requests.end(); /*No increment*/) { if((*it)->HasCompleted()) { //...and remove the completed request CS_SAFEDELETE(*it); it = m_requests.erase(it); } else { ++it; } } } //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- void HttpRequestSystem::OnDestroy() { CancelAllRequests(); HttpRequest::Shutdown(); for (auto it = m_requests.begin(); it != m_requests.end(); ++it) { CS_SAFEDELETE(*it); } m_requests.clear(); m_requests.shrink_to_fit(); WinHttpCloseHandle(m_sessionHandle); } } } #endif <commit_msg>Network reachability for Windows.<commit_after>// // HttpRequestSystem.cpp // Chilli Source // Created by Scott Downie on 23/05/2011. // // The MIT License (MIT) // // Copyright (c) 2011 Tag Games Limited // // 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. // #ifdef CS_TARGETPLATFORM_WINDOWS #include <CSBackend/Platform/Windows/Networking/Http/HttpRequestSystem.h> #include <CSBackend/Platform/Windows/Core/String/WindowsStringUtils.h> #include <ChilliSource/Core/Base/Application.h> #include <ChilliSource/Core/Threading/TaskScheduler.h> #include <Windows.h> // Have to wrap WinInet's include in a namespace, because MS violates ODR with WinInet and WinHTTP. namespace WinInet { #include <WinInet.h> } // A couple of undefs required too. #undef BOOLAPI #undef SECURITY_FLAG_IGNORE_CERT_DATE_INVALID #undef SECURITY_FLAG_IGNORE_CERT_CN_INVALID #include <winhttp.h> #pragma comment(lib, "winhttp") #pragma comment(lib, "wininet") namespace CSBackend { namespace Windows { namespace { //-------------------------------------------------------------------------------------------------- /// Setup the request to use SSL level 3 /// /// @author S Downie /// /// @param Request handle /// /// @return Success or failure //-------------------------------------------------------------------------------------------------- bool ApplySSLSettings(HINTERNET in_requestHandle) { DWORD requestOptions = SECURITY_FLAG_IGNORE_CERT_CN_INVALID | SECURITY_FLAG_IGNORE_CERT_DATE_INVALID | SECURITY_FLAG_IGNORE_UNKNOWN_CA | SECURITY_FLAG_IGNORE_CERT_WRONG_USAGE; if (!WinHttpSetOption(in_requestHandle, WINHTTP_OPTION_SECURITY_FLAGS, &requestOptions, sizeof(DWORD))) { CS_LOG_ERROR("Failed to set HTTP SSL security flag options"); return false; } return true; } //-------------------------------------------------------------------------------------------------- /// Convert param dictionary to header format required by WinHTTP /// /// @author S Downie /// /// @param Header dictionary /// /// @return Header blob //-------------------------------------------------------------------------------------------------- std::wstring ConvertHeaders(const ChilliSource::ParamDictionary& in_headers) { //The headers must be passed as a single string with each header except the last //terminated by a carraige return/line feed std::string headerBlob; for (auto it = in_headers.begin(); it != in_headers.end(); ++it) { headerBlob += it->first; headerBlob += ": "; headerBlob += it->second; headerBlob += '\r'; headerBlob += '\n'; } CS_ASSERT(headerBlob.length() > 2, "Http: Cannot convert empty headers"); std::wstring headerBlobWide(headerBlob.length() - 2, L' '); std::copy(headerBlob.begin(), headerBlob.end()-2, headerBlobWide.begin()); return headerBlobWide; } } CS_DEFINE_NAMEDTYPE(HttpRequestSystem); //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- void HttpRequestSystem::OnInit() { m_sessionHandle = ::WinHttpOpen(L"CSWinHttpClient", WINHTTP_ACCESS_TYPE_NO_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0); CS_ASSERT(m_sessionHandle != nullptr, "Failed to open WinHTTP session"); } //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- bool HttpRequestSystem::IsA(ChilliSource::InterfaceIDType in_interfaceId) const { return in_interfaceId == ChilliSource::HttpRequestSystem::InterfaceID || in_interfaceId == HttpRequestSystem::InterfaceID; } //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- HttpRequest* HttpRequestSystem::MakeGetRequest(const std::string& in_url, const HttpRequest::Delegate& in_delegate, u32 in_timeoutSecs) { return MakeRequest(HttpRequest::Type::k_get, in_url, "", ChilliSource::ParamDictionary(), in_delegate, in_timeoutSecs); } //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- HttpRequest* HttpRequestSystem::MakeGetRequest(const std::string& in_url, const ChilliSource::ParamDictionary& in_headers, const HttpRequest::Delegate& in_delegate, u32 in_timeoutSecs) { return MakeRequest(HttpRequest::Type::k_get, in_url, "", in_headers, in_delegate, in_timeoutSecs); } //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- HttpRequest* HttpRequestSystem::MakePostRequest(const std::string& in_url, const std::string& in_body, const HttpRequest::Delegate& in_delegate, u32 in_timeoutSecs) { return MakeRequest(HttpRequest::Type::k_post, in_url, in_body, ChilliSource::ParamDictionary(), in_delegate, in_timeoutSecs); } //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- HttpRequest* HttpRequestSystem::MakePostRequest(const std::string& in_url, const std::string& in_body, const ChilliSource::ParamDictionary& in_headers, const HttpRequest::Delegate& in_delegate, u32 in_timeoutSecs) { return MakeRequest(HttpRequest::Type::k_post, in_url, in_body, in_headers, in_delegate, in_timeoutSecs); } //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- HttpRequest* HttpRequestSystem::MakeRequest(HttpRequest::Type in_type, const std::string& in_url, const std::string& in_body, const ChilliSource::ParamDictionary& in_headers, const HttpRequest::Delegate& in_delegate, u32 in_timeoutSecs) { CS_ASSERT(ChilliSource::Application::Get()->GetTaskScheduler()->IsMainThread() == true, "Http requests can currently only be made on the main thread"); CS_ASSERT(in_delegate != nullptr, "Cannot make an http request with a null delegate"); CS_ASSERT(in_url.empty() == false, "Cannot make an http request to a blank url"); URL_COMPONENTS urlComps; //Initialize the URL_COMPONENTS structure. ZeroMemory(&urlComps, sizeof(URL_COMPONENTS)); urlComps.dwStructSize = sizeof(URL_COMPONENTS); //Set required component lengths to non-zero so that they are cracked. urlComps.dwSchemeLength = (DWORD)-1; urlComps.dwHostNameLength = (DWORD)-1; urlComps.dwUrlPathLength = (DWORD)-1; urlComps.dwExtraInfoLength = (DWORD)-1; //Change the URL to wide string std::wstring url(WindowsStringUtils::UTF8ToUTF16(in_url)); //Crack the URL. if (!WinHttpCrackUrl(url.c_str(), (DWORD)url.length(), 0, &urlComps)) { CS_LOG_FATAL("Cannot crack URL: " + in_url); return nullptr; } //Weirdly the cracked URL struct only gives you the ability to crack your own URL std::wstring hostName = urlComps.lpszHostName; hostName = hostName.substr(0, urlComps.dwHostNameLength); HINTERNET connectionHandle = ::WinHttpConnect(m_sessionHandle, hostName.c_str(), INTERNET_DEFAULT_PORT, 0); if (!connectionHandle) { CS_LOG_ERROR("Failed to connect to server: " + in_url); return nullptr; } //Set up the request based on whether it is POST or GET and whether it is SSL LPCWSTR type = (in_type == ChilliSource::HttpRequest::Type::k_get ? L"GET" : L"POST"); HINTERNET requestHandle = 0; std::wstring urlPath = urlComps.lpszUrlPath; urlPath = urlPath.substr(0, urlComps.dwUrlPathLength); if (urlComps.nScheme == INTERNET_SCHEME_HTTPS) { requestHandle = ::WinHttpOpenRequest(connectionHandle, type, urlPath.c_str(), L"HTTP/1.1", WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, WINHTTP_FLAG_SECURE); if (requestHandle == nullptr || ApplySSLSettings(requestHandle) == false) { CS_LOG_ERROR("Failed to open request: " + in_url); WinHttpCloseHandle(connectionHandle); return nullptr; } } else { requestHandle = ::WinHttpOpenRequest(connectionHandle, type, urlPath.c_str(), L"HTTP/1.1", WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, 0); if (requestHandle == nullptr) { CS_LOG_ERROR("Failed to open request: " + in_url); WinHttpCloseHandle(connectionHandle); return nullptr; } } if (in_headers.empty() == false) { std::wstring headerBlob = ConvertHeaders(in_headers); if (WinHttpAddRequestHeaders(requestHandle, headerBlob.c_str(), DWORD(headerBlob.length()), WINHTTP_ADDREQ_FLAG_ADD) == false) { CS_LOG_ERROR("Failed to add http headers: " + in_url); WinHttpCloseHandle(requestHandle); WinHttpCloseHandle(connectionHandle); return nullptr; } } HttpRequest* httpRequest = new HttpRequest(in_type, in_url, in_body, in_headers, in_timeoutSecs, requestHandle, connectionHandle, GetMaxBufferSize(), in_delegate); m_requests.push_back(httpRequest); return httpRequest; } //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- void HttpRequestSystem::CancelAllRequests() { CS_ASSERT(ChilliSource::Application::Get()->GetTaskScheduler()->IsMainThread() == true, "Http requests can currently only be made on the main thread"); for(u32 nRequest=0; nRequest<m_requests.size(); ++nRequest) { m_requests[nRequest]->Cancel(); } } //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- void HttpRequestSystem::CheckReachability(const ReachabilityResultDelegate& in_reachabilityDelegate) const { // Check internet connectivity/reachability, using WinINet. DWORD inetState = 0; BOOL hasConnection = WinInet::InternetGetConnectedState(&inetState, 0); // True is returned when the device has an active connection to the internet, or a correctly-configured proxy connection. // False is returned when the device has no connection to the internet, even if successfully connected to LAN. // More information about the connection can be obtained from the 'inetState' flag. CS_ASSERT(in_reachabilityDelegate, "The reachability delegate should not be null."); in_reachabilityDelegate(hasConnection ? true : false); //ternary operator used here because BOOL is a typedef'd int & conversion has perf issues } //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- void HttpRequestSystem::OnUpdate(f32 in_timeSinceLastUpdate) { //We should do this in two loops incase anyone tries to insert into the requests from the completion callback for (u32 i=0; i<m_requests.size(); ++i) { m_requests[i]->Update(in_timeSinceLastUpdate); } for (auto it = m_requests.begin(); it != m_requests.end(); /*No increment*/) { if((*it)->HasCompleted()) { //...and remove the completed request CS_SAFEDELETE(*it); it = m_requests.erase(it); } else { ++it; } } } //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- void HttpRequestSystem::OnDestroy() { CancelAllRequests(); HttpRequest::Shutdown(); for (auto it = m_requests.begin(); it != m_requests.end(); ++it) { CS_SAFEDELETE(*it); } m_requests.clear(); m_requests.shrink_to_fit(); WinHttpCloseHandle(m_sessionHandle); } } } #endif <|endoftext|>
<commit_before>// Copyright (c) 2013 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/component_updater/widevine_cdm_component_installer.h" #include <string.h> #include <vector> #include "base/base_paths.h" #include "base/bind.h" #include "base/command_line.h" #include "base/compiler_specific.h" #include "base/file_util.h" #include "base/files/file_enumerator.h" #include "base/files/file_path.h" #include "base/logging.h" #include "base/path_service.h" #include "base/strings/string_util.h" #include "base/values.h" #include "base/version.h" #include "build/build_config.h" #include "chrome/browser/component_updater/component_updater_service.h" #include "chrome/browser/plugins/plugin_prefs.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/widevine_cdm_constants.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/plugin_service.h" #include "content/public/common/pepper_plugin_info.h" #include "third_party/widevine/cdm/widevine_cdm_common.h" #include "widevine_cdm_version.h" // In SHARED_INTERMEDIATE_DIR. using content::BrowserThread; using content::PluginService; namespace { // TODO(xhwang): Move duplicate code among all component installer // implementations to some common place. #if defined(WIDEVINE_CDM_AVAILABLE) && defined(WIDEVINE_CDM_IS_COMPONENT) // CRX hash. The extension id is: pdkaonnflpjcgibpgaanildgengnihcm. const uint8 kSha2Hash[] = { 0xf3, 0xa0, 0xed, 0xd5, 0xbf, 0x92, 0x68, 0x1f, 0x60, 0x0d, 0x8b, 0x36, 0x4d, 0x6d, 0x87, 0x2c, 0x86, 0x61, 0x12, 0x20, 0x21, 0xf8, 0x94, 0xdd, 0xe1, 0xb6, 0xb4, 0x55, 0x34, 0x8c, 0x2e, 0x20 }; // File name of the Widevine CDM component manifest on different platforms. const char kWidevineCdmManifestName[] = "WidevineCdm"; // Name of the Widevine CDM OS in the component manifest. const char kWidevineCdmOperatingSystem[] = #if defined(OS_MACOSX) "mac"; #elif defined(OS_WIN) "win"; #else // OS_LINUX, etc. TODO(viettrungluu): Separate out Chrome OS and Android? "linux"; #endif // Name of the Widevine CDM architecture in the component manifest. const char kWidevineCdmArch[] = #if defined(ARCH_CPU_X86) "ia32"; #elif defined(ARCH_CPU_X86_64) "x64"; #else // TODO(viettrungluu): Support an ARM check? "???"; #endif // If we don't have a Widevine CDM component, this is the version we claim. const char kNullVersion[] = "0.0.0.0"; // The base directory on Windows looks like: // <profile>\AppData\Local\Google\Chrome\User Data\WidevineCdm\. base::FilePath GetWidevineCdmBaseDirectory() { base::FilePath result; PathService::Get(chrome::DIR_COMPONENT_WIDEVINE_CDM, &result); return result; } // Widevine CDM has the version encoded in the path so we need to enumerate the // directories to find the full path. // On success, |latest_dir| returns something like: // <profile>\AppData\Local\Google\Chrome\User Data\WidevineCdm\10.3.44.555\. // |latest_version| returns the corresponding version number. |older_dirs| // returns directories of all older versions. bool GetWidevineCdmDirectory(base::FilePath* latest_dir, base::Version* latest_version, std::vector<base::FilePath>* older_dirs) { base::FilePath base_dir = GetWidevineCdmBaseDirectory(); bool found = false; base::FileEnumerator file_enumerator( base_dir, false, base::FileEnumerator::DIRECTORIES); for (base::FilePath path = file_enumerator.Next(); !path.value().empty(); path = file_enumerator.Next()) { base::Version version(path.BaseName().MaybeAsASCII()); if (!version.IsValid()) continue; if (found) { if (version.CompareTo(*latest_version) > 0) { older_dirs->push_back(*latest_dir); *latest_dir = path; *latest_version = version; } else { older_dirs->push_back(path); } } else { *latest_dir = path; *latest_version = version; found = true; } } return found; } bool MakeWidevineCdmPluginInfo(const base::FilePath& path, const base::Version& version, content::PepperPluginInfo* plugin_info) { if (!version.IsValid() || version.components().size() != static_cast<size_t>(kWidevineCdmVersionNumComponents)) { return false; } plugin_info->is_internal = false; // Widevine CDM must run out of process. plugin_info->is_out_of_process = true; plugin_info->path = path; plugin_info->name = kWidevineCdmDisplayName; plugin_info->description = kWidevineCdmDescription; plugin_info->version = version.GetString(); webkit::WebPluginMimeType widevine_cdm_mime_type( kWidevineCdmPluginMimeType, kWidevineCdmPluginExtension, kWidevineCdmPluginMimeTypeDescription); plugin_info->mime_types.push_back(widevine_cdm_mime_type); plugin_info->permissions = kWidevineCdmPluginPermissions; return true; } void RegisterWidevineCdmWithChrome(const base::FilePath& path, const base::Version& version) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); content::PepperPluginInfo plugin_info; if (!MakeWidevineCdmPluginInfo(path, version, &plugin_info)) return; PluginService::GetInstance()->RegisterInternalPlugin( plugin_info.ToWebPluginInfo(), true); PluginService::GetInstance()->RefreshPlugins(); } // Returns true if this browser is compatible with the given Widevine CDM // manifest, with the version specified in the manifest in |version_out|. bool CheckWidevineCdmManifest(const base::DictionaryValue& manifest, base::Version* version_out) { std::string name; manifest.GetStringASCII("name", &name); if (name != kWidevineCdmManifestName) return false; std::string proposed_version; manifest.GetStringASCII("version", &proposed_version); base::Version version(proposed_version.c_str()); if (!version.IsValid()) return false; std::string os; manifest.GetStringASCII("x-widevine-cdm-os", &os); if (os != kWidevineCdmOperatingSystem) return false; std::string arch; manifest.GetStringASCII("x-widevine-cdm-arch", &arch); if (arch != kWidevineCdmArch) return false; *version_out = version; return true; } class WidevineCdmComponentInstaller : public ComponentInstaller { public: explicit WidevineCdmComponentInstaller(const base::Version& version); virtual ~WidevineCdmComponentInstaller() {} virtual void OnUpdateError(int error) OVERRIDE; virtual bool Install(const base::DictionaryValue& manifest, const base::FilePath& unpack_path) OVERRIDE; virtual bool GetInstalledFile(const std::string& file, base::FilePath* installed_file) OVERRIDE; private: base::Version current_version_; }; WidevineCdmComponentInstaller::WidevineCdmComponentInstaller( const base::Version& version) : current_version_(version) { DCHECK(version.IsValid()); } void WidevineCdmComponentInstaller::OnUpdateError(int error) { NOTREACHED() << "Widevine CDM update error: " << error; } bool WidevineCdmComponentInstaller::Install( const base::DictionaryValue& manifest, const base::FilePath& unpack_path) { base::Version version; if (!CheckWidevineCdmManifest(manifest, &version)) return false; if (current_version_.CompareTo(version) > 0) return false; if (!file_util::PathExists(unpack_path.AppendASCII(kWidevineCdmFileName))) return false; base::FilePath adapter_source_path; PathService::Get(chrome::FILE_WIDEVINE_CDM_ADAPTER, &adapter_source_path); if (!file_util::PathExists(adapter_source_path)) return false; // Passed the basic tests. Time to install it. base::FilePath install_path = GetWidevineCdmBaseDirectory().AppendASCII(version.GetString()); if (file_util::PathExists(install_path)) return false; if (!file_util::Move(unpack_path, install_path)) return false; base::FilePath adapter_install_path = install_path.AppendASCII(kWidevineCdmAdapterFileName); if (!file_util::CopyFile(adapter_source_path, adapter_install_path)) return false; // Installation is done. Now register the Widevine CDM with chrome. current_version_ = version; BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, base::Bind( &RegisterWidevineCdmWithChrome, adapter_install_path, version)); return true; } bool WidevineCdmComponentInstaller::GetInstalledFile( const std::string& file, base::FilePath* installed_file) { return false; } void FinishWidevineCdmUpdateRegistration(ComponentUpdateService* cus, const base::Version& version) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); CrxComponent widevine_cdm; widevine_cdm.name = "WidevineCdm"; widevine_cdm.installer = new WidevineCdmComponentInstaller(version); widevine_cdm.version = version; widevine_cdm.pk_hash.assign(kSha2Hash, &kSha2Hash[sizeof(kSha2Hash)]); if (cus->RegisterComponent(widevine_cdm) != ComponentUpdateService::kOk) { NOTREACHED() << "Widevine CDM component registration failed."; return; } } void StartWidevineCdmUpdateRegistration(ComponentUpdateService* cus) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); base::FilePath base_dir = GetWidevineCdmBaseDirectory(); if (!file_util::PathExists(base_dir) && !file_util::CreateDirectory(base_dir)) { NOTREACHED() << "Could not create Widevine CDM directory."; return; } base::FilePath latest_dir; base::Version version(kNullVersion); std::vector<base::FilePath> older_dirs; if (GetWidevineCdmDirectory(&latest_dir, &version, &older_dirs)) { base::FilePath adapter_path = latest_dir.AppendASCII(kWidevineCdmAdapterFileName); base::FilePath cdm_path = latest_dir.AppendASCII(kWidevineCdmFileName); if (file_util::PathExists(adapter_path) && file_util::PathExists(cdm_path)) { BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&RegisterWidevineCdmWithChrome, adapter_path, version)); } else { file_util::Delete(latest_dir, true); version = base::Version(kNullVersion); } } BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&FinishWidevineCdmUpdateRegistration, cus, version)); // Remove older versions of Widevine CDM. for (std::vector<base::FilePath>::iterator iter = older_dirs.begin(); iter != older_dirs.end(); ++iter) { file_util::Delete(*iter, true); } } #endif // defined(WIDEVINE_CDM_AVAILABLE) && defined(WIDEVINE_CDM_IS_COMPONENT) } // namespace void RegisterWidevineCdmComponent(ComponentUpdateService* cus) { #if defined(WIDEVINE_CDM_AVAILABLE) && defined(WIDEVINE_CDM_IS_COMPONENT) BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE, base::Bind(&StartWidevineCdmUpdateRegistration, cus)); #endif // defined(WIDEVINE_CDM_AVAILABLE) && defined(WIDEVINE_CDM_IS_COMPONENT) } <commit_msg>Implement GetInstalledFile() in WidevineCdmComponentInstaller.<commit_after>// Copyright (c) 2013 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/component_updater/widevine_cdm_component_installer.h" #include <string.h> #include <vector> #include "base/base_paths.h" #include "base/bind.h" #include "base/command_line.h" #include "base/compiler_specific.h" #include "base/file_util.h" #include "base/files/file_enumerator.h" #include "base/files/file_path.h" #include "base/logging.h" #include "base/path_service.h" #include "base/strings/string_util.h" #include "base/values.h" #include "base/version.h" #include "build/build_config.h" #include "chrome/browser/component_updater/component_updater_service.h" #include "chrome/browser/plugins/plugin_prefs.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/widevine_cdm_constants.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/plugin_service.h" #include "content/public/common/pepper_plugin_info.h" #include "third_party/widevine/cdm/widevine_cdm_common.h" #include "widevine_cdm_version.h" // In SHARED_INTERMEDIATE_DIR. using content::BrowserThread; using content::PluginService; namespace { // TODO(xhwang): Move duplicate code among all component installer // implementations to some common place. #if defined(WIDEVINE_CDM_AVAILABLE) && defined(WIDEVINE_CDM_IS_COMPONENT) // CRX hash. The extension id is: pdkaonnflpjcgibpgaanildgengnihcm. const uint8 kSha2Hash[] = { 0xf3, 0xa0, 0xed, 0xd5, 0xbf, 0x92, 0x68, 0x1f, 0x60, 0x0d, 0x8b, 0x36, 0x4d, 0x6d, 0x87, 0x2c, 0x86, 0x61, 0x12, 0x20, 0x21, 0xf8, 0x94, 0xdd, 0xe1, 0xb6, 0xb4, 0x55, 0x34, 0x8c, 0x2e, 0x20 }; // File name of the Widevine CDM component manifest on different platforms. const char kWidevineCdmManifestName[] = "WidevineCdm"; // Name of the Widevine CDM OS in the component manifest. const char kWidevineCdmOperatingSystem[] = #if defined(OS_MACOSX) "mac"; #elif defined(OS_WIN) "win"; #else // OS_LINUX, etc. TODO(viettrungluu): Separate out Chrome OS and Android? "linux"; #endif // Name of the Widevine CDM architecture in the component manifest. const char kWidevineCdmArch[] = #if defined(ARCH_CPU_X86) "ia32"; #elif defined(ARCH_CPU_X86_64) "x64"; #else // TODO(viettrungluu): Support an ARM check? "???"; #endif // If we don't have a Widevine CDM component, this is the version we claim. const char kNullVersion[] = "0.0.0.0"; // The base directory on Windows looks like: // <profile>\AppData\Local\Google\Chrome\User Data\WidevineCdm\. base::FilePath GetWidevineCdmBaseDirectory() { base::FilePath result; PathService::Get(chrome::DIR_COMPONENT_WIDEVINE_CDM, &result); return result; } // Widevine CDM has the version encoded in the path so we need to enumerate the // directories to find the full path. // On success, |latest_dir| returns something like: // <profile>\AppData\Local\Google\Chrome\User Data\WidevineCdm\10.3.44.555\. // |latest_version| returns the corresponding version number. |older_dirs| // returns directories of all older versions. bool GetWidevineCdmDirectory(base::FilePath* latest_dir, base::Version* latest_version, std::vector<base::FilePath>* older_dirs) { base::FilePath base_dir = GetWidevineCdmBaseDirectory(); bool found = false; base::FileEnumerator file_enumerator( base_dir, false, base::FileEnumerator::DIRECTORIES); for (base::FilePath path = file_enumerator.Next(); !path.value().empty(); path = file_enumerator.Next()) { base::Version version(path.BaseName().MaybeAsASCII()); if (!version.IsValid()) continue; if (found) { if (version.CompareTo(*latest_version) > 0) { older_dirs->push_back(*latest_dir); *latest_dir = path; *latest_version = version; } else { older_dirs->push_back(path); } } else { *latest_dir = path; *latest_version = version; found = true; } } return found; } bool MakeWidevineCdmPluginInfo(const base::FilePath& path, const base::Version& version, content::PepperPluginInfo* plugin_info) { if (!version.IsValid() || version.components().size() != static_cast<size_t>(kWidevineCdmVersionNumComponents)) { return false; } plugin_info->is_internal = false; // Widevine CDM must run out of process. plugin_info->is_out_of_process = true; plugin_info->path = path; plugin_info->name = kWidevineCdmDisplayName; plugin_info->description = kWidevineCdmDescription; plugin_info->version = version.GetString(); webkit::WebPluginMimeType widevine_cdm_mime_type( kWidevineCdmPluginMimeType, kWidevineCdmPluginExtension, kWidevineCdmPluginMimeTypeDescription); plugin_info->mime_types.push_back(widevine_cdm_mime_type); plugin_info->permissions = kWidevineCdmPluginPermissions; return true; } void RegisterWidevineCdmWithChrome(const base::FilePath& path, const base::Version& version) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); content::PepperPluginInfo plugin_info; if (!MakeWidevineCdmPluginInfo(path, version, &plugin_info)) return; PluginService::GetInstance()->RegisterInternalPlugin( plugin_info.ToWebPluginInfo(), true); PluginService::GetInstance()->RefreshPlugins(); } // Returns true if this browser is compatible with the given Widevine CDM // manifest, with the version specified in the manifest in |version_out|. bool CheckWidevineCdmManifest(const base::DictionaryValue& manifest, base::Version* version_out) { std::string name; manifest.GetStringASCII("name", &name); if (name != kWidevineCdmManifestName) return false; std::string proposed_version; manifest.GetStringASCII("version", &proposed_version); base::Version version(proposed_version.c_str()); if (!version.IsValid()) return false; std::string os; manifest.GetStringASCII("x-widevine-cdm-os", &os); if (os != kWidevineCdmOperatingSystem) return false; std::string arch; manifest.GetStringASCII("x-widevine-cdm-arch", &arch); if (arch != kWidevineCdmArch) return false; *version_out = version; return true; } class WidevineCdmComponentInstaller : public ComponentInstaller { public: explicit WidevineCdmComponentInstaller(const base::Version& version); virtual ~WidevineCdmComponentInstaller() {} virtual void OnUpdateError(int error) OVERRIDE; virtual bool Install(const base::DictionaryValue& manifest, const base::FilePath& unpack_path) OVERRIDE; virtual bool GetInstalledFile(const std::string& file, base::FilePath* installed_file) OVERRIDE; private: base::Version current_version_; }; WidevineCdmComponentInstaller::WidevineCdmComponentInstaller( const base::Version& version) : current_version_(version) { DCHECK(version.IsValid()); } void WidevineCdmComponentInstaller::OnUpdateError(int error) { NOTREACHED() << "Widevine CDM update error: " << error; } bool WidevineCdmComponentInstaller::Install( const base::DictionaryValue& manifest, const base::FilePath& unpack_path) { base::Version version; if (!CheckWidevineCdmManifest(manifest, &version)) return false; if (current_version_.CompareTo(version) > 0) return false; if (!file_util::PathExists(unpack_path.AppendASCII(kWidevineCdmFileName))) return false; base::FilePath adapter_source_path; PathService::Get(chrome::FILE_WIDEVINE_CDM_ADAPTER, &adapter_source_path); if (!file_util::PathExists(adapter_source_path)) return false; // Passed the basic tests. Time to install it. base::FilePath install_path = GetWidevineCdmBaseDirectory().AppendASCII(version.GetString()); if (file_util::PathExists(install_path)) return false; if (!file_util::Move(unpack_path, install_path)) return false; base::FilePath adapter_install_path = install_path.AppendASCII(kWidevineCdmAdapterFileName); if (!file_util::CopyFile(adapter_source_path, adapter_install_path)) return false; // Installation is done. Now register the Widevine CDM with chrome. current_version_ = version; BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, base::Bind( &RegisterWidevineCdmWithChrome, adapter_install_path, version)); return true; } bool WidevineCdmComponentInstaller::GetInstalledFile( const std::string& file, base::FilePath* installed_file) { // Only the CDM is component-updated. if (file != kWidevineCdmFileName) return false; if (current_version_.Equals(base::Version(kNullVersion))) return false; // No CDM has been installed yet. *installed_file = GetWidevineCdmBaseDirectory().AppendASCII(current_version_.GetString()) .AppendASCII(kWidevineCdmFileName); return true; } void FinishWidevineCdmUpdateRegistration(ComponentUpdateService* cus, const base::Version& version) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); CrxComponent widevine_cdm; widevine_cdm.name = "WidevineCdm"; widevine_cdm.installer = new WidevineCdmComponentInstaller(version); widevine_cdm.version = version; widevine_cdm.pk_hash.assign(kSha2Hash, &kSha2Hash[sizeof(kSha2Hash)]); if (cus->RegisterComponent(widevine_cdm) != ComponentUpdateService::kOk) { NOTREACHED() << "Widevine CDM component registration failed."; return; } } void StartWidevineCdmUpdateRegistration(ComponentUpdateService* cus) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); base::FilePath base_dir = GetWidevineCdmBaseDirectory(); if (!file_util::PathExists(base_dir) && !file_util::CreateDirectory(base_dir)) { NOTREACHED() << "Could not create Widevine CDM directory."; return; } base::FilePath latest_dir; base::Version version(kNullVersion); std::vector<base::FilePath> older_dirs; if (GetWidevineCdmDirectory(&latest_dir, &version, &older_dirs)) { base::FilePath adapter_path = latest_dir.AppendASCII(kWidevineCdmAdapterFileName); base::FilePath cdm_path = latest_dir.AppendASCII(kWidevineCdmFileName); if (file_util::PathExists(adapter_path) && file_util::PathExists(cdm_path)) { BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&RegisterWidevineCdmWithChrome, adapter_path, version)); } else { file_util::Delete(latest_dir, true); version = base::Version(kNullVersion); } } BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&FinishWidevineCdmUpdateRegistration, cus, version)); // Remove older versions of Widevine CDM. for (std::vector<base::FilePath>::iterator iter = older_dirs.begin(); iter != older_dirs.end(); ++iter) { file_util::Delete(*iter, true); } } #endif // defined(WIDEVINE_CDM_AVAILABLE) && defined(WIDEVINE_CDM_IS_COMPONENT) } // namespace void RegisterWidevineCdmComponent(ComponentUpdateService* cus) { #if defined(WIDEVINE_CDM_AVAILABLE) && defined(WIDEVINE_CDM_IS_COMPONENT) BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE, base::Bind(&StartWidevineCdmUpdateRegistration, cus)); #endif // defined(WIDEVINE_CDM_AVAILABLE) && defined(WIDEVINE_CDM_IS_COMPONENT) } <|endoftext|>
<commit_before>// Copyright 2013 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/ui/ash/multi_user/multi_user_context_menu.h" #include "ash/multi_profile_uma.h" #include "ash/session_state_delegate.h" #include "ash/shell.h" #include "base/strings/utf_string_conversions.h" #include "chrome/app/chrome_command_ids.h" #include "chrome/browser/ui/ash/multi_user/multi_user_util.h" #include "chrome/browser/ui/ash/multi_user/multi_user_window_manager.h" #include "grit/generated_resources.h" #include "ui/aura/window.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/models/simple_menu_model.h" namespace { class MultiUserContextMenuChromeos : public ui::SimpleMenuModel, public ui::SimpleMenuModel::Delegate { public: explicit MultiUserContextMenuChromeos(aura::Window* window); virtual ~MultiUserContextMenuChromeos() {} // SimpleMenuModel::Delegate: virtual bool IsCommandIdChecked(int command_id) const OVERRIDE { return false; } virtual bool IsCommandIdEnabled(int command_id) const OVERRIDE { return true; } virtual bool GetAcceleratorForCommandId( int command_id, ui::Accelerator* accelerator) OVERRIDE { return false; } virtual void ExecuteCommand(int command_id, int event_flags) OVERRIDE; private: // The window for which this menu is. aura::Window* window_; DISALLOW_COPY_AND_ASSIGN(MultiUserContextMenuChromeos); }; MultiUserContextMenuChromeos::MultiUserContextMenuChromeos(aura::Window* window) : ui::SimpleMenuModel(this), window_(window) { } void MultiUserContextMenuChromeos::ExecuteCommand(int command_id, int event_flags) { switch (command_id) { case IDC_VISIT_DESKTOP_OF_LRU_USER_2: case IDC_VISIT_DESKTOP_OF_LRU_USER_3: { ash::MultiProfileUMA::RecordTeleportAction( ash::MultiProfileUMA::TELEPORT_WINDOW_CAPTION_MENU); // When running the multi user mode on Chrome OS, windows can "visit" // another user's desktop. const std::string& user_id = ash::Shell::GetInstance()->session_state_delegate()->GetUserID( IDC_VISIT_DESKTOP_OF_LRU_USER_2 == command_id ? 1 : 2); chrome::MultiUserWindowManager::GetInstance()->ShowWindowForUser( window_, user_id); return; } default: NOTREACHED(); } } } // namespace scoped_ptr<ui::MenuModel> CreateMultiUserContextMenu( aura::Window* window) { scoped_ptr<ui::MenuModel> model; ash::SessionStateDelegate* delegate = ash::Shell::GetInstance()->session_state_delegate(); int logged_in_users = delegate->NumberOfLoggedInUsers(); if (delegate && logged_in_users > 1) { // If this window is not owned, we don't show the menu addition. chrome::MultiUserWindowManager* manager = chrome::MultiUserWindowManager::GetInstance(); const std::string user_id = manager->GetWindowOwner(window); if (user_id.empty() || !window || manager->GetWindowOwner(window).empty()) return model.Pass(); MultiUserContextMenuChromeos* menu = new MultiUserContextMenuChromeos(window); model.reset(menu); for (int user_index = 1; user_index < logged_in_users; ++user_index) { menu->AddItem( user_index == 1 ? IDC_VISIT_DESKTOP_OF_LRU_USER_2 : IDC_VISIT_DESKTOP_OF_LRU_USER_3, l10n_util::GetStringFUTF16( IDS_VISIT_DESKTOP_OF_LRU_USER, delegate->GetUserDisplayName(user_index), base::ASCIIToUTF16(delegate->GetUserEmail(user_index)))); } } return model.Pass(); } <commit_msg>Move a null check before it's usage.<commit_after>// Copyright 2013 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/ui/ash/multi_user/multi_user_context_menu.h" #include "ash/multi_profile_uma.h" #include "ash/session_state_delegate.h" #include "ash/shell.h" #include "base/strings/utf_string_conversions.h" #include "chrome/app/chrome_command_ids.h" #include "chrome/browser/ui/ash/multi_user/multi_user_util.h" #include "chrome/browser/ui/ash/multi_user/multi_user_window_manager.h" #include "grit/generated_resources.h" #include "ui/aura/window.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/models/simple_menu_model.h" namespace { class MultiUserContextMenuChromeos : public ui::SimpleMenuModel, public ui::SimpleMenuModel::Delegate { public: explicit MultiUserContextMenuChromeos(aura::Window* window); virtual ~MultiUserContextMenuChromeos() {} // SimpleMenuModel::Delegate: virtual bool IsCommandIdChecked(int command_id) const OVERRIDE { return false; } virtual bool IsCommandIdEnabled(int command_id) const OVERRIDE { return true; } virtual bool GetAcceleratorForCommandId( int command_id, ui::Accelerator* accelerator) OVERRIDE { return false; } virtual void ExecuteCommand(int command_id, int event_flags) OVERRIDE; private: // The window for which this menu is. aura::Window* window_; DISALLOW_COPY_AND_ASSIGN(MultiUserContextMenuChromeos); }; MultiUserContextMenuChromeos::MultiUserContextMenuChromeos(aura::Window* window) : ui::SimpleMenuModel(this), window_(window) { } void MultiUserContextMenuChromeos::ExecuteCommand(int command_id, int event_flags) { switch (command_id) { case IDC_VISIT_DESKTOP_OF_LRU_USER_2: case IDC_VISIT_DESKTOP_OF_LRU_USER_3: { ash::MultiProfileUMA::RecordTeleportAction( ash::MultiProfileUMA::TELEPORT_WINDOW_CAPTION_MENU); // When running the multi user mode on Chrome OS, windows can "visit" // another user's desktop. const std::string& user_id = ash::Shell::GetInstance()->session_state_delegate()->GetUserID( IDC_VISIT_DESKTOP_OF_LRU_USER_2 == command_id ? 1 : 2); chrome::MultiUserWindowManager::GetInstance()->ShowWindowForUser( window_, user_id); return; } default: NOTREACHED(); } } } // namespace scoped_ptr<ui::MenuModel> CreateMultiUserContextMenu( aura::Window* window) { scoped_ptr<ui::MenuModel> model; ash::SessionStateDelegate* delegate = ash::Shell::GetInstance()->session_state_delegate(); if (!delegate) return model.Pass(); int logged_in_users = delegate->NumberOfLoggedInUsers(); if (logged_in_users > 1) { // If this window is not owned, we don't show the menu addition. chrome::MultiUserWindowManager* manager = chrome::MultiUserWindowManager::GetInstance(); const std::string user_id = manager->GetWindowOwner(window); if (user_id.empty() || !window || manager->GetWindowOwner(window).empty()) return model.Pass(); MultiUserContextMenuChromeos* menu = new MultiUserContextMenuChromeos(window); model.reset(menu); for (int user_index = 1; user_index < logged_in_users; ++user_index) { menu->AddItem( user_index == 1 ? IDC_VISIT_DESKTOP_OF_LRU_USER_2 : IDC_VISIT_DESKTOP_OF_LRU_USER_3, l10n_util::GetStringFUTF16( IDS_VISIT_DESKTOP_OF_LRU_USER, delegate->GetUserDisplayName(user_index), base::ASCIIToUTF16(delegate->GetUserEmail(user_index)))); } } return model.Pass(); } <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/webui/options/language_options_handler.h" #include <string> #include "base/memory/scoped_ptr.h" #include "base/values.h" #include "testing/gtest/include/gtest/gtest.h" #if defined(OS_CHROMEOS) #include "chrome/browser/chromeos/cros/cros_library.h" #include "chrome/browser/chromeos/cros/input_method_library.h" #include "chrome/browser/ui/webui/options/chromeos/cros_language_options_handler.h" #endif // defined(OS_CHROMEOS) #if defined(OS_CHROMEOS) static chromeos::InputMethodDescriptors CreateInputMethodDescriptors() { chromeos::InputMethodDescriptors descriptors; descriptors.push_back( chromeos::InputMethodDescriptor("xkb:us::eng", "USA", "us", "eng")); descriptors.push_back( chromeos::InputMethodDescriptor("xkb:fr::fra", "France", "fr", "fra")); descriptors.push_back( chromeos::InputMethodDescriptor("xkb:be::fra", "Belgium", "be", "fr")); descriptors.push_back( chromeos::InputMethodDescriptor("mozc", "Mozc (US keyboard layout)", "us", "ja")); return descriptors; } TEST(LanguageOptionsHandlerTest, GetInputMethodList) { // Use the stub libcros. The object will take care of the cleanup. chromeos::ScopedStubCrosEnabler stub_cros_enabler; // Reset the library implementation so it will be initialized // again. Otherwise, non-stub implementation can be reused, if it's // already initialized elsewhere, which results in a crash. chromeos::CrosLibrary::Get()->GetTestApi()->SetInputMethodLibrary(NULL, false); chromeos::InputMethodDescriptors descriptors = CreateInputMethodDescriptors(); scoped_ptr<ListValue> list( chromeos::CrosLanguageOptionsHandler::GetInputMethodList(descriptors)); ASSERT_EQ(4U, list->GetSize()); DictionaryValue* entry = NULL; DictionaryValue *language_code_set = NULL; std::string input_method_id; std::string display_name; std::string language_code; // As shown below, the list should be input method ids should appear in // the same order of the descriptors. ASSERT_TRUE(list->GetDictionary(0, &entry)); ASSERT_TRUE(entry->GetString("id", &input_method_id)); ASSERT_TRUE(entry->GetString("displayName", &display_name)); ASSERT_TRUE(entry->GetDictionary("languageCodeSet", &language_code_set)); EXPECT_EQ("xkb:us::eng", input_method_id); // Commented out as it depends on translation in generated_resources.grd // (i.e. makes the test fragile). // EXPECT_EQ("English (USA) keyboard layout", display_name); ASSERT_TRUE(language_code_set->HasKey("en-US")); ASSERT_TRUE(language_code_set->HasKey("id")); // From kExtraLanguages. ASSERT_TRUE(language_code_set->HasKey("fil")); // From kExtraLanguages. ASSERT_TRUE(list->GetDictionary(1, &entry)); ASSERT_TRUE(entry->GetString("id", &input_method_id)); ASSERT_TRUE(entry->GetString("displayName", &display_name)); ASSERT_TRUE(entry->GetDictionary("languageCodeSet", &language_code_set)); EXPECT_EQ("xkb:fr::fra", input_method_id); // Commented out. See above. // EXPECT_EQ("French keyboard layout", display_name); ASSERT_TRUE(language_code_set->HasKey("fr")); ASSERT_TRUE(list->GetDictionary(2, &entry)); ASSERT_TRUE(entry->GetString("id", &input_method_id)); ASSERT_TRUE(entry->GetString("displayName", &display_name)); ASSERT_TRUE(entry->GetDictionary("languageCodeSet", &language_code_set)); EXPECT_EQ("xkb:be::fra", input_method_id); // Commented out. See above. // EXPECT_EQ("Belgian keyboard layout", display_name); ASSERT_TRUE(language_code_set->HasKey("fr")); ASSERT_TRUE(list->GetDictionary(3, &entry)); ASSERT_TRUE(entry->GetString("id", &input_method_id)); ASSERT_TRUE(entry->GetString("displayName", &display_name)); ASSERT_TRUE(entry->GetDictionary("languageCodeSet", &language_code_set)); EXPECT_EQ("mozc", input_method_id); // Commented out. See above. // EXPECT_EQ("Japanese input method (for US keyboard)", display_name); ASSERT_TRUE(language_code_set->HasKey("ja")); } TEST(LanguageOptionsHandlerTest, GetLanguageList) { chromeos::InputMethodDescriptors descriptors = CreateInputMethodDescriptors(); scoped_ptr<ListValue> list( chromeos::CrosLanguageOptionsHandler::GetLanguageList(descriptors)); ASSERT_EQ(6U, list->GetSize()); DictionaryValue* entry = NULL; std::string language_code; std::string display_name; std::string native_display_name; // As shown below, the list should be sorted by the display names, // and these names should not have duplicates. ASSERT_TRUE(list->GetDictionary(0, &entry)); ASSERT_TRUE(entry->GetString("code", &language_code)); ASSERT_TRUE(entry->GetString("displayName", &display_name)); ASSERT_TRUE(entry->GetString("nativeDisplayName", &native_display_name)); EXPECT_EQ("en-US", language_code); EXPECT_EQ("English (United States)", display_name); EXPECT_EQ("English (United States)", native_display_name); // This comes from kExtraLanguages. ASSERT_TRUE(list->GetDictionary(1, &entry)); ASSERT_TRUE(entry->GetString("code", &language_code)); ASSERT_TRUE(entry->GetString("displayName", &display_name)); ASSERT_TRUE(entry->GetString("nativeDisplayName", &native_display_name)); EXPECT_EQ("fil", language_code); EXPECT_EQ("Filipino", display_name); EXPECT_EQ("Filipino", native_display_name); ASSERT_TRUE(list->GetDictionary(2, &entry)); ASSERT_TRUE(entry->GetString("code", &language_code)); ASSERT_TRUE(entry->GetString("displayName", &display_name)); ASSERT_TRUE(entry->GetString("nativeDisplayName", &native_display_name)); EXPECT_EQ("fr", language_code); EXPECT_EQ("French", display_name); EXPECT_EQ("fran\u00E7ais", native_display_name); // This comes from kExtraLanguages. ASSERT_TRUE(list->GetDictionary(3, &entry)); ASSERT_TRUE(entry->GetString("code", &language_code)); ASSERT_TRUE(entry->GetString("displayName", &display_name)); ASSERT_TRUE(entry->GetString("nativeDisplayName", &native_display_name)); EXPECT_EQ("id", language_code); EXPECT_EQ("Indonesian", display_name); EXPECT_EQ("Bahasa Indonesia", native_display_name); ASSERT_TRUE(list->GetDictionary(4, &entry)); ASSERT_TRUE(entry->GetString("code", &language_code)); ASSERT_TRUE(entry->GetString("displayName", &display_name)); ASSERT_TRUE(entry->GetString("nativeDisplayName", &native_display_name)); EXPECT_EQ("ja", language_code); EXPECT_EQ("Japanese", display_name); EXPECT_EQ("\u65E5\u672C\u8A9E", native_display_name); // This comes from kExtraLanguages. ASSERT_TRUE(list->GetDictionary(5, &entry)); ASSERT_TRUE(entry->GetString("code", &language_code)); ASSERT_TRUE(entry->GetString("displayName", &display_name)); ASSERT_TRUE(entry->GetString("nativeDisplayName", &native_display_name)); EXPECT_EQ("es-419", language_code); EXPECT_EQ("Spanish (Latin America)", display_name); EXPECT_EQ("espa\u00F1ol (Latinoam\u00E9rica y el Caribe)", native_display_name); } #endif // defined(OS_CHROMEOS) #if !defined(OS_MACOSX) TEST(LanguageOptionsHandlerTest, GetUILanguageCodeSet) { scoped_ptr<DictionaryValue> dictionary( LanguageOptionsHandler::GetUILanguageCodeSet()); EXPECT_TRUE(dictionary->HasKey("en-US")); // Note that we don't test a false case, as such an expectation will // fail when we add support for the language. // EXPECT_FALSE(dictionary->HasKey("no")); } #endif // !defined(OS_MACOSX) TEST(LanguageOptionsHandlerTest, GetSpellCheckLanguageCodeSet) { scoped_ptr<DictionaryValue> dictionary( LanguageOptionsHandler::GetSpellCheckLanguageCodeSet()); EXPECT_TRUE(dictionary->HasKey("en-US")); } <commit_msg>Fix the unit test expectations to handle Australia<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/webui/options/language_options_handler.h" #include <string> #include "base/memory/scoped_ptr.h" #include "base/values.h" #include "testing/gtest/include/gtest/gtest.h" #if defined(OS_CHROMEOS) #include "chrome/browser/chromeos/cros/cros_library.h" #include "chrome/browser/chromeos/cros/input_method_library.h" #include "chrome/browser/ui/webui/options/chromeos/cros_language_options_handler.h" #endif // defined(OS_CHROMEOS) #if defined(OS_CHROMEOS) static chromeos::InputMethodDescriptors CreateInputMethodDescriptors() { chromeos::InputMethodDescriptors descriptors; descriptors.push_back( chromeos::InputMethodDescriptor("xkb:us::eng", "USA", "us", "eng")); descriptors.push_back( chromeos::InputMethodDescriptor("xkb:fr::fra", "France", "fr", "fra")); descriptors.push_back( chromeos::InputMethodDescriptor("xkb:be::fra", "Belgium", "be", "fr")); descriptors.push_back( chromeos::InputMethodDescriptor("mozc", "Mozc (US keyboard layout)", "us", "ja")); return descriptors; } TEST(LanguageOptionsHandlerTest, GetInputMethodList) { // Use the stub libcros. The object will take care of the cleanup. chromeos::ScopedStubCrosEnabler stub_cros_enabler; // Reset the library implementation so it will be initialized // again. Otherwise, non-stub implementation can be reused, if it's // already initialized elsewhere, which results in a crash. chromeos::CrosLibrary::Get()->GetTestApi()->SetInputMethodLibrary(NULL, false); chromeos::InputMethodDescriptors descriptors = CreateInputMethodDescriptors(); scoped_ptr<ListValue> list( chromeos::CrosLanguageOptionsHandler::GetInputMethodList(descriptors)); ASSERT_EQ(4U, list->GetSize()); DictionaryValue* entry = NULL; DictionaryValue *language_code_set = NULL; std::string input_method_id; std::string display_name; std::string language_code; // As shown below, the list should be input method ids should appear in // the same order of the descriptors. ASSERT_TRUE(list->GetDictionary(0, &entry)); ASSERT_TRUE(entry->GetString("id", &input_method_id)); ASSERT_TRUE(entry->GetString("displayName", &display_name)); ASSERT_TRUE(entry->GetDictionary("languageCodeSet", &language_code_set)); EXPECT_EQ("xkb:us::eng", input_method_id); // Commented out as it depends on translation in generated_resources.grd // (i.e. makes the test fragile). // EXPECT_EQ("English (USA) keyboard layout", display_name); ASSERT_TRUE(language_code_set->HasKey("en-US")); ASSERT_TRUE(language_code_set->HasKey("id")); // From kExtraLanguages. ASSERT_TRUE(language_code_set->HasKey("fil")); // From kExtraLanguages. ASSERT_TRUE(list->GetDictionary(1, &entry)); ASSERT_TRUE(entry->GetString("id", &input_method_id)); ASSERT_TRUE(entry->GetString("displayName", &display_name)); ASSERT_TRUE(entry->GetDictionary("languageCodeSet", &language_code_set)); EXPECT_EQ("xkb:fr::fra", input_method_id); // Commented out. See above. // EXPECT_EQ("French keyboard layout", display_name); ASSERT_TRUE(language_code_set->HasKey("fr")); ASSERT_TRUE(list->GetDictionary(2, &entry)); ASSERT_TRUE(entry->GetString("id", &input_method_id)); ASSERT_TRUE(entry->GetString("displayName", &display_name)); ASSERT_TRUE(entry->GetDictionary("languageCodeSet", &language_code_set)); EXPECT_EQ("xkb:be::fra", input_method_id); // Commented out. See above. // EXPECT_EQ("Belgian keyboard layout", display_name); ASSERT_TRUE(language_code_set->HasKey("fr")); ASSERT_TRUE(list->GetDictionary(3, &entry)); ASSERT_TRUE(entry->GetString("id", &input_method_id)); ASSERT_TRUE(entry->GetString("displayName", &display_name)); ASSERT_TRUE(entry->GetDictionary("languageCodeSet", &language_code_set)); EXPECT_EQ("mozc", input_method_id); // Commented out. See above. // EXPECT_EQ("Japanese input method (for US keyboard)", display_name); ASSERT_TRUE(language_code_set->HasKey("ja")); } TEST(LanguageOptionsHandlerTest, GetLanguageList) { chromeos::InputMethodDescriptors descriptors = CreateInputMethodDescriptors(); scoped_ptr<ListValue> list( chromeos::CrosLanguageOptionsHandler::GetLanguageList(descriptors)); ASSERT_EQ(7U, list->GetSize()); DictionaryValue* entry = NULL; std::string language_code; std::string display_name; std::string native_display_name; // As shown below, the list should be sorted by the display names, // and these names should not have duplicates. // This comes from kExtraLanguages. ASSERT_TRUE(list->GetDictionary(0, &entry)); ASSERT_TRUE(entry->GetString("code", &language_code)); ASSERT_TRUE(entry->GetString("displayName", &display_name)); ASSERT_TRUE(entry->GetString("nativeDisplayName", &native_display_name)); EXPECT_EQ("en-AU", language_code); EXPECT_EQ("English (Australia)", display_name); EXPECT_EQ("English (Australia)", native_display_name); ASSERT_TRUE(list->GetDictionary(1, &entry)); ASSERT_TRUE(entry->GetString("code", &language_code)); ASSERT_TRUE(entry->GetString("displayName", &display_name)); ASSERT_TRUE(entry->GetString("nativeDisplayName", &native_display_name)); EXPECT_EQ("en-US", language_code); EXPECT_EQ("English (United States)", display_name); EXPECT_EQ("English (United States)", native_display_name); // This comes from kExtraLanguages. ASSERT_TRUE(list->GetDictionary(2, &entry)); ASSERT_TRUE(entry->GetString("code", &language_code)); ASSERT_TRUE(entry->GetString("displayName", &display_name)); ASSERT_TRUE(entry->GetString("nativeDisplayName", &native_display_name)); EXPECT_EQ("fil", language_code); EXPECT_EQ("Filipino", display_name); EXPECT_EQ("Filipino", native_display_name); ASSERT_TRUE(list->GetDictionary(3, &entry)); ASSERT_TRUE(entry->GetString("code", &language_code)); ASSERT_TRUE(entry->GetString("displayName", &display_name)); ASSERT_TRUE(entry->GetString("nativeDisplayName", &native_display_name)); EXPECT_EQ("fr", language_code); EXPECT_EQ("French", display_name); EXPECT_EQ("fran\u00E7ais", native_display_name); // This comes from kExtraLanguages. ASSERT_TRUE(list->GetDictionary(4, &entry)); ASSERT_TRUE(entry->GetString("code", &language_code)); ASSERT_TRUE(entry->GetString("displayName", &display_name)); ASSERT_TRUE(entry->GetString("nativeDisplayName", &native_display_name)); EXPECT_EQ("id", language_code); EXPECT_EQ("Indonesian", display_name); EXPECT_EQ("Bahasa Indonesia", native_display_name); ASSERT_TRUE(list->GetDictionary(5, &entry)); ASSERT_TRUE(entry->GetString("code", &language_code)); ASSERT_TRUE(entry->GetString("displayName", &display_name)); ASSERT_TRUE(entry->GetString("nativeDisplayName", &native_display_name)); EXPECT_EQ("ja", language_code); EXPECT_EQ("Japanese", display_name); EXPECT_EQ("\u65E5\u672C\u8A9E", native_display_name); // This comes from kExtraLanguages. ASSERT_TRUE(list->GetDictionary(6, &entry)); ASSERT_TRUE(entry->GetString("code", &language_code)); ASSERT_TRUE(entry->GetString("displayName", &display_name)); ASSERT_TRUE(entry->GetString("nativeDisplayName", &native_display_name)); EXPECT_EQ("es-419", language_code); EXPECT_EQ("Spanish (Latin America)", display_name); EXPECT_EQ("espa\u00F1ol (Latinoam\u00E9rica y el Caribe)", native_display_name); } #endif // defined(OS_CHROMEOS) #if !defined(OS_MACOSX) TEST(LanguageOptionsHandlerTest, GetUILanguageCodeSet) { scoped_ptr<DictionaryValue> dictionary( LanguageOptionsHandler::GetUILanguageCodeSet()); EXPECT_TRUE(dictionary->HasKey("en-US")); // Note that we don't test a false case, as such an expectation will // fail when we add support for the language. // EXPECT_FALSE(dictionary->HasKey("no")); } #endif // !defined(OS_MACOSX) TEST(LanguageOptionsHandlerTest, GetSpellCheckLanguageCodeSet) { scoped_ptr<DictionaryValue> dictionary( LanguageOptionsHandler::GetSpellCheckLanguageCodeSet()); EXPECT_TRUE(dictionary->HasKey("en-US")); } <|endoftext|>
<commit_before><?php define('APP_ENV', 'MAIN'); require(__DIR__.'/core/app-load.php'); header('Content-Type: text/html; charset=utf-8'); echo Helper::go(HTTP::GET, $_GET, $_POST, $_SERVER, $_COOKIE); <commit_msg>:bug: Ignore any post data in main website<commit_after><?php define('APP_ENV', 'MAIN'); require(__DIR__.'/core/app-load.php'); header('Content-Type: text/html; charset=utf-8'); echo Helper::go(HTTP::GET, $_GET, [], $_SERVER, $_COOKIE); <|endoftext|>
<commit_before>#include <iostream> #include "memfun.hpp" struct S { void f() const noexcept { std::cout << "Hello world!" << std::endl; } void g(int const a) const noexcept { std::cout << a << std::endl; } }; int main() { S s; auto const f(gnr::memfun<MEMFUN(S::f)>(s)); f(); auto const g(gnr::memfun<MEMFUN(S::f)>(&s)); g(); auto const h(gnr::memfun<MEMFUN(S::f)>()); h(s); auto const i(gnr::memfun<MEMFUN(S::g)>()); i(s, 10); i(&s, 10); return 0; } <commit_msg>some fixes<commit_after>#include <iostream> #include "memfun.hpp" struct S { void f() const noexcept { std::cout << "Hello world!" << std::endl; } void g(int const a) const noexcept { std::cout << a << std::endl; } }; int main() { S s; auto const f(gnr::memfun<MEMFUN(S::f)>(s)); f(); auto const g(gnr::memfun<MEMFUN(S::f)>(&s)); g(); auto const h(gnr::memfun<MEMFUN(S::f)>()); h(s); auto const i(gnr::memfun<MEMFUN(S::g)>()); i(s, 10); i(&s, 10); return 0; } <|endoftext|>
<commit_before>// ------------------------------------------------------------------------- // @FileName : NFCProperty.cpp // @Author : LvSheng.Huang // @Date : 2012-03-01 // @Module : NFCProperty // // ------------------------------------------------------------------------- #include "NFCProperty.h" #include <complex> NFCProperty::NFCProperty() { mbPublic = false; mbPrivate = false; mbSave = false; mSelf = NFGUID(); eType = TDATA_UNKNOWN; msPropertyName = ""; } NFCProperty::NFCProperty(const NFGUID& self, const std::string& strPropertyName, const TDATA_TYPE varType, bool bPublic, bool bPrivate, bool bSave, bool bView, int nIndex, const std::string& strScriptFunction) { mbPublic = bPublic; mbPrivate = bPrivate; mbSave = bSave; mbView = bView; mnIndex = nIndex; mSelf = self; msPropertyName = strPropertyName; eType = varType; } NFCProperty::~NFCProperty() { for (TPROPERTYCALLBACKEX::iterator iter = mtPropertyCallback.begin(); iter != mtPropertyCallback.end(); ++iter) { iter->reset(); } mtPropertyCallback.clear(); mxData.reset(); } void NFCProperty::SetValue(const NFIDataList::TData& TData) { if (eType != TData.GetType()) { return; } if (!mxData.get()) { if (!TData.IsNullValue()) { return; } mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TData)); } NFCDataList::TData oldValue; oldValue = *mxData; mxData->variantData = TData.variantData; NFCDataList::TData newValue; newValue = *mxData; OnEventHandler(oldValue , newValue); } void NFCProperty::SetValue(const NFIProperty* pProperty) { SetValue(pProperty->GetValue()); } const NFIDataList::TData& NFCProperty::GetValue() const { if (mxData.get()) { return *mxData; } return NULL_TDATA; } const std::string& NFCProperty::GetKey() const { return msPropertyName; } const bool NFCProperty::GetSave() const { return mbSave; } const bool NFCProperty::GetView() const { return mbView; } const bool NFCProperty::GetPublic() const { return mbPublic; } const bool NFCProperty::GetPrivate() const { return mbPrivate; } const int NFCProperty::GetIndex() const { return mnIndex; }; const std::string& NFCProperty::GetRelationValue() const { return NULL_STR;//msScriptFunction; } void NFCProperty::SetSave(bool bSave) { mbSave = bSave; } void NFCProperty::SetView(bool bView) { mbView = bView; } void NFCProperty::SetPublic(bool bPublic) { mbPublic = bPublic; } void NFCProperty::SetPrivate(bool bPrivate) { mbPrivate = bPrivate; } void NFCProperty::SetScriptFunction(const std::string& strScriptFunction) { //msScriptFunction = strScriptFunction; } NFINT64 NFCProperty::GetInt() const { if (!mxData.get()) { return 0; } return mxData->GetInt(); } double NFCProperty::GetFloat() const { if (!mxData.get()) { return 0.0; } return mxData->GetFloat(); } const std::string& NFCProperty::GetString() const { if (!mxData.get()) { return NULL_STR; } return mxData->GetString(); } const NFGUID& NFCProperty::GetObject() const { if (!mxData.get()) { return NULL_OBJECT; } return mxData->GetObject(); } void NFCProperty::RegisterCallback(const PROPERTY_EVENT_FUNCTOR_PTR& cb) { mtPropertyCallback.push_back(cb); } int NFCProperty::OnEventHandler(const NFIDataList::TData& oldVar, const NFIDataList::TData& newVar) { if (mtPropertyCallback.size() <= 0) { return 0; } TPROPERTYCALLBACKEX::iterator it = mtPropertyCallback.begin(); TPROPERTYCALLBACKEX::iterator end = mtPropertyCallback.end(); for (it; it != end; ++it) { //NFIDataList:OLDֵNEWֵ, ARG(pKernel,self) PROPERTY_EVENT_FUNCTOR_PTR& pFunPtr = *it; PROPERTY_EVENT_FUNCTOR* pFunc = pFunPtr.get(); int nTemRet = pFunc->operator()(mSelf, msPropertyName, oldVar, newVar); } return 0; } bool NFCProperty::SetInt(const NFINT64 value) { if (eType != TDATA_INT) { return false; } if (!mxData.get()) { //ǿվΪûݣûݵľͲ if (0 == value) { return false; } mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_INT)); mxData->SetInt(0); } if (value == mxData->GetInt()) { return false; } NFCDataList::TData oldValue; oldValue = *mxData; mxData->SetInt(value); OnEventHandler(oldValue , *mxData); return true; } bool NFCProperty::SetFloat(const double value) { if (eType != TDATA_FLOAT) { return false; } if (!mxData.get()) { //ǿվΪûݣûݵľͲ if (std::abs(value) < 0.001) { return false; } mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_FLOAT)); mxData->SetFloat(0.0); } if (value - mxData->GetFloat() < 0.001) { return false; } NFCDataList::TData oldValue; oldValue = *mxData; mxData->SetFloat(value); OnEventHandler(oldValue , *mxData); return true; } bool NFCProperty::SetString(const std::string& value) { if (eType != TDATA_STRING) { return false; } if (!mxData.get()) { //ǿվΪûݣûݵľͲ if (value.empty()) { return false; } mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_STRING)); mxData->SetString(NULL_STR); } if (value == mxData->GetString()) { return false; } NFCDataList::TData oldValue; oldValue = *mxData; mxData->SetString(value); OnEventHandler(oldValue , *mxData); return true; } bool NFCProperty::SetObject(const NFGUID& value) { if (eType != TDATA_OBJECT) { return false; } if (!mxData.get()) { //ǿվΪûݣûݵľͲ if (value.IsNull()) { return false; } mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_OBJECT)); mxData->SetObject(NFGUID()); } if (value == mxData->GetObject()) { return false; } NFCDataList::TData oldValue; oldValue = *mxData; mxData->SetObject(value); OnEventHandler(oldValue , *mxData); return true; } bool NFCProperty::Changed() const { return GetValue().IsNullValue(); } const TDATA_TYPE NFCProperty::GetType() const { return eType; } const bool NFCProperty::GeUsed() const { if (mxData.get()) { return true; } return false; } std::string NFCProperty::ToString() { std::string strData; const TDATA_TYPE eType = GetType(); switch (eType) { case TDATA_INT: strData = lexical_cast<std::string> (GetInt()); break; case TDATA_FLOAT: strData = lexical_cast<std::string> (GetFloat()); break; case TDATA_STRING: strData = lexical_cast<std::string> (GetString()); break; case TDATA_OBJECT: strData = GetObject().ToString(); break; default: strData = NULL_STR; break; } return strData; } bool NFCProperty::FromString( const std::string& strData ) { const TDATA_TYPE eType = GetType(); bool bRet = false; switch (eType) { case TDATA_INT: { NFINT64 nValue = 0; bRet = NF_StrTo(strData, nValue); SetInt(nValue); } break; case TDATA_FLOAT: { double dValue = 0; bRet = NF_StrTo(strData, dValue); SetFloat(dValue); } break; case TDATA_STRING: { SetString(strData); bRet = true; } break; case TDATA_OBJECT: { NFGUID xID; bRet = xID.FromString(strData); SetObject(xID); } break; default: break; } return bRet; } <commit_msg>optimize code when property been set<commit_after>// ------------------------------------------------------------------------- // @FileName : NFCProperty.cpp // @Author : LvSheng.Huang // @Date : 2012-03-01 // @Module : NFCProperty // // ------------------------------------------------------------------------- #include "NFCProperty.h" #include <complex> NFCProperty::NFCProperty() { mbPublic = false; mbPrivate = false; mbSave = false; mSelf = NFGUID(); eType = TDATA_UNKNOWN; msPropertyName = ""; } NFCProperty::NFCProperty(const NFGUID& self, const std::string& strPropertyName, const TDATA_TYPE varType, bool bPublic, bool bPrivate, bool bSave, bool bView, int nIndex, const std::string& strScriptFunction) { mbPublic = bPublic; mbPrivate = bPrivate; mbSave = bSave; mbView = bView; mnIndex = nIndex; mSelf = self; msPropertyName = strPropertyName; eType = varType; } NFCProperty::~NFCProperty() { for (TPROPERTYCALLBACKEX::iterator iter = mtPropertyCallback.begin(); iter != mtPropertyCallback.end(); ++iter) { iter->reset(); } mtPropertyCallback.clear(); mxData.reset(); } void NFCProperty::SetValue(const NFIDataList::TData& TData) { if (eType != TData.GetType()) { return; } if (!mxData.get()) { if (!TData.IsNullValue()) { return; } mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TData)); } NFCDataList::TData oldValue; oldValue = *mxData; mxData->variantData = TData.variantData; NFCDataList::TData newValue; newValue = *mxData; OnEventHandler(oldValue , newValue); } void NFCProperty::SetValue(const NFIProperty* pProperty) { SetValue(pProperty->GetValue()); } const NFIDataList::TData& NFCProperty::GetValue() const { if (mxData.get()) { return *mxData; } return NULL_TDATA; } const std::string& NFCProperty::GetKey() const { return msPropertyName; } const bool NFCProperty::GetSave() const { return mbSave; } const bool NFCProperty::GetView() const { return mbView; } const bool NFCProperty::GetPublic() const { return mbPublic; } const bool NFCProperty::GetPrivate() const { return mbPrivate; } const int NFCProperty::GetIndex() const { return mnIndex; }; const std::string& NFCProperty::GetRelationValue() const { return NULL_STR;//msScriptFunction; } void NFCProperty::SetSave(bool bSave) { mbSave = bSave; } void NFCProperty::SetView(bool bView) { mbView = bView; } void NFCProperty::SetPublic(bool bPublic) { mbPublic = bPublic; } void NFCProperty::SetPrivate(bool bPrivate) { mbPrivate = bPrivate; } void NFCProperty::SetScriptFunction(const std::string& strScriptFunction) { //msScriptFunction = strScriptFunction; } NFINT64 NFCProperty::GetInt() const { if (!mxData.get()) { return 0; } return mxData->GetInt(); } double NFCProperty::GetFloat() const { if (!mxData.get()) { return 0.0; } return mxData->GetFloat(); } const std::string& NFCProperty::GetString() const { if (!mxData.get()) { return NULL_STR; } return mxData->GetString(); } const NFGUID& NFCProperty::GetObject() const { if (!mxData.get()) { return NULL_OBJECT; } return mxData->GetObject(); } void NFCProperty::RegisterCallback(const PROPERTY_EVENT_FUNCTOR_PTR& cb) { mtPropertyCallback.push_back(cb); } int NFCProperty::OnEventHandler(const NFIDataList::TData& oldVar, const NFIDataList::TData& newVar) { if (mtPropertyCallback.size() <= 0) { return 0; } TPROPERTYCALLBACKEX::iterator it = mtPropertyCallback.begin(); TPROPERTYCALLBACKEX::iterator end = mtPropertyCallback.end(); for (it; it != end; ++it) { //NFIDataList:OLDֵNEWֵ, ARG(pKernel,self) PROPERTY_EVENT_FUNCTOR_PTR& pFunPtr = *it; PROPERTY_EVENT_FUNCTOR* pFunc = pFunPtr.get(); int nTemRet = pFunc->operator()(mSelf, msPropertyName, oldVar, newVar); } return 0; } bool NFCProperty::SetInt(const NFINT64 value) { if (eType != TDATA_INT) { return false; } if (!mxData.get()) { //ǿվΪûݣûݵľͲ if (0 == value) { return false; } mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_INT)); mxData->SetInt(0); } if (value == mxData->GetInt()) { return false; } NFCDataList::TData oldValue; oldValue = *mxData; mxData->SetInt(value); OnEventHandler(oldValue , value); return true; } bool NFCProperty::SetFloat(const double value) { if (eType != TDATA_FLOAT) { return false; } if (!mxData.get()) { //ǿվΪûݣûݵľͲ if (std::abs(value) < 0.001) { return false; } mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_FLOAT)); mxData->SetFloat(0.0); } if (value - mxData->GetFloat() < 0.001) { return false; } NFCDataList::TData oldValue; oldValue = *mxData; mxData->SetFloat(value); OnEventHandler(oldValue , newValue); return true; } bool NFCProperty::SetString(const std::string& value) { if (eType != TDATA_STRING) { return false; } if (!mxData.get()) { //ǿվΪûݣûݵľͲ if (value.empty()) { return false; } mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_STRING)); mxData->SetString(NULL_STR); } if (value == mxData->GetString()) { return false; } NFCDataList::TData oldValue; oldValue = *mxData; mxData->SetString(value); OnEventHandler(oldValue , newValue); return true; } bool NFCProperty::SetObject(const NFGUID& value) { if (eType != TDATA_OBJECT) { return false; } if (!mxData.get()) { //ǿվΪûݣûݵľͲ if (value.IsNull()) { return false; } mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_OBJECT)); mxData->SetObject(NFGUID()); } if (value == mxData->GetObject()) { return false; } NFCDataList::TData oldValue; oldValue = *mxData; mxData->SetObject(value); OnEventHandler(oldValue , *mxData); return true; } bool NFCProperty::Changed() const { return GetValue().IsNullValue(); } const TDATA_TYPE NFCProperty::GetType() const { return eType; } const bool NFCProperty::GeUsed() const { if (mxData.get()) { return true; } return false; } std::string NFCProperty::ToString() { std::string strData; const TDATA_TYPE eType = GetType(); switch (eType) { case TDATA_INT: strData = lexical_cast<std::string> (GetInt()); break; case TDATA_FLOAT: strData = lexical_cast<std::string> (GetFloat()); break; case TDATA_STRING: strData = lexical_cast<std::string> (GetString()); break; case TDATA_OBJECT: strData = GetObject().ToString(); break; default: strData = NULL_STR; break; } return strData; } bool NFCProperty::FromString( const std::string& strData ) { const TDATA_TYPE eType = GetType(); bool bRet = false; switch (eType) { case TDATA_INT: { NFINT64 nValue = 0; bRet = NF_StrTo(strData, nValue); SetInt(nValue); } break; case TDATA_FLOAT: { double dValue = 0; bRet = NF_StrTo(strData, dValue); SetFloat(dValue); } break; case TDATA_STRING: { SetString(strData); bRet = true; } break; case TDATA_OBJECT: { NFGUID xID; bRet = xID.FromString(strData); SetObject(xID); } break; default: break; } return bRet; } <|endoftext|>
<commit_before><commit_msg>Messages<commit_after><|endoftext|>
<commit_before>#include "alpha-expansion.hpp" MultiLabelCRF::MultiLabelCRF(Label max_label) : m_num_labels(max_label), m_constant_term(0), m_cliques(), m_unary_cost(), m_labels() { } MultiLabelCRF::NodeId MultiLabelCRF::AddNode(int n) { NodeId ret = m_labels.size(); for (int i = 0; i < n; ++i) { m_labels.push_back(0); UnaryCost uc(m_num_labels, 0); m_unary_cost.push_back(uc); } return ret; } int MultiLabelCRF::GetLabel(NodeId i) const { return m_labels[i]; } void MultiLabelCRF::AddConstantTerm(REAL c) { m_constant_term += c; } void MultiLabelCRF::AddUnaryTerm(NodeId i, const std::vector<REAL>& coeffs) { ASSERT(coeffs.size() == m_num_labels); for (size_t j = 0; j < m_num_labels; ++j) { m_unary_cost[i][j] += coeffs[j]; } } void MultiLabelCRF::AddClique(const CliquePtr& cp) { m_cliques.push_back(cp); } void MultiLabelCRF::SetupAlphaEnergy(Label alpha, SubmodularFlow& crf) const { typedef int32_t Assgn; for (const CliquePtr& cp : m_cliques) { const Clique& c = *cp; const size_t k = c.Size(); ASSERT(k < 32); const Assgn max_assgn = 1 << k; std::vector<REAL> energy_table; std::vector<Label> label_buf; for (Assgn a = 0; a < max_assgn; ++a) { label_buf.clear(); for (size_t i_idx = 0; i_idx < k; ++i_idx) { if (a & (1 << i_idx)) label_buf.push_back(alpha); else label_buf.push_back(m_labels[c.Nodes()[i_idx]]); } energy_table.push_back(c.Energy(label_buf)); } crf.AddClique(c.Nodes(), energy_table); } } void MultiLabelCRF::AlphaExpansion() { std::cout << "Starting Alpha Expansion\n"; REAL last_energy = std::numeric_limits<REAL>::max(); REAL energy = ComputeEnergy(); const NodeId n = m_labels.size(); size_t num_rounds = 0; while (energy < last_energy) { std::cout << "\tRound: " << num_rounds; std::cout.flush(); for (Label alpha = 0; alpha < m_num_labels; ++alpha) { std::cout << "."; std::cout.flush(); SubmodularFlow crf; crf.AddNode(m_labels.size()); SetupAlphaEnergy(alpha, crf); crf.Solve(); for (NodeId i = 0; i < n; ++i) { int crf_label = crf.GetLabel(i); if (crf_label == 1) m_labels[i] = alpha; } } std::cout << "\n"; last_energy = energy; energy = ComputeEnergy(); num_rounds++; } } void MultiLabelCRF::Solve() { AlphaExpansion(); } REAL MultiLabelCRF::ComputeEnergy() const { return ComputeEnergy(m_labels); } REAL MultiLabelCRF::ComputeEnergy(const std::vector<Label>& labels) const { REAL energy = m_constant_term; std::vector<Label> labelBuf; for (const CliquePtr& cp : m_cliques) { const Clique& c = *cp; labelBuf.clear(); for (NodeId i : c.Nodes()) labelBuf.push_back(m_labels[i]); energy += c.Energy(labelBuf); } return energy; } <commit_msg>Actually adding unary terms to AlphaExpansion Energy<commit_after>#include "alpha-expansion.hpp" MultiLabelCRF::MultiLabelCRF(Label max_label) : m_num_labels(max_label), m_constant_term(0), m_cliques(), m_unary_cost(), m_labels() { } MultiLabelCRF::NodeId MultiLabelCRF::AddNode(int n) { NodeId ret = m_labels.size(); for (int i = 0; i < n; ++i) { m_labels.push_back(0); UnaryCost uc(m_num_labels, 0); m_unary_cost.push_back(uc); } return ret; } int MultiLabelCRF::GetLabel(NodeId i) const { return m_labels[i]; } void MultiLabelCRF::AddConstantTerm(REAL c) { m_constant_term += c; } void MultiLabelCRF::AddUnaryTerm(NodeId i, const std::vector<REAL>& coeffs) { ASSERT(coeffs.size() == m_num_labels); for (size_t j = 0; j < m_num_labels; ++j) { m_unary_cost[i][j] += coeffs[j]; } } void MultiLabelCRF::AddClique(const CliquePtr& cp) { m_cliques.push_back(cp); } void MultiLabelCRF::SetupAlphaEnergy(Label alpha, SubmodularFlow& crf) const { typedef int32_t Assgn; for (const CliquePtr& cp : m_cliques) { const Clique& c = *cp; const size_t k = c.Size(); ASSERT(k < 32); const Assgn max_assgn = 1 << k; std::vector<REAL> energy_table; std::vector<Label> label_buf; for (Assgn a = 0; a < max_assgn; ++a) { label_buf.clear(); for (size_t i_idx = 0; i_idx < k; ++i_idx) { if (a & (1 << i_idx)) label_buf.push_back(alpha); else label_buf.push_back(m_labels[c.Nodes()[i_idx]]); } energy_table.push_back(c.Energy(label_buf)); } crf.AddClique(c.Nodes(), energy_table); } const NodeId n = m_unary_cost.size(); for (NodeId i = 0; i < n; ++i) { crf.AddUnaryTerm(i, m_unary_cost[i][m_labels[i]], m_unary_cost[i][alpha]); } } void MultiLabelCRF::AlphaExpansion() { std::cout << "Starting Alpha Expansion\n"; REAL last_energy = std::numeric_limits<REAL>::max(); REAL energy = ComputeEnergy(); const NodeId n = m_labels.size(); size_t num_rounds = 0; while (energy < last_energy) { std::cout << "\tRound: " << num_rounds; std::cout.flush(); for (Label alpha = 0; alpha < m_num_labels; ++alpha) { std::cout << "."; std::cout.flush(); SubmodularFlow crf; crf.AddNode(m_labels.size()); SetupAlphaEnergy(alpha, crf); crf.Solve(); for (NodeId i = 0; i < n; ++i) { int crf_label = crf.GetLabel(i); if (crf_label == 1) m_labels[i] = alpha; } } std::cout << "\n"; last_energy = energy; energy = ComputeEnergy(); num_rounds++; } } void MultiLabelCRF::Solve() { AlphaExpansion(); } REAL MultiLabelCRF::ComputeEnergy() const { return ComputeEnergy(m_labels); } REAL MultiLabelCRF::ComputeEnergy(const std::vector<Label>& labels) const { REAL energy = m_constant_term; std::vector<Label> labelBuf; for (const CliquePtr& cp : m_cliques) { const Clique& c = *cp; labelBuf.clear(); for (NodeId i : c.Nodes()) labelBuf.push_back(m_labels[i]); energy += c.Energy(labelBuf); } const NodeId n = m_labels.size(); for (NodeId i = 0; i < n; ++i) energy += m_unary_cost[i][labels[i]]; return energy; } <|endoftext|>
<commit_before>/** * Copyright 2015-2017 MICRORISC s.r.o. * Copyright 2017 IQRF Tech s.r.o. * * 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 "DpaTransfer.h" #include "DpaTransaction.h" #include "unexpected_packet_type.h" #include "unexpected_command.h" #include "unexpected_peripheral.h" #include "IqrfLogging.h" DpaTransfer::DpaTransfer() : m_status(kCreated), m_sentMessage(nullptr), m_responseMessage(nullptr), m_expectedDurationMs(400), m_timeoutMs(400), m_currentCommunicationMode(kStd), m_dpaTransaction(nullptr) { } DpaTransfer::DpaTransfer(DpaTransaction* dpaTransaction, IqrfRfCommunicationMode comMode) : m_status(kCreated), m_sentMessage(nullptr), m_responseMessage(nullptr), m_expectedDurationMs(400), m_timeoutMs(400), m_currentCommunicationMode(comMode), m_dpaTransaction(dpaTransaction) { } DpaTransfer::~DpaTransfer() { delete m_sentMessage; delete m_responseMessage; } void DpaTransfer::ProcessSentMessage(const DpaMessage& sentMessage) { TRC_ENTER(""); if (m_status != kCreated) { throw std::logic_error("Sent message already set."); } // current request status is set as sent if (sentMessage.NodeAddress() == COORDINATOR_ADDRESS) { SetStatus(kSentCoordinator); } else { SetStatus(kSent); } // message itself is destroyed after being sent delete m_sentMessage; // creating object to hold new request m_sentMessage = new DpaMessage(sentMessage); // setting default timeout, no estimation yet SetTimingForCurrentTransfer(); TRC_LEAVE(""); } void DpaTransfer::ProcessReceivedMessage(const DpaMessage& receivedMessage) { TRC_ENTER(""); if (receivedMessage.MessageDirection() != DpaMessage::kResponse && receivedMessage.MessageDirection() != DpaMessage::kConfirmation) throw unexpected_packet_type("Response is expected."); std::lock_guard<std::mutex> lck(m_statusMutex); // checks if (!IsInProgressStatus(m_status)) { throw unexpected_packet_type("Request has not been sent, yet."); } if (receivedMessage.PeripheralType() != m_sentMessage->PeripheralType()) { throw unexpected_peripheral("Different peripheral type than in sent message."); } if ((receivedMessage.PeripheralCommand() & ~0x80) != m_sentMessage->PeripheralCommand()) { throw unexpected_command("Different peripheral command than in sent message."); } // direction auto messageDirection = receivedMessage.MessageDirection(); if (messageDirection == DpaMessage::kConfirmation) { if (m_dpaTransaction) { m_dpaTransaction->processConfirmationMessage(receivedMessage); } ProcessConfirmationMessage(receivedMessage); TRC_INF("Confirmation processed."); } else { if (m_dpaTransaction) { m_dpaTransaction->processResponseMessage(receivedMessage); } ProcessResponseMessage(receivedMessage); TRC_INF("Response processed."); } TRC_LEAVE(""); } void DpaTransfer::ProcessConfirmationMessage(const DpaMessage& confirmationMessage) { if (confirmationMessage.NodeAddress() == DpaMessage::kBroadCastAddress) { m_status = kConfirmationBroadcast; } else { m_status = kConfirmation; } // setting timeout based on the confirmation SetTimingForCurrentTransfer(EstimatedTimeout(confirmationMessage)); } void DpaTransfer::ProcessResponseMessage(const DpaMessage& responseMessage) { // if there is a request to coordinator then after receiving response it is allowed to send another if (m_status == kSentCoordinator) { // done, next request gets ready m_status = kProcessed; } else { // only if there is not infinite timeout if (m_expectedDurationMs != 0) { m_status = kReceivedResponse; // adjust timing before allowing next request SetTimingForCurrentTransfer(EstimatedTimeout(responseMessage)); } // infinite timeout else { // done, next request gets ready m_status = kProcessed; } } delete m_responseMessage; m_responseMessage = new DpaMessage(responseMessage); } int32_t DpaTransfer::EstimatedTimeout(const DpaMessage& receivedMessage) { // direction auto direction = receivedMessage.MessageDirection(); // double check if (direction != DpaMessage::kConfirmation && direction != DpaMessage::kResponse) { throw std::invalid_argument("Parameter is not a received message type."); } // confirmation if (direction == DpaMessage::kConfirmation) { auto iFace = receivedMessage.DpaPacket().DpaResponsePacket_t.DpaMessage.IFaceConfirmation; // save for later use with response m_hops = iFace.Hops; m_timeslotLength = iFace.TimeSlotLength; m_hopsResponse = iFace.HopsResponse; // lp if (m_currentCommunicationMode == kLp) { return EstimateLpTimeout(m_hops, m_timeslotLength, m_hopsResponse); } // std return EstimateStdTimeout(m_hops, m_timeslotLength, m_hopsResponse); } // response if (direction == DpaMessage::kResponse) { // lp if (m_currentCommunicationMode == kLp) { return EstimateLpTimeout(m_hops, m_timeslotLength, m_hopsResponse, receivedMessage.GetLength() - (sizeof(TDpaIFaceHeader) + 2)); } // std return EstimateStdTimeout(m_hops, m_timeslotLength, m_hopsResponse, receivedMessage.GetLength() - (sizeof(TDpaIFaceHeader) + 2)); } } int32_t DpaTransfer::EstimateStdTimeout(uint8_t hopsRequest, uint8_t timeslotReq, uint8_t hopsResponse, int8_t responseDataLength) { TRC_ENTER(""); int32_t responseTimeSlotLengthMs; auto estimatedTimeoutMs = (hopsRequest + 1) * timeslotReq * 10; // estimation from confirmation if (responseDataLength == -1) { if (timeslotReq == 20) { responseTimeSlotLengthMs = 200; } else { // worst case responseTimeSlotLengthMs = 60; } } // correction of the estimation from response else { TRC_DBG("PData length of the received response: " << PAR((int)responseDataLength)); if (responseDataLength >= 0 && responseDataLength < 16) { responseTimeSlotLengthMs = 40; } else if (responseDataLength >= 16 && responseDataLength <= 39) { responseTimeSlotLengthMs = 50; } else if (responseDataLength > 39) { responseTimeSlotLengthMs = 60; } TRC_DBG("Correction of the response timeout: " << PAR(responseTimeSlotLengthMs)); } estimatedTimeoutMs += (hopsResponse + 1) * responseTimeSlotLengthMs + m_safetyTimeoutMs; TRC_DBG("Estimated STD timeout: " << PAR(estimatedTimeoutMs)); TRC_LEAVE(""); return estimatedTimeoutMs; } int32_t DpaTransfer::EstimateLpTimeout(uint8_t hopsRequest, uint8_t timeslotReq, uint8_t hopsResponse, int8_t responseDataLength) { TRC_ENTER(""); int32_t responseTimeSlotLengthMs; auto estimatedTimeoutMs = (hopsRequest + 1) * timeslotReq * 10; // estimation from confirmation if (responseDataLength == -1) { if (timeslotReq == 20) { responseTimeSlotLengthMs = 200; } else { // worst case responseTimeSlotLengthMs = 110; } } // correction of the estimation from response else { TRC_DBG("PData length of the received response: " << PAR((int)responseDataLength)); if (responseDataLength >= 0 && responseDataLength < 11) { responseTimeSlotLengthMs = 80; } else if (responseDataLength >= 11 && responseDataLength <= 33) { responseTimeSlotLengthMs = 90; } else if (responseDataLength >= 34 && responseDataLength <= 56) { responseTimeSlotLengthMs = 100; } else if (responseDataLength > 56) { responseTimeSlotLengthMs = 110; } TRC_DBG("Correction of the response timeout: " << PAR(responseTimeSlotLengthMs)); } estimatedTimeoutMs += (hopsResponse + 1) * responseTimeSlotLengthMs + m_safetyTimeoutMs; TRC_DBG("Estimated LP timeout: " << PAR(estimatedTimeoutMs)); TRC_LEAVE(""); return estimatedTimeoutMs; } void DpaTransfer::SetTimingForCurrentTransfer(int32_t estimatedTimeMs) { TRC_ENTER(""); // waiting forever if (m_timeoutMs == 0) { m_expectedDurationMs = m_timeoutMs; TRC_DBG("Expected duration to wait :" << PAR(m_expectedDurationMs)); return; } // adjust time to wait before allowing next request to go the iqrf network if (m_status == kReceivedResponse) { //adjust new timing based on length of PData in response m_expectedDurationMs = estimatedTimeMs; TRC_DBG("New expected duration to wait :" << PAR(m_expectedDurationMs)); return; } // estimation done if (estimatedTimeMs >= 0) { // either default timeout is 400 or user sets lower time than estimated if (m_timeoutMs < estimatedTimeMs) { // in both cases use estimation from confirmation m_timeoutMs = estimatedTimeMs; } // set new duration // there is also case when user sets higher than estimation then user choice is set m_expectedDurationMs = m_timeoutMs; TRC_DBG("Expected duration to wait :" << PAR(m_expectedDurationMs)); } // start time when dpa request is sent and rerun again when confirmation is received m_startTime = std::chrono::system_clock::now(); TRC_INF("Transfer status: started"); TRC_LEAVE(""); } DpaTransfer::DpaTransferStatus DpaTransfer::ProcessStatus() { std::lock_guard<std::mutex> lck(m_statusMutex); // changes m_status, does not care about remains // todo: refactor and rename - two functions CheckTimeout(); return m_status; } int32_t DpaTransfer::CheckTimeout() { int32_t remains(0); if (m_status == kCreated) { TRC_INF("Transfer status: created"); return remains; } if (m_status == kAborted) { TRC_INF("Transfer status: aborted"); return remains; } bool timingFinished(false); // infinite (0) is out of this statement if (m_expectedDurationMs > 0) { // passed time from sent request auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now() - m_startTime); remains = m_expectedDurationMs - duration.count(); TRC_DBG("Time to wait: " << PAR(remains)); // already over? timingFinished = remains < 0; } // not yet set and yes time is over // processed or timeouted can be set only after finished timing if (m_status != kProcessed && m_status != kTimeout) { if (timingFinished) { // and we have received confirmation for broadcast or response if (m_status == kConfirmationBroadcast || m_status == kReceivedResponse) { SetStatus(kProcessed); TRC_INF("Transfer status: processed"); } else { SetStatus(kTimeout); TRC_INF("Transfer status: timeout"); } } } // time to wait return remains; } bool DpaTransfer::IsInProgress() { return IsInProgressStatus(ProcessStatus()); } bool DpaTransfer::IsInProgress(int32_t& expectedDuration) { std::lock_guard<std::mutex> lck(m_statusMutex); expectedDuration = CheckTimeout(); return IsInProgressStatus(m_status); } bool DpaTransfer::IsInProgressStatus(DpaTransferStatus status) { switch (status) { case kSent: case kSentCoordinator: case kConfirmation: case kConfirmationBroadcast: case kReceivedResponse: return true; // kCreated, kProcessed, kTimeout, kAbort, kError default: return false; } } void DpaTransfer::Abort() { std::lock_guard<std::mutex> lck(m_statusMutex); m_status = kAborted; } void DpaTransfer::SetStatus(DpaTransfer::DpaTransferStatus status) { m_status = status; } <commit_msg>Adding more traces around CheckTimeout()<commit_after>/** * Copyright 2015-2017 MICRORISC s.r.o. * Copyright 2017 IQRF Tech s.r.o. * * 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 "DpaTransfer.h" #include "DpaTransaction.h" #include "unexpected_packet_type.h" #include "unexpected_command.h" #include "unexpected_peripheral.h" #include "IqrfLogging.h" DpaTransfer::DpaTransfer() : m_status(kCreated), m_sentMessage(nullptr), m_responseMessage(nullptr), m_expectedDurationMs(400), m_timeoutMs(400), m_currentCommunicationMode(kStd), m_dpaTransaction(nullptr) { } DpaTransfer::DpaTransfer(DpaTransaction* dpaTransaction, IqrfRfCommunicationMode comMode) : m_status(kCreated), m_sentMessage(nullptr), m_responseMessage(nullptr), m_expectedDurationMs(400), m_timeoutMs(400), m_currentCommunicationMode(comMode), m_dpaTransaction(dpaTransaction) { } DpaTransfer::~DpaTransfer() { delete m_sentMessage; delete m_responseMessage; } void DpaTransfer::ProcessSentMessage(const DpaMessage& sentMessage) { TRC_ENTER(""); if (m_status != kCreated) { throw std::logic_error("Sent message already set."); } // current request status is set as sent if (sentMessage.NodeAddress() == COORDINATOR_ADDRESS) { SetStatus(kSentCoordinator); } else { SetStatus(kSent); } // message itself is destroyed after being sent delete m_sentMessage; // creating object to hold new request m_sentMessage = new DpaMessage(sentMessage); // setting default timeout, no estimation yet SetTimingForCurrentTransfer(); TRC_LEAVE(""); } void DpaTransfer::ProcessReceivedMessage(const DpaMessage& receivedMessage) { TRC_ENTER(""); if (receivedMessage.MessageDirection() != DpaMessage::kResponse && receivedMessage.MessageDirection() != DpaMessage::kConfirmation) throw unexpected_packet_type("Response is expected."); std::lock_guard<std::mutex> lck(m_statusMutex); // checks if (!IsInProgressStatus(m_status)) { throw unexpected_packet_type("Request has not been sent, yet."); } if (receivedMessage.PeripheralType() != m_sentMessage->PeripheralType()) { throw unexpected_peripheral("Different peripheral type than in sent message."); } if ((receivedMessage.PeripheralCommand() & ~0x80) != m_sentMessage->PeripheralCommand()) { throw unexpected_command("Different peripheral command than in sent message."); } // direction auto messageDirection = receivedMessage.MessageDirection(); if (messageDirection == DpaMessage::kConfirmation) { if (m_dpaTransaction) { m_dpaTransaction->processConfirmationMessage(receivedMessage); } ProcessConfirmationMessage(receivedMessage); TRC_INF("Confirmation processed."); } else { if (m_dpaTransaction) { m_dpaTransaction->processResponseMessage(receivedMessage); } ProcessResponseMessage(receivedMessage); TRC_INF("Response processed."); } TRC_LEAVE(""); } void DpaTransfer::ProcessConfirmationMessage(const DpaMessage& confirmationMessage) { if (confirmationMessage.NodeAddress() == DpaMessage::kBroadCastAddress) { m_status = kConfirmationBroadcast; } else { m_status = kConfirmation; } // setting timeout based on the confirmation SetTimingForCurrentTransfer(EstimatedTimeout(confirmationMessage)); } void DpaTransfer::ProcessResponseMessage(const DpaMessage& responseMessage) { // if there is a request to coordinator then after receiving response it is allowed to send another if (m_status == kSentCoordinator) { // done, next request gets ready m_status = kProcessed; } else { // only if there is not infinite timeout if (m_expectedDurationMs != 0) { m_status = kReceivedResponse; // adjust timing before allowing next request SetTimingForCurrentTransfer(EstimatedTimeout(responseMessage)); } // infinite timeout else { // done, next request gets ready m_status = kProcessed; } } delete m_responseMessage; m_responseMessage = new DpaMessage(responseMessage); } int32_t DpaTransfer::EstimatedTimeout(const DpaMessage& receivedMessage) { // direction auto direction = receivedMessage.MessageDirection(); // double check if (direction != DpaMessage::kConfirmation && direction != DpaMessage::kResponse) { throw std::invalid_argument("Parameter is not a received message type."); } // confirmation if (direction == DpaMessage::kConfirmation) { auto iFace = receivedMessage.DpaPacket().DpaResponsePacket_t.DpaMessage.IFaceConfirmation; // save for later use with response m_hops = iFace.Hops; m_timeslotLength = iFace.TimeSlotLength; m_hopsResponse = iFace.HopsResponse; // lp if (m_currentCommunicationMode == kLp) { return EstimateLpTimeout(m_hops, m_timeslotLength, m_hopsResponse); } // std return EstimateStdTimeout(m_hops, m_timeslotLength, m_hopsResponse); } // response if (direction == DpaMessage::kResponse) { // lp if (m_currentCommunicationMode == kLp) { return EstimateLpTimeout(m_hops, m_timeslotLength, m_hopsResponse, receivedMessage.GetLength() - (sizeof(TDpaIFaceHeader) + 2)); } // std return EstimateStdTimeout(m_hops, m_timeslotLength, m_hopsResponse, receivedMessage.GetLength() - (sizeof(TDpaIFaceHeader) + 2)); } } int32_t DpaTransfer::EstimateStdTimeout(uint8_t hopsRequest, uint8_t timeslotReq, uint8_t hopsResponse, int8_t responseDataLength) { TRC_ENTER(""); int32_t responseTimeSlotLengthMs; auto estimatedTimeoutMs = (hopsRequest + 1) * timeslotReq * 10; // estimation from confirmation if (responseDataLength == -1) { if (timeslotReq == 20) { responseTimeSlotLengthMs = 200; } else { // worst case responseTimeSlotLengthMs = 60; } } // correction of the estimation from response else { TRC_DBG("PData length of the received response: " << PAR((int)responseDataLength)); if (responseDataLength >= 0 && responseDataLength < 16) { responseTimeSlotLengthMs = 40; } else if (responseDataLength >= 16 && responseDataLength <= 39) { responseTimeSlotLengthMs = 50; } else if (responseDataLength > 39) { responseTimeSlotLengthMs = 60; } TRC_DBG("Correction of the response timeout: " << PAR(responseTimeSlotLengthMs)); } estimatedTimeoutMs += (hopsResponse + 1) * responseTimeSlotLengthMs + m_safetyTimeoutMs; TRC_DBG("Estimated STD timeout: " << PAR(estimatedTimeoutMs)); TRC_LEAVE(""); return estimatedTimeoutMs; } int32_t DpaTransfer::EstimateLpTimeout(uint8_t hopsRequest, uint8_t timeslotReq, uint8_t hopsResponse, int8_t responseDataLength) { TRC_ENTER(""); int32_t responseTimeSlotLengthMs; auto estimatedTimeoutMs = (hopsRequest + 1) * timeslotReq * 10; // estimation from confirmation if (responseDataLength == -1) { if (timeslotReq == 20) { responseTimeSlotLengthMs = 200; } else { // worst case responseTimeSlotLengthMs = 110; } } // correction of the estimation from response else { TRC_DBG("PData length of the received response: " << PAR((int)responseDataLength)); if (responseDataLength >= 0 && responseDataLength < 11) { responseTimeSlotLengthMs = 80; } else if (responseDataLength >= 11 && responseDataLength <= 33) { responseTimeSlotLengthMs = 90; } else if (responseDataLength >= 34 && responseDataLength <= 56) { responseTimeSlotLengthMs = 100; } else if (responseDataLength > 56) { responseTimeSlotLengthMs = 110; } TRC_DBG("Correction of the response timeout: " << PAR(responseTimeSlotLengthMs)); } estimatedTimeoutMs += (hopsResponse + 1) * responseTimeSlotLengthMs + m_safetyTimeoutMs; TRC_DBG("Estimated LP timeout: " << PAR(estimatedTimeoutMs)); TRC_LEAVE(""); return estimatedTimeoutMs; } void DpaTransfer::SetTimingForCurrentTransfer(int32_t estimatedTimeMs) { TRC_ENTER(""); // waiting forever if (m_timeoutMs == 0) { m_expectedDurationMs = m_timeoutMs; TRC_DBG("Expected duration to wait :" << PAR(m_expectedDurationMs)); return; } // adjust time to wait before allowing next request to go the iqrf network if (m_status == kReceivedResponse) { //adjust new timing based on length of PData in response m_expectedDurationMs = estimatedTimeMs; TRC_DBG("New expected duration to wait :" << PAR(m_expectedDurationMs)); return; } // estimation done if (estimatedTimeMs >= 0) { // either default timeout is 400 or user sets lower time than estimated if (m_timeoutMs < estimatedTimeMs) { // in both cases use estimation from confirmation m_timeoutMs = estimatedTimeMs; } // set new duration // there is also case when user sets higher than estimation then user choice is set m_expectedDurationMs = m_timeoutMs; TRC_DBG("Expected duration to wait :" << PAR(m_expectedDurationMs)); } // start time when dpa request is sent and rerun again when confirmation is received m_startTime = std::chrono::system_clock::now(); TRC_INF("Transfer status: started"); TRC_LEAVE(""); } DpaTransfer::DpaTransferStatus DpaTransfer::ProcessStatus() { TRC_ENTER(""); std::lock_guard<std::mutex> lck(m_statusMutex); // changes m_status, does not care about remains // todo: refactor and rename - two functions CheckTimeout(); TRC_LEAVE(""); return m_status; } int32_t DpaTransfer::CheckTimeout() { int32_t remains(0); if (m_status == kCreated) { TRC_INF("Transfer status: created"); return remains; } if (m_status == kAborted) { TRC_INF("Transfer status: aborted"); return remains; } bool timingFinished(false); // infinite (0) is out of this statement if (m_expectedDurationMs > 0) { // passed time from sent request auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now() - m_startTime); remains = m_expectedDurationMs - duration.count(); TRC_DBG("Time to wait: " << PAR(remains)); // already over? timingFinished = remains < 0; } // not yet set and yes time is over // processed or timeouted can be set only after finished timing if (m_status != kProcessed && m_status != kTimeout) { if (timingFinished) { // and we have received confirmation for broadcast or response if (m_status == kConfirmationBroadcast || m_status == kReceivedResponse) { SetStatus(kProcessed); TRC_INF("Transfer status: processed"); } else { SetStatus(kTimeout); TRC_INF("Transfer status: timeout"); } } } // time to wait return remains; } bool DpaTransfer::IsInProgress() { return IsInProgressStatus(ProcessStatus()); } bool DpaTransfer::IsInProgress(int32_t& expectedDuration) { TRC_ENTER(""); std::lock_guard<std::mutex> lck(m_statusMutex); expectedDuration = CheckTimeout(); return IsInProgressStatus(m_status); TRC_LEAVE(""); } bool DpaTransfer::IsInProgressStatus(DpaTransferStatus status) { switch (status) { case kSent: case kSentCoordinator: case kConfirmation: case kConfirmationBroadcast: case kReceivedResponse: return true; // kCreated, kProcessed, kTimeout, kAbort, kError default: return false; } } void DpaTransfer::Abort() { std::lock_guard<std::mutex> lck(m_statusMutex); m_status = kAborted; } void DpaTransfer::SetStatus(DpaTransfer::DpaTransferStatus status) { m_status = status; } <|endoftext|>
<commit_before>#include "sample_protocol.h" #include "snapl/dispatcher.h" #include "snapl/net/inbox.h" #include "snapl/net/outbox.h" #include "connection_acceptor.h" int main( int argc, char **argv ) { short port( 9000 ); sample_protocol_c sample_protocol( port ); queue_c< server_message_c > request_queue; queue_c< server_message_c > response_queue; queue_c< server_message_c > complete_queue; connection_acceptor_c acceptor; inbox_c inbox( acceptor, request_queue, complete_queue ); dispatcher_c dispatch( request_queue, response_queue ); outbox_c outbox( response_queue, complete_queue ); dispatch.add( sample_protocol ); for (;;) { inbox.iterate(); dispatch.iterate(); outbox.iterate(); } return 0; } <commit_msg>set the sample app to listen on the given port<commit_after>#include "sample_protocol.h" #include "snapl/dispatcher.h" #include "snapl/net/inbox.h" #include "snapl/net/outbox.h" #include "connection_acceptor.h" int main( int argc, char **argv ) { short port( 9000 ); sample_protocol_c sample_protocol( port ); queue_c< server_message_c > request_queue; queue_c< server_message_c > response_queue; queue_c< server_message_c > complete_queue; connection_acceptor_c acceptor; inbox_c inbox( acceptor, request_queue, complete_queue ); dispatcher_c dispatch( request_queue, response_queue ); outbox_c outbox( response_queue, complete_queue ); inbox.listen( port ); dispatch.add( sample_protocol ); for (;;) { inbox.iterate(); dispatch.iterate(); outbox.iterate(); } return 0; } <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * Copyright (c) 1999-2000 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 "Xerces" 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/>. */ /** * $Log$ * Revision 1.6 2000/02/06 07:47:33 rahulj * Year 2K copyright swat. * * Revision 1.5 2000/02/04 01:49:26 aruna1 * TreeWalker and NodeIterator changes * * Revision 1.4 1999/11/30 21:16:25 roddey * Changes to add the transcode() method to DOMString, which returns a transcoded * version (to local code page) of the DOM string contents. And I changed all of the * exception 'throw by pointer' to 'throw by value' style. * * Revision 1.3 1999/11/23 01:48:16 rahulj * Changed 0L to 0. CC under HPUX is happy now. * * Revision 1.2 1999/11/20 00:56:39 rahulj * Source files must end with an un-escaped newline. * * Revision 1.1.1.1 1999/11/09 01:09:15 twl * Initial checkin * * Revision 1.2 1999/11/08 20:44:30 rahul * Swat for adding in Product name and CVS comment log variable. * */ // NodeIteratorImpl.cpp: implementation of the NodeIteratorImpl class. // ////////////////////////////////////////////////////////////////////// #include "NodeIteratorImpl.hpp" #include "DOM_Document.hpp" #include "DOM_DOMException.hpp" #include "DocumentImpl.hpp" ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// NodeIteratorImpl::NodeIteratorImpl () : fDetached(false), fNodeFilter(0) { } NodeIteratorImpl::~NodeIteratorImpl () { fDetached = false; } void NodeIteratorImpl::detach () { fDetached = true; } NodeIteratorImpl::NodeIteratorImpl ( DOM_Node root, unsigned long whatToShow, DOM_NodeFilter* nodeFilter, bool expandEntityRef) : fDetached(false), fRoot(root), fCurrentNode(0), fWhatToShow(whatToShow), fNodeFilter(nodeFilter), fForward(true), fExpandEntityReferences(expandEntityRef) { } NodeIteratorImpl::NodeIteratorImpl ( const NodeIteratorImpl& toCopy) : fDetached(toCopy.fDetached), fRoot(toCopy.fRoot), fCurrentNode(toCopy.fCurrentNode), fWhatToShow(toCopy.fWhatToShow), fNodeFilter(toCopy.fNodeFilter), fForward(toCopy.fForward), fExpandEntityReferences(toCopy.fExpandEntityReferences) { } NodeIteratorImpl& NodeIteratorImpl::operator= (const NodeIteratorImpl& other) { fRoot = other.fRoot; fCurrentNode = other.fRoot; fWhatToShow = other.fWhatToShow; fNodeFilter = other.fNodeFilter; fForward = other.fForward; fDetached = other.fDetached; fExpandEntityReferences = other.fExpandEntityReferences; return *this; } // Implementation Note: Note that the iterator looks at whatToShow // and filter values at each call, and therefore one _could_ add // setters for these values and alter them while iterating! /** Return the whatToShow value */ unsigned long NodeIteratorImpl::getWhatToShow () { return fWhatToShow; } /** Return the filter */ DOM_NodeFilter* NodeIteratorImpl::getFilter () { return fNodeFilter; } /** Get the expandEntity reference flag. */ bool NodeIteratorImpl::getExpandEntityReferences() { return fExpandEntityReferences; } /** Return the next DOM_Node in the Iterator. The node is the next node in * depth-first order which also passes the filter, and whatToShow. * A null return means either that */ DOM_Node NodeIteratorImpl::nextNode () { if (fDetached) throw DOM_DOMException(DOM_DOMException::INVALID_STATE_ERR, null); DOM_Node result; // if root is null there is no next node. if (fRoot.isNull()) return result; DOM_Node aNextNode = fCurrentNode; bool accepted = false; // the next node has not been accepted. while (!accepted) { // if last direction is not forward, repeat node. if (!fForward && !aNextNode.isNull()) { //System.out.println("nextNode():!fForward:"+fCurrentNode.getNodeName()); aNextNode = fCurrentNode; } else { // else get the next node via depth-first aNextNode = nextNode(aNextNode, true); } fForward = true; //REVIST: should direction be set forward before null check? // nothing in the list. return null. if (aNextNode.isNull()) return result; // does node pass the filters and whatToShow? accepted = acceptNode(aNextNode); if (accepted) { // if so, then the node is the current node. fCurrentNode = aNextNode; return fCurrentNode; } } // no nodes, or no accepted nodes. return result; } /** Return the previous Node in the Iterator. The node is the next node in * _backwards_ depth-first order which also passes the filter, and whatToShow. */ DOM_Node NodeIteratorImpl::previousNode () { if (fDetached) throw DOM_DOMException(DOM_DOMException::INVALID_STATE_ERR, null); DOM_Node result; // if the root is null, or the current node is null, return null. if (fRoot.isNull() || fCurrentNode.isNull()) return result; DOM_Node aPreviousNode = fCurrentNode; bool accepted = false; while (!accepted) { if (fForward && ! aPreviousNode.isNull()) { //repeat last node. aPreviousNode = fCurrentNode; } else { // get previous node in backwards depth first order. aPreviousNode = previousNode(aPreviousNode); } // we are going backwards fForward = false; // if the new previous node is null, we're at head or past the root, // so return null. if (aPreviousNode.isNull()) return result; // check if node passes filters and whatToShow. accepted = acceptNode(aPreviousNode); if (accepted) { // if accepted, update the current node, and return it. fCurrentNode = aPreviousNode; return fCurrentNode; } } // there are no nodes? return result; } /** The node is accepted if it passes the whatToShow and the filter. */ bool NodeIteratorImpl::acceptNode (DOM_Node node) { if (fDetached) throw DOM_DOMException(DOM_DOMException::INVALID_STATE_ERR, null); if (fNodeFilter == 0) { return ((fWhatToShow & ((1 << node.getNodeType()) - 1)) != 0); } else { return ((fWhatToShow & ((1 << node.getNodeType()) - 1)) != 0 ) && fNodeFilter->acceptNode(node) == DOM_NodeFilter::FILTER_ACCEPT; } } /** Return node, if matches or any parent if matches. */ DOM_Node NodeIteratorImpl::matchNodeOrParent (DOM_Node node) { DOM_Node result; for (DOM_Node n = node; n != fRoot; n = n.getParentNode()) { if (node == n) return n; } return result; } /** The method nextNode(DOM_Node, bool) returns the next node * from the actual DOM tree. * * The bool visitChildren determines whether to visit the children. * The result is the nextNode. */ DOM_Node NodeIteratorImpl::nextNode (DOM_Node node, bool visitChildren) { if (fDetached) throw DOM_DOMException(DOM_DOMException::INVALID_STATE_ERR, null); if (node.isNull()) return fRoot; DOM_Node result; // only check children if we visit children. if (visitChildren) { //if hasChildren, return 1st child. if (node.hasChildNodes()) { result = node.getFirstChild(); return result; } } // if hasSibling, return sibling result = node.getNextSibling(); if (! result.isNull()) return result; // return parent's 1st sibling. DOM_Node parent = node.getParentNode(); while (!parent.isNull() && parent != fRoot) { result = parent.getNextSibling(); if (!result.isNull()) { return result; } else { parent = parent.getParentNode(); } } // while (parent != null && parent != fRoot) { // end of list, return null DOM_Node aNull; return aNull; } /** The method previousNode(DOM_Node) returns the previous node * from the actual DOM tree. */ DOM_Node NodeIteratorImpl::previousNode (DOM_Node node) { if (fDetached) throw DOM_DOMException(DOM_DOMException::INVALID_STATE_ERR, null); DOM_Node result; // if we're at the root, return null. if (node == fRoot) return result; // get sibling result = node.getPreviousSibling(); if (result.isNull()) { //if 1st sibling, return parent result = node.getParentNode(); return result; } // if sibling has children, keep getting last child of child. if (result.hasChildNodes()) { while (result.hasChildNodes()) { result = result.getLastChild(); } } return result; } /** Fix-up the iterator on a remove. Called by DOM or otherwise, * before an actual DOM remove. */ void NodeIteratorImpl::removeNode (DOM_Node node) { if (fDetached) throw DOM_DOMException(DOM_DOMException::INVALID_STATE_ERR, null); // Implementation note: Fix-up means setting the current node properly // after a remove. if (node.isNull()) return; DOM_Node deleted = matchNodeOrParent(node); if (deleted.isNull()) return; if (fForward) { fCurrentNode = previousNode(deleted); } else // if (!fForward) { DOM_Node next = nextNode(deleted, false); if (! next.isNull()) { // normal case: there _are_ nodes following this in the iterator. fCurrentNode = next; } else { // the last node in the iterator is to be removed, // so we set the current node to be the previous one. fCurrentNode = previousNode(deleted); fForward = true; } } } void NodeIteratorImpl::unreferenced() { DOM_Document doc = fRoot.getOwnerDocument(); DocumentImpl* impl; if (! doc.isNull()) { impl = (DocumentImpl *) doc.fImpl; } else impl = (DocumentImpl *) fRoot.fImpl; if (impl->iterators != 0L) { int i; int sz = impl->iterators->size(); for (i = 0; i < sz; i++) if (impl->iterators->elementAt(i) == this) { impl->iterators->removeElementAt(i); break; } } delete this; } <commit_msg>nodeIterator previous tracking problem solved<commit_after>/* * The Apache Software License, Version 1.1 * * Copyright (c) 1999-2000 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 "Xerces" 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/>. */ /** * $Log$ * Revision 1.7 2000/02/08 01:16:18 aruna1 * nodeIterator previous tracking problem solved * * Revision 1.6 2000/02/06 07:47:33 rahulj * Year 2K copyright swat. * * Revision 1.5 2000/02/04 01:49:26 aruna1 * TreeWalker and NodeIterator changes * * Revision 1.4 1999/11/30 21:16:25 roddey * Changes to add the transcode() method to DOMString, which returns a transcoded * version (to local code page) of the DOM string contents. And I changed all of the * exception 'throw by pointer' to 'throw by value' style. * * Revision 1.3 1999/11/23 01:48:16 rahulj * Changed 0L to 0. CC under HPUX is happy now. * * Revision 1.2 1999/11/20 00:56:39 rahulj * Source files must end with an un-escaped newline. * * Revision 1.1.1.1 1999/11/09 01:09:15 twl * Initial checkin * * Revision 1.2 1999/11/08 20:44:30 rahul * Swat for adding in Product name and CVS comment log variable. * */ // NodeIteratorImpl.cpp: implementation of the NodeIteratorImpl class. // ////////////////////////////////////////////////////////////////////// #include "NodeIteratorImpl.hpp" #include "DOM_Document.hpp" #include "DOM_DOMException.hpp" #include "DocumentImpl.hpp" ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// NodeIteratorImpl::NodeIteratorImpl () : fDetached(false), fNodeFilter(0) { } NodeIteratorImpl::~NodeIteratorImpl () { fDetached = false; } void NodeIteratorImpl::detach () { fDetached = true; } NodeIteratorImpl::NodeIteratorImpl ( DOM_Node root, unsigned long whatToShow, DOM_NodeFilter* nodeFilter, bool expandEntityRef) : fDetached(false), fRoot(root), fCurrentNode(0), fWhatToShow(whatToShow), fNodeFilter(nodeFilter), fForward(true), fExpandEntityReferences(expandEntityRef) { } NodeIteratorImpl::NodeIteratorImpl ( const NodeIteratorImpl& toCopy) : fDetached(toCopy.fDetached), fRoot(toCopy.fRoot), fCurrentNode(toCopy.fCurrentNode), fWhatToShow(toCopy.fWhatToShow), fNodeFilter(toCopy.fNodeFilter), fForward(toCopy.fForward), fExpandEntityReferences(toCopy.fExpandEntityReferences) { } NodeIteratorImpl& NodeIteratorImpl::operator= (const NodeIteratorImpl& other) { fRoot = other.fRoot; fCurrentNode = other.fRoot; fWhatToShow = other.fWhatToShow; fNodeFilter = other.fNodeFilter; fForward = other.fForward; fDetached = other.fDetached; fExpandEntityReferences = other.fExpandEntityReferences; return *this; } // Implementation Note: Note that the iterator looks at whatToShow // and filter values at each call, and therefore one _could_ add // setters for these values and alter them while iterating! /** Return the whatToShow value */ unsigned long NodeIteratorImpl::getWhatToShow () { return fWhatToShow; } /** Return the filter */ DOM_NodeFilter* NodeIteratorImpl::getFilter () { return fNodeFilter; } /** Get the expandEntity reference flag. */ bool NodeIteratorImpl::getExpandEntityReferences() { return fExpandEntityReferences; } /** Return the next DOM_Node in the Iterator. The node is the next node in * depth-first order which also passes the filter, and whatToShow. * A null return means either that */ DOM_Node NodeIteratorImpl::nextNode () { if (fDetached) throw DOM_DOMException(DOM_DOMException::INVALID_STATE_ERR, null); DOM_Node result; // if root is null there is no next node. if (fRoot.isNull()) return result; DOM_Node aNextNode = fCurrentNode; bool accepted = false; // the next node has not been accepted. while (!accepted) { // if last direction is not forward, repeat node. if (!fForward && !aNextNode.isNull()) { //System.out.println("nextNode():!fForward:"+fCurrentNode.getNodeName()); aNextNode = fCurrentNode; } else { // else get the next node via depth-first aNextNode = nextNode(aNextNode, true); } fForward = true; //REVIST: should direction be set forward before null check? // nothing in the list. return null. if (aNextNode.isNull()) return result; // does node pass the filters and whatToShow? accepted = acceptNode(aNextNode); if (accepted) { // if so, then the node is the current node. fCurrentNode = aNextNode; return fCurrentNode; } } // no nodes, or no accepted nodes. return result; } /** Return the previous Node in the Iterator. The node is the next node in * _backwards_ depth-first order which also passes the filter, and whatToShow. */ DOM_Node NodeIteratorImpl::previousNode () { if (fDetached) throw DOM_DOMException(DOM_DOMException::INVALID_STATE_ERR, null); DOM_Node result; // if the root is null, or the current node is null, return null. if (fRoot.isNull() || fCurrentNode.isNull()) return result; DOM_Node aPreviousNode = fCurrentNode; bool accepted = false; while (!accepted) { // we are going backwards fForward = false; if (fForward && ! aPreviousNode.isNull()) { //repeat last node. aPreviousNode = fCurrentNode; } else { // get previous node in backwards depth first order. aPreviousNode = previousNode(aPreviousNode); } // if the new previous node is null, we're at head or past the root, // so return null. if (aPreviousNode.isNull()) return result; // check if node passes filters and whatToShow. accepted = acceptNode(aPreviousNode); if (accepted) { // if accepted, update the current node, and return it. fCurrentNode = aPreviousNode; return fCurrentNode; } } // there are no nodes? return result; } /** The node is accepted if it passes the whatToShow and the filter. */ bool NodeIteratorImpl::acceptNode (DOM_Node node) { if (fDetached) throw DOM_DOMException(DOM_DOMException::INVALID_STATE_ERR, null); if (fNodeFilter == 0) { return ((fWhatToShow & ((1 << node.getNodeType()) - 1)) != 0); } else { return ((fWhatToShow & ((1 << node.getNodeType()) - 1)) != 0 ) && fNodeFilter->acceptNode(node) == DOM_NodeFilter::FILTER_ACCEPT; } } /** Return node, if matches or any parent if matches. */ DOM_Node NodeIteratorImpl::matchNodeOrParent (DOM_Node node) { DOM_Node result; for (DOM_Node n = node; n != fRoot; n = n.getParentNode()) { if (node == n) return n; } return result; } /** The method nextNode(DOM_Node, bool) returns the next node * from the actual DOM tree. * * The bool visitChildren determines whether to visit the children. * The result is the nextNode. */ DOM_Node NodeIteratorImpl::nextNode (DOM_Node node, bool visitChildren) { if (fDetached) throw DOM_DOMException(DOM_DOMException::INVALID_STATE_ERR, null); if (node.isNull()) return fRoot; DOM_Node result; // only check children if we visit children. if (visitChildren) { //if hasChildren, return 1st child. if (node.hasChildNodes()) { result = node.getFirstChild(); return result; } } // if hasSibling, return sibling result = node.getNextSibling(); if (! result.isNull()) return result; // return parent's 1st sibling. DOM_Node parent = node.getParentNode(); while (!parent.isNull() && parent != fRoot) { result = parent.getNextSibling(); if (!result.isNull()) { return result; } else { parent = parent.getParentNode(); } } // while (parent != null && parent != fRoot) { // end of list, return null DOM_Node aNull; return aNull; } /** The method previousNode(DOM_Node) returns the previous node * from the actual DOM tree. */ DOM_Node NodeIteratorImpl::previousNode (DOM_Node node) { if (fDetached) throw DOM_DOMException(DOM_DOMException::INVALID_STATE_ERR, null); DOM_Node result; // if we're at the root, return null. if (node == fRoot) return result; // get sibling result = node.getPreviousSibling(); if (result.isNull()) { //if 1st sibling, return parent result = node.getParentNode(); return result; } // if sibling has children, keep getting last child of child. if (result.hasChildNodes()) { while (result.hasChildNodes()) { result = result.getLastChild(); } } return result; } /** Fix-up the iterator on a remove. Called by DOM or otherwise, * before an actual DOM remove. */ void NodeIteratorImpl::removeNode (DOM_Node node) { if (fDetached) throw DOM_DOMException(DOM_DOMException::INVALID_STATE_ERR, null); // Implementation note: Fix-up means setting the current node properly // after a remove. if (node.isNull()) return; DOM_Node deleted = matchNodeOrParent(node); if (deleted.isNull()) return; if (fForward) { fCurrentNode = previousNode(deleted); } else // if (!fForward) { DOM_Node next = nextNode(deleted, false); if (! next.isNull()) { // normal case: there _are_ nodes following this in the iterator. fCurrentNode = next; } else { // the last node in the iterator is to be removed, // so we set the current node to be the previous one. fCurrentNode = previousNode(deleted); fForward = true; } } } void NodeIteratorImpl::unreferenced() { DOM_Document doc = fRoot.getOwnerDocument(); DocumentImpl* impl; if (! doc.isNull()) { impl = (DocumentImpl *) doc.fImpl; } else impl = (DocumentImpl *) fRoot.fImpl; if (impl->iterators != 0L) { int i; int sz = impl->iterators->size(); for (i = 0; i < sz; i++) if (impl->iterators->elementAt(i) == this) { impl->iterators->removeElementAt(i); break; } } delete this; } <|endoftext|>
<commit_before>#include "sslpkix/iosink.h" namespace sslpkix { IoSink& operator<<(IoSink& sink, const std::string& str) { const size_t total_size = str.length(); const char *buf = str.data(); const char *current = buf; size_t written_size = 0; int ret = 0; do { ret = BIO_write(sink.handle(), current, total_size - written_size); if (ret > 0) { current += ret; written_size += static_cast<size_t>(ret); } } while (ret > 0 && written_size < total_size); if (ret == 0 || ret == -1) throw std::ios_base::failure("BIO_write failed"); else if (ret == -2) throw std::ios_base::failure("BIO_write is not implemented for this BIO"); // TODO: Need to check result? 1=success, 0 or -1=failure ret = BIO_flush(sink.handle()); return sink; } IoSink& operator>>(IoSink& sink, std::string& str) { char buf[1024]; int ret = 0; do { ret = BIO_read(sink.handle(), buf, sizeof(buf)); if (ret > 0) str.append(buf, ret); } while (ret > 0); if (ret == -1) throw std::ios_base::failure("BIO_read failed"); else if (ret == -2) throw std::ios_base::failure("BIO_read is not implemented for this BIO"); return sink; } std::ostream& operator<<(std::ostream& stream, IoSink& sink) { char buf[1024]; int ret = 0; do { ret = BIO_read(sink.handle(), buf, sizeof(buf)-1); if (ret > 0) { buf[ret] = '\0'; stream << buf; } } while (ret > 0); if (ret == -1) ; // EOF? else if (ret == -2) throw std::ios_base::failure("BIO_read is not implemented for this BIO"); return stream; } std::istream& operator>>(std::istream& stream, IoSink& sink) { char buf[1024]; int ret = 0; while (!stream.eof()) { stream.read(buf, sizeof(buf)); ret = BIO_write(sink.handle(), buf, stream.gcount()); // BIO_write must succeed writing the exact amount of bytes we pass to it. if (ret == 0 || ret == -1) throw std::ios_base::failure("BIO_write failed"); else if (ret == -2) throw std::ios_base::failure("BIO_write is not implemented for this BIO"); } // TODO: Need to check result? 1=success, 0 or -1=failure ret = BIO_flush(sink.handle()); return stream; } } // namespace sslpkix <commit_msg>BIO_read: A return of -1 is not necessarily an indication of error.<commit_after>#include "sslpkix/iosink.h" namespace sslpkix { IoSink& operator<<(IoSink& sink, const std::string& str) { const size_t total_size = str.length(); const char *buf = str.data(); const char *current = buf; size_t written_size = 0; int ret = 0; do { ret = BIO_write(sink.handle(), current, total_size - written_size); if (ret > 0) { current += ret; written_size += static_cast<size_t>(ret); } } while (ret > 0 && written_size < total_size); if (ret == 0 || ret == -1) throw std::ios_base::failure("BIO_write failed"); else if (ret == -2) throw std::ios_base::failure("BIO_write is not implemented for this BIO"); // TODO: Need to check result? 1=success, 0 or -1=failure ret = BIO_flush(sink.handle()); return sink; } IoSink& operator>>(IoSink& sink, std::string& str) { char buf[1024]; int ret = 0; do { ret = BIO_read(sink.handle(), buf, sizeof(buf)); if (ret > 0) str.append(buf, ret); } while (ret > 0); // man BIO_read - http://www.manpagez.com/man/3/BIO_read/ // NOTES // A 0 or -1 return is not necessarily an indication of an error. In // particular when the source/sink is non-blocking or of a certain type it // may merely be an indication that no data is currently available and // that the application should retry the operation later. if (ret == -1) ; // EOF? else if (ret == -2) throw std::ios_base::failure("BIO_read is not implemented for this BIO"); return sink; } std::ostream& operator<<(std::ostream& stream, IoSink& sink) { char buf[1024]; int ret = 0; do { ret = BIO_read(sink.handle(), buf, sizeof(buf)-1); if (ret > 0) { buf[ret] = '\0'; stream << buf; } } while (ret > 0); if (ret == -1) ; // EOF? else if (ret == -2) throw std::ios_base::failure("BIO_read is not implemented for this BIO"); return stream; } std::istream& operator>>(std::istream& stream, IoSink& sink) { char buf[1024]; int ret = 0; while (!stream.eof()) { stream.read(buf, sizeof(buf)); ret = BIO_write(sink.handle(), buf, stream.gcount()); // BIO_write must succeed writing the exact amount of bytes we pass to it. if (ret == 0 || ret == -1) throw std::ios_base::failure("BIO_write failed"); else if (ret == -2) throw std::ios_base::failure("BIO_write is not implemented for this BIO"); } // TODO: Need to check result? 1=success, 0 or -1=failure ret = BIO_flush(sink.handle()); return stream; } } // namespace sslpkix <|endoftext|>
<commit_before><commit_msg>missing pointer check in new multiline input code, fdo#43856<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: colrowba.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: hr $ $Date: 2004-02-03 12:37:08 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef SC_COLROWBAR_HXX #define SC_COLROWBAR_HXX #ifndef SC_HDRCONT_HXX #include "hdrcont.hxx" #endif #ifndef SC_VIEWDATA_HXX #include "viewdata.hxx" #endif class ScHeaderFunctionSet; class ScHeaderSelectionEngine; // --------------------------------------------------------------------------- class ScColBar : public ScHeaderControl { ScViewData* pViewData; ScHSplitPos eWhich; ScHeaderFunctionSet* pFuncSet; ScHeaderSelectionEngine* pSelEngine; public: ScColBar( Window* pParent, ScViewData* pData, ScHSplitPos eWhichPos, ScHeaderFunctionSet* pFunc, ScHeaderSelectionEngine* pEng ); ~ScColBar(); virtual USHORT GetPos(); virtual USHORT GetEntrySize( USHORT nEntryNo ); virtual String GetEntryText( USHORT nEntryNo ); virtual BOOL IsLayoutRTL(); // only for columns virtual void SetEntrySize( USHORT nPos, USHORT nNewSize ); virtual void HideEntries( USHORT nStart, USHORT nEnd ); virtual void SetMarking( BOOL bSet ); virtual void SelectWindow(); virtual BOOL IsDisabled(); virtual BOOL ResizeAllowed(); virtual void DrawInvert( long nDragPos ); virtual String GetDragHelp( long nVal ); }; class ScRowBar : public ScHeaderControl { ScViewData* pViewData; ScVSplitPos eWhich; ScHeaderFunctionSet* pFuncSet; ScHeaderSelectionEngine* pSelEngine; public: ScRowBar( Window* pParent, ScViewData* pData, ScVSplitPos eWhichPos, ScHeaderFunctionSet* pFunc, ScHeaderSelectionEngine* pEng ); ~ScRowBar(); virtual USHORT GetPos(); virtual USHORT GetEntrySize( USHORT nEntryNo ); virtual String GetEntryText( USHORT nEntryNo ); virtual BOOL IsMirrored(); // only for columns virtual USHORT GetHiddenCount( USHORT nEntryNo ); // only for columns virtual void SetEntrySize( USHORT nPos, USHORT nNewSize ); virtual void HideEntries( USHORT nStart, USHORT nEnd ); virtual void SetMarking( BOOL bSet ); virtual void SelectWindow(); virtual BOOL IsDisabled(); virtual BOOL ResizeAllowed(); virtual void DrawInvert( long nDragPos ); virtual String GetDragHelp( long nVal ); }; #endif <commit_msg>INTEGRATION: CWS rowlimit (1.2.12); FILE MERGED 2004/02/26 19:13:39 jmarmion 1.2.12.1: #i1967# setp 5 changes.<commit_after>/************************************************************************* * * $RCSfile: colrowba.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: obo $ $Date: 2004-06-04 11:30:53 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef SC_COLROWBAR_HXX #define SC_COLROWBAR_HXX #ifndef SC_HDRCONT_HXX #include "hdrcont.hxx" #endif #ifndef SC_VIEWDATA_HXX #include "viewdata.hxx" #endif class ScHeaderFunctionSet; class ScHeaderSelectionEngine; // --------------------------------------------------------------------------- class ScColBar : public ScHeaderControl { ScViewData* pViewData; ScHSplitPos eWhich; ScHeaderFunctionSet* pFuncSet; ScHeaderSelectionEngine* pSelEngine; public: ScColBar( Window* pParent, ScViewData* pData, ScHSplitPos eWhichPos, ScHeaderFunctionSet* pFunc, ScHeaderSelectionEngine* pEng ); ~ScColBar(); virtual SCCOLROW GetPos(); virtual USHORT GetEntrySize( SCCOLROW nEntryNo ); virtual String GetEntryText( SCCOLROW nEntryNo ); virtual BOOL IsLayoutRTL(); // only for columns virtual void SetEntrySize( SCCOLROW nPos, USHORT nNewSize ); virtual void HideEntries( SCCOLROW nStart, SCCOLROW nEnd ); virtual void SetMarking( BOOL bSet ); virtual void SelectWindow(); virtual BOOL IsDisabled(); virtual BOOL ResizeAllowed(); virtual void DrawInvert( long nDragPos ); virtual String GetDragHelp( long nVal ); }; class ScRowBar : public ScHeaderControl { ScViewData* pViewData; ScVSplitPos eWhich; ScHeaderFunctionSet* pFuncSet; ScHeaderSelectionEngine* pSelEngine; public: ScRowBar( Window* pParent, ScViewData* pData, ScVSplitPos eWhichPos, ScHeaderFunctionSet* pFunc, ScHeaderSelectionEngine* pEng ); ~ScRowBar(); virtual SCCOLROW GetPos(); virtual USHORT GetEntrySize( SCCOLROW nEntryNo ); virtual String GetEntryText( SCCOLROW nEntryNo ); virtual BOOL IsMirrored(); // only for columns virtual SCROW GetHiddenCount( SCROW nEntryNo ); // only for columns virtual void SetEntrySize( SCCOLROW nPos, USHORT nNewSize ); virtual void HideEntries( SCCOLROW nStart, SCCOLROW nEnd ); virtual void SetMarking( BOOL bSet ); virtual void SelectWindow(); virtual BOOL IsDisabled(); virtual BOOL ResizeAllowed(); virtual void DrawInvert( long nDragPos ); virtual String GetDragHelp( long nVal ); }; #endif <|endoftext|>
<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "indexcollection.h" #include "indexsearchablevisitor.h" #include <vespa/searchlib/queryeval/isourceselector.h> #include <vespa/searchlib/queryeval/create_blueprint_visitor_helper.h> #include <vespa/searchlib/queryeval/intermediate_blueprints.h> #include <vespa/searchlib/queryeval/leaf_blueprints.h> #include <vespa/log/log.h> LOG_SETUP(".searchcorespi.index.indexcollection"); using namespace search::queryeval; using namespace search::query; using search::attribute::IAttributeContext; namespace searchcorespi { IndexCollection::IndexCollection(const ISourceSelector::SP & selector) : _source_selector(selector), _sources() { } IndexCollection::IndexCollection(const ISourceSelector::SP & selector, const ISearchableIndexCollection &sources) : _source_selector(selector), _sources() { for (size_t i(0), m(sources.getSourceCount()); i < m; i++) { append(sources.getSourceId(i), sources.getSearchableSP(i)); } setCurrentIndex(sources.getCurrentIndex()); } IndexCollection::~IndexCollection() {} void IndexCollection::setSource(uint32_t docId) { assert( valid() ); _source_selector->setSource(docId, getCurrentIndex()); } ISearchableIndexCollection::UP IndexCollection::replaceAndRenumber(const ISourceSelector::SP & selector, const ISearchableIndexCollection &fsc, uint32_t id_diff, const IndexSearchable::SP &new_source) { ISearchableIndexCollection::UP new_fsc(new IndexCollection(selector)); new_fsc->append(0, new_source); for (size_t i = 0; i < fsc.getSourceCount(); ++i) { if (fsc.getSourceId(i) > id_diff) { new_fsc->append(fsc.getSourceId(i) - id_diff, fsc.getSearchableSP(i)); } } return new_fsc; } void IndexCollection::append(uint32_t id, const IndexSearchable::SP &fs) { _sources.push_back(SourceWithId(id, fs)); } IndexSearchable::SP IndexCollection::getSearchableSP(uint32_t i) const { return _sources[i].source_wrapper; } void IndexCollection::replace(uint32_t id, const IndexSearchable::SP &fs) { for (size_t i = 0; i < _sources.size(); ++i) { if (_sources[i].id == id) { _sources[i].source_wrapper = fs; return; } } LOG(warning, "Tried to replace Searchable %d, but it wasn't there.", id); append(id, fs); } const ISourceSelector & IndexCollection::getSourceSelector() const { return *_source_selector; } size_t IndexCollection::getSourceCount() const { return _sources.size(); } IndexSearchable & IndexCollection::getSearchable(uint32_t i) const { return *_sources[i].source_wrapper; } uint32_t IndexCollection::getSourceId(uint32_t i) const { return _sources[i].id; } search::SearchableStats IndexCollection::getSearchableStats() const { search::SearchableStats stats; for (size_t i = 0; i < _sources.size(); ++i) { stats.add(_sources[i].source_wrapper->getSearchableStats()); } return stats; } search::SerialNum IndexCollection::getSerialNum() const { search::SerialNum serialNum = 0; for (auto &source : _sources) { serialNum = std::max(serialNum, source.source_wrapper->getSerialNum()); } return serialNum; } void IndexCollection::accept(IndexSearchableVisitor &visitor) const { for (auto &source : _sources) { source.source_wrapper->accept(visitor); } } namespace { struct Mixer { const ISourceSelector &_selector; std::unique_ptr<SourceBlenderBlueprint> _blender; Mixer(const ISourceSelector &selector) : _selector(selector), _blender() {} void addIndex(Blueprint::UP index) { if (_blender.get() == NULL) { _blender.reset(new SourceBlenderBlueprint(_selector)); } _blender->addChild(std::move(index)); } Blueprint::UP mix() { if (_blender.get() == NULL) { return Blueprint::UP(new EmptyBlueprint()); } return Blueprint::UP(_blender.release()); } }; class CreateBlueprintVisitor : public search::query::QueryVisitor { private: const IIndexCollection &_indexes; const FieldSpecList &_fields; const IRequestContext &_requestContext; Blueprint::UP _result; template <typename NodeType> void visitTerm(NodeType &n) { Mixer mixer(_indexes.getSourceSelector()); for (size_t i = 0; i < _indexes.getSourceCount(); ++i) { Blueprint::UP blueprint = _indexes.getSearchable(i).createBlueprint(_requestContext, _fields, n); blueprint->setSourceId(_indexes.getSourceId(i)); mixer.addIndex(std::move(blueprint)); } _result = mixer.mix(); } void visit(And &) override { } void visit(AndNot &) override { } void visit(Or &) override { } void visit(WeakAnd &) override { } void visit(Equiv &) override { } void visit(Rank &) override { } void visit(Near &) override { } void visit(ONear &) override { } void visit(WeightedSetTerm &n) override { visitTerm(n); } void visit(DotProduct &n) override { visitTerm(n); } void visit(WandTerm &n) override { visitTerm(n); } void visit(Phrase &n) override { visitTerm(n); } void visit(SameElement &n) override { visitTerm(n); } void visit(NumberTerm &n) override { visitTerm(n); } void visit(LocationTerm &n) override { visitTerm(n); } void visit(PrefixTerm &n) override { visitTerm(n); } void visit(RangeTerm &n) override { visitTerm(n); } void visit(StringTerm &n) override { visitTerm(n); } void visit(SubstringTerm &n) override { visitTerm(n); } void visit(SuffixTerm &n) override { visitTerm(n); } void visit(PredicateQuery &n) override { visitTerm(n); } void visit(RegExpTerm &n) override { visitTerm(n); } public: CreateBlueprintVisitor(const IIndexCollection &indexes, const FieldSpecList &fields, const IRequestContext & requestContext) : _indexes(indexes), _fields(fields), _requestContext(requestContext), _result() {} Blueprint::UP getResult() { return std::move(_result); } }; } Blueprint::UP IndexCollection::createBlueprint(const IRequestContext & requestContext, const FieldSpec &field, const Node &term) { FieldSpecList fields; fields.add(field); return createBlueprint(requestContext, fields, term); } Blueprint::UP IndexCollection::createBlueprint(const IRequestContext & requestContext, const FieldSpecList &fields, const Node &term) { CreateBlueprintVisitor visitor(*this, fields, requestContext); const_cast<Node &>(term).accept(visitor); return visitor.getResult(); } } // namespace searchcorespi <commit_msg>SameEelemt is not a term.<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "indexcollection.h" #include "indexsearchablevisitor.h" #include <vespa/searchlib/queryeval/isourceselector.h> #include <vespa/searchlib/queryeval/create_blueprint_visitor_helper.h> #include <vespa/searchlib/queryeval/intermediate_blueprints.h> #include <vespa/searchlib/queryeval/leaf_blueprints.h> #include <vespa/log/log.h> LOG_SETUP(".searchcorespi.index.indexcollection"); using namespace search::queryeval; using namespace search::query; using search::attribute::IAttributeContext; namespace searchcorespi { IndexCollection::IndexCollection(const ISourceSelector::SP & selector) : _source_selector(selector), _sources() { } IndexCollection::IndexCollection(const ISourceSelector::SP & selector, const ISearchableIndexCollection &sources) : _source_selector(selector), _sources() { for (size_t i(0), m(sources.getSourceCount()); i < m; i++) { append(sources.getSourceId(i), sources.getSearchableSP(i)); } setCurrentIndex(sources.getCurrentIndex()); } IndexCollection::~IndexCollection() {} void IndexCollection::setSource(uint32_t docId) { assert( valid() ); _source_selector->setSource(docId, getCurrentIndex()); } ISearchableIndexCollection::UP IndexCollection::replaceAndRenumber(const ISourceSelector::SP & selector, const ISearchableIndexCollection &fsc, uint32_t id_diff, const IndexSearchable::SP &new_source) { ISearchableIndexCollection::UP new_fsc(new IndexCollection(selector)); new_fsc->append(0, new_source); for (size_t i = 0; i < fsc.getSourceCount(); ++i) { if (fsc.getSourceId(i) > id_diff) { new_fsc->append(fsc.getSourceId(i) - id_diff, fsc.getSearchableSP(i)); } } return new_fsc; } void IndexCollection::append(uint32_t id, const IndexSearchable::SP &fs) { _sources.push_back(SourceWithId(id, fs)); } IndexSearchable::SP IndexCollection::getSearchableSP(uint32_t i) const { return _sources[i].source_wrapper; } void IndexCollection::replace(uint32_t id, const IndexSearchable::SP &fs) { for (size_t i = 0; i < _sources.size(); ++i) { if (_sources[i].id == id) { _sources[i].source_wrapper = fs; return; } } LOG(warning, "Tried to replace Searchable %d, but it wasn't there.", id); append(id, fs); } const ISourceSelector & IndexCollection::getSourceSelector() const { return *_source_selector; } size_t IndexCollection::getSourceCount() const { return _sources.size(); } IndexSearchable & IndexCollection::getSearchable(uint32_t i) const { return *_sources[i].source_wrapper; } uint32_t IndexCollection::getSourceId(uint32_t i) const { return _sources[i].id; } search::SearchableStats IndexCollection::getSearchableStats() const { search::SearchableStats stats; for (size_t i = 0; i < _sources.size(); ++i) { stats.add(_sources[i].source_wrapper->getSearchableStats()); } return stats; } search::SerialNum IndexCollection::getSerialNum() const { search::SerialNum serialNum = 0; for (auto &source : _sources) { serialNum = std::max(serialNum, source.source_wrapper->getSerialNum()); } return serialNum; } void IndexCollection::accept(IndexSearchableVisitor &visitor) const { for (auto &source : _sources) { source.source_wrapper->accept(visitor); } } namespace { struct Mixer { const ISourceSelector &_selector; std::unique_ptr<SourceBlenderBlueprint> _blender; Mixer(const ISourceSelector &selector) : _selector(selector), _blender() {} void addIndex(Blueprint::UP index) { if (_blender.get() == NULL) { _blender.reset(new SourceBlenderBlueprint(_selector)); } _blender->addChild(std::move(index)); } Blueprint::UP mix() { if (_blender.get() == NULL) { return Blueprint::UP(new EmptyBlueprint()); } return Blueprint::UP(_blender.release()); } }; class CreateBlueprintVisitor : public search::query::QueryVisitor { private: const IIndexCollection &_indexes; const FieldSpecList &_fields; const IRequestContext &_requestContext; Blueprint::UP _result; template <typename NodeType> void visitTerm(NodeType &n) { Mixer mixer(_indexes.getSourceSelector()); for (size_t i = 0; i < _indexes.getSourceCount(); ++i) { Blueprint::UP blueprint = _indexes.getSearchable(i).createBlueprint(_requestContext, _fields, n); blueprint->setSourceId(_indexes.getSourceId(i)); mixer.addIndex(std::move(blueprint)); } _result = mixer.mix(); } void visit(And &) override { } void visit(AndNot &) override { } void visit(Or &) override { } void visit(WeakAnd &) override { } void visit(Equiv &) override { } void visit(Rank &) override { } void visit(Near &) override { } void visit(ONear &) override { } void visit(SameElement &) override { } void visit(WeightedSetTerm &n) override { visitTerm(n); } void visit(DotProduct &n) override { visitTerm(n); } void visit(WandTerm &n) override { visitTerm(n); } void visit(Phrase &n) override { visitTerm(n); } void visit(NumberTerm &n) override { visitTerm(n); } void visit(LocationTerm &n) override { visitTerm(n); } void visit(PrefixTerm &n) override { visitTerm(n); } void visit(RangeTerm &n) override { visitTerm(n); } void visit(StringTerm &n) override { visitTerm(n); } void visit(SubstringTerm &n) override { visitTerm(n); } void visit(SuffixTerm &n) override { visitTerm(n); } void visit(PredicateQuery &n) override { visitTerm(n); } void visit(RegExpTerm &n) override { visitTerm(n); } public: CreateBlueprintVisitor(const IIndexCollection &indexes, const FieldSpecList &fields, const IRequestContext & requestContext) : _indexes(indexes), _fields(fields), _requestContext(requestContext), _result() {} Blueprint::UP getResult() { return std::move(_result); } }; } Blueprint::UP IndexCollection::createBlueprint(const IRequestContext & requestContext, const FieldSpec &field, const Node &term) { FieldSpecList fields; fields.add(field); return createBlueprint(requestContext, fields, term); } Blueprint::UP IndexCollection::createBlueprint(const IRequestContext & requestContext, const FieldSpecList &fields, const Node &term) { CreateBlueprintVisitor visitor(*this, fields, requestContext); const_cast<Node &>(term).accept(visitor); return visitor.getResult(); } } // namespace searchcorespi <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: drawview.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2003-11-24 17:26:47 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef SC_DRAWVIEW_HXX #define SC_DRAWVIEW_HXX #ifndef _SVX_FMVIEW_HXX //autogen #include <svx/fmview.hxx> #endif #include "global.hxx" class ScDocument; class ScViewData; class SdrViewUserMarker; class ScDrawView: public FmFormView { ScViewData* pViewData; OutputDevice* pDev; //! noetig ? ScDocument* pDoc; USHORT nTab; Fraction aScaleX; // Faktor fuer Drawing-MapMode Fraction aScaleY; SdrViewUserMarker* pDropMarker; SdrObject* pDropMarkObj; BOOL bInConstruct; BOOL bDisableHdl; void Construct(); void UpdateBrowser(); protected: virtual void ModelHasChanged(); virtual void MakeVisible( const Rectangle& rRect, Window& rWin ); // add custom handles (used by other apps, e.g. AnchorPos) virtual void AddCustomHdl(); public: ScDrawView( OutputDevice* pOut, ScViewData* pData ); ScDrawView( OutputDevice* pOut, ScDocument* pDocument, USHORT nTable ); virtual ~ScDrawView(); virtual void MarkListHasChanged(); virtual void SFX_NOTIFY( SfxBroadcaster& rBC, const TypeId& rBCType, const SfxHint& rHint, const TypeId& rHintType ); void DrawMarks( OutputDevice* pOut ) const; void MarkDropObj( SdrObject* pObj ); BOOL IsDisableHdl() const { return bDisableHdl; } void SetMarkedToLayer( BYTE nLayerNo ); void InvalidateAttribs(); void InvalidateDrawTextAttrs(); BOOL BeginDrag( Window* pWindow, const Point& rStartPos ); void DoCut(); void DoCopy(); void GetScale( Fraction& rFractX, Fraction& rFractY ) const; void RecalcScale(); void UpdateWorkArea(); USHORT GetTab() const { return nTab; } void CalcNormScale( Fraction& rFractX, Fraction& rFractY ) const; // #110094#-17 Not used // void PaintObject( SdrObject* pObject, OutputDevice* pDev ) const; void SetAnchor( ScAnchorType ); ScAnchorType GetAnchor() const; void VCAddWin( Window* pWin ); void VCRemoveWin( Window* pWin ); void UpdateIMap( SdrObject* pObj ); USHORT GetPopupMenuId(); void UpdateUserViewOptions(); void SetMarkedOriginalSize(); BOOL SelectObject( const String& rName ); String GetSelectedChartName() const; BOOL HasMarkedControl() const; FASTBOOL InsertObjectSafe(SdrObject* pObj, SdrPageView& rPV, ULONG nOptions=0); SdrEndTextEditKind ScEndTextEdit(); // ruft SetDrawTextUndo(0) }; #endif <commit_msg>INTEGRATION: CWS rowlimit (1.3.28); FILE MERGED 2004/01/13 20:04:13 er 1.3.28.1: #i1967# SCCOL,SCROW,SCTAB replace USHORT; SCsCOL,SCsROW,SCsTAB replace short<commit_after>/************************************************************************* * * $RCSfile: drawview.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: obo $ $Date: 2004-06-04 11:32:40 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef SC_DRAWVIEW_HXX #define SC_DRAWVIEW_HXX #ifndef _SVX_FMVIEW_HXX //autogen #include <svx/fmview.hxx> #endif #include "global.hxx" class ScDocument; class ScViewData; class SdrViewUserMarker; class ScDrawView: public FmFormView { ScViewData* pViewData; OutputDevice* pDev; //! noetig ? ScDocument* pDoc; SCTAB nTab; Fraction aScaleX; // Faktor fuer Drawing-MapMode Fraction aScaleY; SdrViewUserMarker* pDropMarker; SdrObject* pDropMarkObj; BOOL bInConstruct; BOOL bDisableHdl; void Construct(); void UpdateBrowser(); protected: virtual void ModelHasChanged(); virtual void MakeVisible( const Rectangle& rRect, Window& rWin ); // add custom handles (used by other apps, e.g. AnchorPos) virtual void AddCustomHdl(); public: ScDrawView( OutputDevice* pOut, ScViewData* pData ); ScDrawView( OutputDevice* pOut, ScDocument* pDocument, SCTAB nTable ); virtual ~ScDrawView(); virtual void MarkListHasChanged(); virtual void SFX_NOTIFY( SfxBroadcaster& rBC, const TypeId& rBCType, const SfxHint& rHint, const TypeId& rHintType ); void DrawMarks( OutputDevice* pOut ) const; void MarkDropObj( SdrObject* pObj ); BOOL IsDisableHdl() const { return bDisableHdl; } void SetMarkedToLayer( BYTE nLayerNo ); void InvalidateAttribs(); void InvalidateDrawTextAttrs(); BOOL BeginDrag( Window* pWindow, const Point& rStartPos ); void DoCut(); void DoCopy(); void GetScale( Fraction& rFractX, Fraction& rFractY ) const; void RecalcScale(); void UpdateWorkArea(); SCTAB GetTab() const { return nTab; } void CalcNormScale( Fraction& rFractX, Fraction& rFractY ) const; // #110094#-17 Not used // void PaintObject( SdrObject* pObject, OutputDevice* pDev ) const; void SetAnchor( ScAnchorType ); ScAnchorType GetAnchor() const; void VCAddWin( Window* pWin ); void VCRemoveWin( Window* pWin ); void UpdateIMap( SdrObject* pObj ); USHORT GetPopupMenuId(); void UpdateUserViewOptions(); void SetMarkedOriginalSize(); BOOL SelectObject( const String& rName ); String GetSelectedChartName() const; BOOL HasMarkedControl() const; FASTBOOL InsertObjectSafe(SdrObject* pObj, SdrPageView& rPV, ULONG nOptions=0); SdrEndTextEditKind ScEndTextEdit(); // ruft SetDrawTextUndo(0) }; #endif <|endoftext|>
<commit_before>#pragma once //=====================================================================// /*! @file @brief 固定サイズ文字列クラス @author 平松邦仁 (hira@rvf-rc45.net) @copyright Copyright (C) 2017, 2020 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/RX/blob/master/LICENSE */ //=====================================================================// #include <algorithm> #include <cstring> #include <iterator> #include "common/string_utils.hpp" namespace utils { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief 固定サイズ文字列クラス @param[in] SIZE 文字列サイズ */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template <uint32_t SIZE> class fixed_string { uint32_t pos_; char str_[SIZE + 1]; public: //-----------------------------------------------------------------// /*! @brief コンストラクタ @param[in] str 初期設定文字列 */ //-----------------------------------------------------------------// fixed_string(const char* str = nullptr) noexcept : pos_(0) { if(str != nullptr) { utils::str::strncpy_(str_, str, SIZE); pos_ = std::strlen(str_); } str_[pos_] = 0; str_[SIZE] = 0; } //-----------------------------------------------------------------// /*! @brief 格納可能な最大サイズを返す(終端の数を除外) @return 格納可能な最大サイズ */ //-----------------------------------------------------------------// uint32_t capacity() const noexcept { return SIZE; } //-----------------------------------------------------------------// /*! @brief 現在のサイズを返す @return 現在のサイズ */ //-----------------------------------------------------------------// uint32_t size() const noexcept { return pos_; } //-----------------------------------------------------------------// /*! @brief 空か調べる @return 空の場合「true」 */ //-----------------------------------------------------------------// bool empty() const noexcept { return pos_ == 0; } //-----------------------------------------------------------------// /*! @brief 文字列をクリア(リセット) */ //-----------------------------------------------------------------// void clear() noexcept { pos_ = 0; str_[pos_] = 0; } //-----------------------------------------------------------------// /*! @brief 末尾の1要素を削除する。 */ //-----------------------------------------------------------------// void pop_back() noexcept { if(pos_ > 0) { --pos_; str_[pos_] = 0; } } //-----------------------------------------------------------------// /*! @brief 配列の先頭 @return 配列の先頭 */ //-----------------------------------------------------------------// const char* begin() const noexcept { return &str_[0]; } //-----------------------------------------------------------------// /*! @brief 配列の先頭 @return 配列の先頭 */ //-----------------------------------------------------------------// char* begin() noexcept { return &str_[0]; } //-----------------------------------------------------------------// /*! @brief 配列の終端 @return 配列の終端 */ //-----------------------------------------------------------------// const char* end() const noexcept { return &str_[pos_]; } //-----------------------------------------------------------------// /*! @brief 配列の終端 @return 配列の終端 */ //-----------------------------------------------------------------// char* end() noexcept { return &str_[pos_]; } //-----------------------------------------------------------------// /*! @brief 末尾要素への参照を取得する。 @return 末尾要素への参照 */ //-----------------------------------------------------------------// char& back() noexcept { auto pos = pos_; if(pos > 0) --pos; return str_[pos]; } //-----------------------------------------------------------------// /*! @brief 末尾要素への参照を取得する。 @return 末尾要素への参照 */ //-----------------------------------------------------------------// const char& back() const noexcept { auto pos = pos_; if(pos > 0) --pos; return str_[pos]; } //-----------------------------------------------------------------// /*! @brief 文字列を返す @return 文字列 */ //-----------------------------------------------------------------// const char* c_str() const noexcept { return str_; } //-----------------------------------------------------------------// /*! @brief 交換 @param[in] src ソース @return 自分 */ //-----------------------------------------------------------------// void swap(fixed_string& src) noexcept { std::swap(src.str_, str_); std::swap(src.pos_, pos_); } //-----------------------------------------------------------------// /*! @brief 代入 @param[in] src ソース @return 自分 */ //-----------------------------------------------------------------// fixed_string& operator = (const char* src) noexcept { utils::str::strncpy_(str_, src, SIZE); pos_ = std::strlen(str_); return *this; } //-----------------------------------------------------------------// /*! @brief 代入 @param[in] src ソース @return 自分 */ //-----------------------------------------------------------------// fixed_string& operator = (const fixed_string& src) noexcept { utils::str::strncpy_(str_, src.c_str(), SIZE); pos_ = src.pos_; return *this; } //-----------------------------------------------------------------// /*! @brief 文字を追加 @param[in] ch 文字 @return 自分 */ //-----------------------------------------------------------------// fixed_string& operator += (char ch) noexcept { if(pos_ < SIZE) { str_[pos_] = ch; ++pos_; str_[pos_] = 0; } return *this; } //-----------------------------------------------------------------// /*! @brief 文字列を追加 @param[in] str 文字列 @return 自分 */ //-----------------------------------------------------------------// fixed_string& operator += (const char* str) noexcept { if(str == nullptr) { return *this; } uint32_t l = std::strlen(str); if((pos_ + l) < SIZE) { std::strcpy(&str_[pos_], str); pos_ += l; } else { // バッファが許す範囲でコピー l = SIZE - pos_; utils::str::strncpy_(&str_[pos_], str, l); pos_ = SIZE; } str_[pos_] = 0; return *this; } //-----------------------------------------------------------------// /*! @brief 文字参照 @n ※範囲外ではテンポラリを返す(例外を投げない) @param[in] pos 配列位置 @return 文字 */ //-----------------------------------------------------------------// char& operator [] (uint32_t pos) noexcept { if(pos >= SIZE) { static char tmp = 0; return tmp; } return str_[pos]; } //-----------------------------------------------------------------// /*! @brief 文字参照 const @n ※範囲外ではテンポラリを返す(例外を投げない) @param[in] pos 配列位置 @return 文字 */ //-----------------------------------------------------------------// const char& operator [] (uint32_t pos) const noexcept { if(pos >= SIZE) { static char tmp = 0; return tmp; } return str_[pos]; } //-----------------------------------------------------------------// /*! @brief クラス一致比較 @param[in] th 文字列クラス @return 同じなら「true」 */ //-----------------------------------------------------------------// int cmp(const fixed_string& th) const noexcept { return std::strcmp(c_str(), th.c_str()); } //-----------------------------------------------------------------// /*! @brief クラス一致比較(オペレーター) @param[in] th 文字列クラス @return 同じなら「true」 */ //-----------------------------------------------------------------// bool operator == (const fixed_string& th) const noexcept { return std::strcmp(c_str(), th.c_str()) == 0; } //-----------------------------------------------------------------// /*! @brief クラス、不一致比較(オペレーター) @param[in] th 文字列クラス @return 同じなら「true」 */ //-----------------------------------------------------------------// bool operator != (const fixed_string& th) const noexcept { return std::strcmp(c_str(), th.c_str()) != 0; } //-----------------------------------------------------------------// /*! @brief クラス大小比較(オペレーター) @param[in] th 文字列クラス @return 大小なら「true」 */ //-----------------------------------------------------------------// bool operator > (const fixed_string& th) const noexcept { return std::strcmp(c_str(), th.c_str()) > 0; } //-----------------------------------------------------------------// /*! @brief クラス小大比較(オペレーター) @param[in] th 文字列クラス @return 小大なら「true」 */ //-----------------------------------------------------------------// bool operator < (const fixed_string& th) const noexcept { return std::strcmp(c_str(), th.c_str()) < 0; } //-----------------------------------------------------------------// /*! @brief クラス大小一致比較(オペレーター) @param[in] th 文字列 @return 大小一致なら「true」 */ //-----------------------------------------------------------------// bool operator >= (const fixed_string& th) const noexcept { return std::strcmp(c_str(), th.c_str()) >= 0; } //-----------------------------------------------------------------// /*! @brief クラス小大一致比較(オペレーター) @param[in] th 文字列クラス @return 小大一致なら「true」 */ //-----------------------------------------------------------------// bool operator <= (const fixed_string& th) const noexcept { return std::strcmp(c_str(), th.c_str()) <= 0; } }; typedef fixed_string<16> STR16; typedef fixed_string<32> STR32; typedef fixed_string<64> STR64; typedef fixed_string<128> STR128; typedef fixed_string<256> STR256; } <commit_msg>Update: add erase api<commit_after>#pragma once //=====================================================================// /*! @file @brief 固定サイズ文字列クラス @author 平松邦仁 (hira@rvf-rc45.net) @copyright Copyright (C) 2017, 2020 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/RX/blob/master/LICENSE */ //=====================================================================// #include <algorithm> #include <cstring> #include <iterator> #include "common/string_utils.hpp" namespace utils { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief 固定サイズ文字列クラス @param[in] SIZE 文字列サイズ */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template <uint32_t SIZE> class fixed_string { uint32_t pos_; char str_[SIZE + 1]; public: //-----------------------------------------------------------------// /*! @brief コンストラクタ @param[in] str 初期設定文字列 */ //-----------------------------------------------------------------// fixed_string(const char* str = nullptr) noexcept : pos_(0) { if(str != nullptr) { utils::str::strncpy_(str_, str, SIZE); pos_ = std::strlen(str_); } str_[pos_] = 0; str_[SIZE] = 0; } //-----------------------------------------------------------------// /*! @brief 格納可能な最大サイズを返す(終端の数を除外) @return 格納可能な最大サイズ */ //-----------------------------------------------------------------// uint32_t capacity() const noexcept { return SIZE; } //-----------------------------------------------------------------// /*! @brief 現在のサイズを返す @return 現在のサイズ */ //-----------------------------------------------------------------// uint32_t size() const noexcept { return pos_; } //-----------------------------------------------------------------// /*! @brief 空か調べる @return 空の場合「true」 */ //-----------------------------------------------------------------// bool empty() const noexcept { return pos_ == 0; } //-----------------------------------------------------------------// /*! @brief 文字列をクリア(リセット) */ //-----------------------------------------------------------------// void clear() noexcept { pos_ = 0; str_[pos_] = 0; } //-----------------------------------------------------------------// /*! @brief 末尾の1要素を削除する。 */ //-----------------------------------------------------------------// void pop_back() noexcept { if(pos_ > 0) { --pos_; str_[pos_] = 0; } } //-----------------------------------------------------------------// /*! @brief 要素を削除する。 @param[in] org 先頭位置 @param[in] num 個数 @return 自分 */ //-----------------------------------------------------------------// fixed_string& erase(uint32_t org, uint32_t num) noexcept { if(org < pos_ && (org + num) <= pos_) { for(auto i = org; i < (org + num); ++i) { str_[i] = str_[i + num]; } pos_ -= num; str_[pos_] = 0; } return *this; } //-----------------------------------------------------------------// /*! @brief 配列の先頭 @return 配列の先頭 */ //-----------------------------------------------------------------// const char* begin() const noexcept { return &str_[0]; } //-----------------------------------------------------------------// /*! @brief 配列の先頭 @return 配列の先頭 */ //-----------------------------------------------------------------// char* begin() noexcept { return &str_[0]; } //-----------------------------------------------------------------// /*! @brief 配列の終端 @return 配列の終端 */ //-----------------------------------------------------------------// const char* end() const noexcept { return &str_[pos_]; } //-----------------------------------------------------------------// /*! @brief 配列の終端 @return 配列の終端 */ //-----------------------------------------------------------------// char* end() noexcept { return &str_[pos_]; } //-----------------------------------------------------------------// /*! @brief 末尾要素への参照を取得する。 @return 末尾要素への参照 */ //-----------------------------------------------------------------// char& back() noexcept { auto pos = pos_; if(pos > 0) --pos; return str_[pos]; } //-----------------------------------------------------------------// /*! @brief 末尾要素への参照を取得する。 @return 末尾要素への参照 */ //-----------------------------------------------------------------// const char& back() const noexcept { auto pos = pos_; if(pos > 0) --pos; return str_[pos]; } //-----------------------------------------------------------------// /*! @brief 文字列を返す @return 文字列 */ //-----------------------------------------------------------------// const char* c_str() const noexcept { return str_; } //-----------------------------------------------------------------// /*! @brief 交換 @param[in] src ソース @return 自分 */ //-----------------------------------------------------------------// void swap(fixed_string& src) noexcept { std::swap(src.str_, str_); std::swap(src.pos_, pos_); } //-----------------------------------------------------------------// /*! @brief 代入 @param[in] src ソース @return 自分 */ //-----------------------------------------------------------------// fixed_string& operator = (const char* src) noexcept { utils::str::strncpy_(str_, src, SIZE); pos_ = std::strlen(str_); return *this; } //-----------------------------------------------------------------// /*! @brief 代入 @param[in] src ソース @return 自分 */ //-----------------------------------------------------------------// fixed_string& operator = (const fixed_string& src) noexcept { utils::str::strncpy_(str_, src.c_str(), SIZE); pos_ = src.pos_; return *this; } //-----------------------------------------------------------------// /*! @brief 文字を追加 @param[in] ch 文字 @return 自分 */ //-----------------------------------------------------------------// fixed_string& operator += (char ch) noexcept { if(pos_ < SIZE) { str_[pos_] = ch; ++pos_; str_[pos_] = 0; } return *this; } //-----------------------------------------------------------------// /*! @brief 文字列を追加 @param[in] str 文字列 @return 自分 */ //-----------------------------------------------------------------// fixed_string& operator += (const char* str) noexcept { if(str == nullptr) { return *this; } uint32_t l = std::strlen(str); if((pos_ + l) < SIZE) { std::strcpy(&str_[pos_], str); pos_ += l; } else { // バッファが許す範囲でコピー l = SIZE - pos_; utils::str::strncpy_(&str_[pos_], str, l); pos_ = SIZE; } str_[pos_] = 0; return *this; } //-----------------------------------------------------------------// /*! @brief 文字参照 @n ※範囲外ではテンポラリを返す(例外を投げない) @param[in] pos 配列位置 @return 文字 */ //-----------------------------------------------------------------// char& operator [] (uint32_t pos) noexcept { if(pos >= SIZE) { static char tmp = 0; return tmp; } return str_[pos]; } //-----------------------------------------------------------------// /*! @brief 文字参照 const @n ※範囲外ではテンポラリを返す(例外を投げない) @param[in] pos 配列位置 @return 文字 */ //-----------------------------------------------------------------// const char& operator [] (uint32_t pos) const noexcept { if(pos >= SIZE) { static char tmp = 0; return tmp; } return str_[pos]; } //-----------------------------------------------------------------// /*! @brief クラス一致比較 @param[in] th 文字列クラス @return 同じなら「true」 */ //-----------------------------------------------------------------// int cmp(const fixed_string& th) const noexcept { return std::strcmp(c_str(), th.c_str()); } //-----------------------------------------------------------------// /*! @brief クラス一致比較(オペレーター) @param[in] th 文字列クラス @return 同じなら「true」 */ //-----------------------------------------------------------------// bool operator == (const fixed_string& th) const noexcept { return std::strcmp(c_str(), th.c_str()) == 0; } //-----------------------------------------------------------------// /*! @brief クラス、不一致比較(オペレーター) @param[in] th 文字列クラス @return 同じなら「true」 */ //-----------------------------------------------------------------// bool operator != (const fixed_string& th) const noexcept { return std::strcmp(c_str(), th.c_str()) != 0; } //-----------------------------------------------------------------// /*! @brief クラス大小比較(オペレーター) @param[in] th 文字列クラス @return 大小なら「true」 */ //-----------------------------------------------------------------// bool operator > (const fixed_string& th) const noexcept { return std::strcmp(c_str(), th.c_str()) > 0; } //-----------------------------------------------------------------// /*! @brief クラス小大比較(オペレーター) @param[in] th 文字列クラス @return 小大なら「true」 */ //-----------------------------------------------------------------// bool operator < (const fixed_string& th) const noexcept { return std::strcmp(c_str(), th.c_str()) < 0; } //-----------------------------------------------------------------// /*! @brief クラス大小一致比較(オペレーター) @param[in] th 文字列 @return 大小一致なら「true」 */ //-----------------------------------------------------------------// bool operator >= (const fixed_string& th) const noexcept { return std::strcmp(c_str(), th.c_str()) >= 0; } //-----------------------------------------------------------------// /*! @brief クラス小大一致比較(オペレーター) @param[in] th 文字列クラス @return 小大一致なら「true」 */ //-----------------------------------------------------------------// bool operator <= (const fixed_string& th) const noexcept { return std::strcmp(c_str(), th.c_str()) <= 0; } }; typedef fixed_string<16> STR16; typedef fixed_string<32> STR32; typedef fixed_string<64> STR64; typedef fixed_string<128> STR128; typedef fixed_string<256> STR256; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: tphf.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: rt $ $Date: 2005-09-08 22:22:14 $ * * 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 * ************************************************************************/ #undef SC_DLLIMPLEMENTATION #ifdef PCH #include "ui_pch.hxx" #endif #pragma hdrstop //------------------------------------------------------------------ #define _TPHF_CXX #include "scitems.hxx" #include <sfx2/basedlgs.hxx> #include <svtools/style.hxx> #include <vcl/svapp.hxx> #include <vcl/msgbox.hxx> #include "tphf.hxx" #include "sc.hrc" #include "globstr.hrc" #include "tabvwsh.hxx" #include "viewdata.hxx" #include "document.hxx" //CHINA001 #include "tphfedit.hxx" #include "hfedtdlg.hxx" #include "styledlg.hxx" #include "scresid.hxx" #include "scuitphfedit.hxx" //CHINA001 #undef _TPHF_CXX //================================================================== // class ScHFPage //================================================================== ScHFPage::ScHFPage( Window* pParent, USHORT nResId, const SfxItemSet& rSet, USHORT nSetId ) : SvxHFPage ( pParent, nResId, rSet, nSetId ), aBtnEdit ( this, ScResId( RID_SCBTN_HFEDIT ) ), aDataSet ( *rSet.GetPool(), ATTR_PAGE_HEADERLEFT, ATTR_PAGE_FOOTERRIGHT, ATTR_PAGE, ATTR_PAGE, 0 ), nPageUsage ( (USHORT)SVX_PAGE_ALL ), pStyleDlg ( NULL ) { SetExchangeSupport(); SfxViewShell* pSh = SfxViewShell::Current(); ScTabViewShell* pViewSh = PTR_CAST(ScTabViewShell,pSh); Point aPos( aBackgroundBtn.GetPosPixel() ); // aBackgroundBtn position not changed anymore aPos.X() += aBackgroundBtn.GetSizePixel().Width(); aPos.X() += LogicToPixel( Size(3,0), MAP_APPFONT ).Width(); aBtnEdit.SetPosPixel( aPos ); aBtnEdit.Show(); aDataSet.Put( rSet ); if ( pViewSh ) { ScViewData* pViewData = pViewSh->GetViewData(); ScDocument* pDoc = pViewData->GetDocument(); aStrPageStyle = pDoc->GetPageStyle( pViewData->GetTabNo() ); } aBtnEdit.SetClickHdl ( LINK( this, ScHFPage, BtnHdl ) ); aTurnOnBox.SetClickHdl ( LINK( this, ScHFPage, TurnOnHdl ) ); if ( nId == SID_ATTR_PAGE_HEADERSET ) aBtnEdit.SetHelpId( HID_SC_HEADER_EDIT ); else aBtnEdit.SetHelpId( HID_SC_FOOTER_EDIT ); } //------------------------------------------------------------------ __EXPORT ScHFPage::~ScHFPage() { } //------------------------------------------------------------------ void __EXPORT ScHFPage::Reset( const SfxItemSet& rSet ) { SvxHFPage::Reset( rSet ); TurnOnHdl( 0 ); } //------------------------------------------------------------------ BOOL __EXPORT ScHFPage::FillItemSet( SfxItemSet& rOutSet ) { BOOL bResult = SvxHFPage::FillItemSet( rOutSet ); if ( nId == SID_ATTR_PAGE_HEADERSET ) { rOutSet.Put( aDataSet.Get( ATTR_PAGE_HEADERLEFT ) ); rOutSet.Put( aDataSet.Get( ATTR_PAGE_HEADERRIGHT ) ); } else { rOutSet.Put( aDataSet.Get( ATTR_PAGE_FOOTERLEFT ) ); rOutSet.Put( aDataSet.Get( ATTR_PAGE_FOOTERRIGHT ) ); } return bResult; } //------------------------------------------------------------------ void __EXPORT ScHFPage::ActivatePage( const SfxItemSet& rSet ) { USHORT nPageWhich = GetWhich( SID_ATTR_PAGE ); const SvxPageItem& rPageItem = (const SvxPageItem&) rSet.Get(nPageWhich); nPageUsage = rPageItem.GetPageUsage(); if ( pStyleDlg ) aStrPageStyle = pStyleDlg->GetStyleSheet().GetName(); aDataSet.Put( rSet.Get(ATTR_PAGE) ); SvxHFPage::ActivatePage( rSet ); } //------------------------------------------------------------------ int __EXPORT ScHFPage::DeactivatePage( SfxItemSet* pSet ) { if ( LEAVE_PAGE == SvxHFPage::DeactivatePage( pSet ) ) if ( pSet ) FillItemSet( *pSet ); return LEAVE_PAGE; } //------------------------------------------------------------------ // Handler: //------------------------------------------------------------------ IMPL_LINK( ScHFPage, TurnOnHdl, CheckBox*, EMPTYARG ) { SvxHFPage::TurnOnHdl( &aTurnOnBox ); if ( aTurnOnBox.IsChecked() ) aBtnEdit.Enable(); else aBtnEdit.Disable(); return 0; } //------------------------------------------------------------------ IMPL_LINK( ScHFPage, BtnHdl, PushButton*, EMPTYARG ) { // Wenn der Bearbeiten-Dialog direkt aus dem Click-Handler des Buttons // aufgerufen wird, funktioniert im Bearbeiten-Dialog unter OS/2 das // GrabFocus nicht (Bug #41805#). // Mit dem neuen StarView sollte dieser Workaround wieder raus koennen! Application::PostUserEvent( LINK( this, ScHFPage, HFEditHdl ) ); return 0; } IMPL_LINK( ScHFPage, HFEditHdl, void*, EMPTYARG ) { SfxViewShell* pViewSh = SfxViewShell::Current(); if ( !pViewSh ) { DBG_ERROR( "Current ViewShell not found." ); return 0; } if ( aCntSharedBox.IsEnabled() && !aCntSharedBox.IsChecked() ) { USHORT nResId = ( nId == SID_ATTR_PAGE_HEADERSET ) ? RID_SCDLG_HFED_HEADER : RID_SCDLG_HFED_FOOTER; ScHFEditDlg* pDlg = new ScHFEditDlg( pViewSh->GetViewFrame(), this, aDataSet, aStrPageStyle, nResId ); if ( pDlg->Execute() == RET_OK ) { aDataSet.Put( *pDlg->GetOutputItemSet() ); } delete pDlg; } else { String aText; SfxSingleTabDialog* pDlg = new SfxSingleTabDialog( pViewSh->GetViewFrame(), this, aDataSet, 42 ); BOOL bRightPage = aCntSharedBox.IsChecked() || ( SVX_PAGE_LEFT != SvxPageUsage(nPageUsage) ); if ( nId == SID_ATTR_PAGE_HEADERSET ) { aText = ScGlobal::GetRscString( STR_PAGEHEADER ); if ( bRightPage ) pDlg->SetTabPage( ScRightHeaderEditPage::Create( pDlg, aDataSet ) ); else pDlg->SetTabPage( ScLeftHeaderEditPage::Create( pDlg, aDataSet ) ); } else { aText = ScGlobal::GetRscString( STR_PAGEFOOTER ); if ( bRightPage ) pDlg->SetTabPage( ScRightFooterEditPage::Create( pDlg, aDataSet ) ); else pDlg->SetTabPage( ScLeftFooterEditPage::Create( pDlg, aDataSet ) ); } SvxNumType eNumType = ((const SvxPageItem&)aDataSet.Get(ATTR_PAGE)).GetNumType(); ((ScHFEditPage*)pDlg->GetTabPage())->SetNumType(eNumType); aText.AppendAscii(RTL_CONSTASCII_STRINGPARAM( " (" )); aText += ScGlobal::GetRscString( STR_PAGESTYLE ); aText.AppendAscii(RTL_CONSTASCII_STRINGPARAM( ": " )); aText += aStrPageStyle; aText += ')'; pDlg->SetText( aText ); if ( pDlg->Execute() == RET_OK ) { aDataSet.Put( *pDlg->GetOutputItemSet() ); } delete pDlg; } return 0; } //================================================================== // class ScHeaderPage //================================================================== ScHeaderPage::ScHeaderPage( Window* pParent, const SfxItemSet& rSet ) : ScHFPage( pParent, RID_SVXPAGE_HEADER, rSet, SID_ATTR_PAGE_HEADERSET ) { } //------------------------------------------------------------------ SfxTabPage* __EXPORT ScHeaderPage::Create( Window* pParent, const SfxItemSet& rCoreSet ) { return ( new ScHeaderPage( pParent, rCoreSet ) ); } //------------------------------------------------------------------ USHORT* __EXPORT ScHeaderPage::GetRanges() { return SvxHeaderPage::GetRanges(); } //================================================================== // class ScFooterPage //================================================================== ScFooterPage::ScFooterPage( Window* pParent, const SfxItemSet& rSet ) : ScHFPage( pParent, RID_SVXPAGE_FOOTER, rSet, SID_ATTR_PAGE_FOOTERSET ) { } //------------------------------------------------------------------ SfxTabPage* __EXPORT ScFooterPage::Create( Window* pParent, const SfxItemSet& rCoreSet ) { return ( new ScFooterPage( pParent, rCoreSet ) ); } //------------------------------------------------------------------ USHORT* __EXPORT ScFooterPage::GetRanges() { return SvxHeaderPage::GetRanges(); } <commit_msg>INTEGRATION: CWS pchfix01 (1.8.214); FILE MERGED 2006/07/12 10:02:50 kaib 1.8.214.1: #i67080# Converted cxx files in sc, added initial project level pch and stripped old PCH definitions.<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: tphf.cxx,v $ * * $Revision: 1.9 $ * * last change: $Author: kz $ $Date: 2006-07-21 14:21:08 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sc.hxx" #undef SC_DLLIMPLEMENTATION //------------------------------------------------------------------ #define _TPHF_CXX #include "scitems.hxx" #include <sfx2/basedlgs.hxx> #include <svtools/style.hxx> #include <vcl/svapp.hxx> #include <vcl/msgbox.hxx> #include "tphf.hxx" #include "sc.hrc" #include "globstr.hrc" #include "tabvwsh.hxx" #include "viewdata.hxx" #include "document.hxx" //CHINA001 #include "tphfedit.hxx" #include "hfedtdlg.hxx" #include "styledlg.hxx" #include "scresid.hxx" #include "scuitphfedit.hxx" //CHINA001 #undef _TPHF_CXX //================================================================== // class ScHFPage //================================================================== ScHFPage::ScHFPage( Window* pParent, USHORT nResId, const SfxItemSet& rSet, USHORT nSetId ) : SvxHFPage ( pParent, nResId, rSet, nSetId ), aBtnEdit ( this, ScResId( RID_SCBTN_HFEDIT ) ), aDataSet ( *rSet.GetPool(), ATTR_PAGE_HEADERLEFT, ATTR_PAGE_FOOTERRIGHT, ATTR_PAGE, ATTR_PAGE, 0 ), nPageUsage ( (USHORT)SVX_PAGE_ALL ), pStyleDlg ( NULL ) { SetExchangeSupport(); SfxViewShell* pSh = SfxViewShell::Current(); ScTabViewShell* pViewSh = PTR_CAST(ScTabViewShell,pSh); Point aPos( aBackgroundBtn.GetPosPixel() ); // aBackgroundBtn position not changed anymore aPos.X() += aBackgroundBtn.GetSizePixel().Width(); aPos.X() += LogicToPixel( Size(3,0), MAP_APPFONT ).Width(); aBtnEdit.SetPosPixel( aPos ); aBtnEdit.Show(); aDataSet.Put( rSet ); if ( pViewSh ) { ScViewData* pViewData = pViewSh->GetViewData(); ScDocument* pDoc = pViewData->GetDocument(); aStrPageStyle = pDoc->GetPageStyle( pViewData->GetTabNo() ); } aBtnEdit.SetClickHdl ( LINK( this, ScHFPage, BtnHdl ) ); aTurnOnBox.SetClickHdl ( LINK( this, ScHFPage, TurnOnHdl ) ); if ( nId == SID_ATTR_PAGE_HEADERSET ) aBtnEdit.SetHelpId( HID_SC_HEADER_EDIT ); else aBtnEdit.SetHelpId( HID_SC_FOOTER_EDIT ); } //------------------------------------------------------------------ __EXPORT ScHFPage::~ScHFPage() { } //------------------------------------------------------------------ void __EXPORT ScHFPage::Reset( const SfxItemSet& rSet ) { SvxHFPage::Reset( rSet ); TurnOnHdl( 0 ); } //------------------------------------------------------------------ BOOL __EXPORT ScHFPage::FillItemSet( SfxItemSet& rOutSet ) { BOOL bResult = SvxHFPage::FillItemSet( rOutSet ); if ( nId == SID_ATTR_PAGE_HEADERSET ) { rOutSet.Put( aDataSet.Get( ATTR_PAGE_HEADERLEFT ) ); rOutSet.Put( aDataSet.Get( ATTR_PAGE_HEADERRIGHT ) ); } else { rOutSet.Put( aDataSet.Get( ATTR_PAGE_FOOTERLEFT ) ); rOutSet.Put( aDataSet.Get( ATTR_PAGE_FOOTERRIGHT ) ); } return bResult; } //------------------------------------------------------------------ void __EXPORT ScHFPage::ActivatePage( const SfxItemSet& rSet ) { USHORT nPageWhich = GetWhich( SID_ATTR_PAGE ); const SvxPageItem& rPageItem = (const SvxPageItem&) rSet.Get(nPageWhich); nPageUsage = rPageItem.GetPageUsage(); if ( pStyleDlg ) aStrPageStyle = pStyleDlg->GetStyleSheet().GetName(); aDataSet.Put( rSet.Get(ATTR_PAGE) ); SvxHFPage::ActivatePage( rSet ); } //------------------------------------------------------------------ int __EXPORT ScHFPage::DeactivatePage( SfxItemSet* pSet ) { if ( LEAVE_PAGE == SvxHFPage::DeactivatePage( pSet ) ) if ( pSet ) FillItemSet( *pSet ); return LEAVE_PAGE; } //------------------------------------------------------------------ // Handler: //------------------------------------------------------------------ IMPL_LINK( ScHFPage, TurnOnHdl, CheckBox*, EMPTYARG ) { SvxHFPage::TurnOnHdl( &aTurnOnBox ); if ( aTurnOnBox.IsChecked() ) aBtnEdit.Enable(); else aBtnEdit.Disable(); return 0; } //------------------------------------------------------------------ IMPL_LINK( ScHFPage, BtnHdl, PushButton*, EMPTYARG ) { // Wenn der Bearbeiten-Dialog direkt aus dem Click-Handler des Buttons // aufgerufen wird, funktioniert im Bearbeiten-Dialog unter OS/2 das // GrabFocus nicht (Bug #41805#). // Mit dem neuen StarView sollte dieser Workaround wieder raus koennen! Application::PostUserEvent( LINK( this, ScHFPage, HFEditHdl ) ); return 0; } IMPL_LINK( ScHFPage, HFEditHdl, void*, EMPTYARG ) { SfxViewShell* pViewSh = SfxViewShell::Current(); if ( !pViewSh ) { DBG_ERROR( "Current ViewShell not found." ); return 0; } if ( aCntSharedBox.IsEnabled() && !aCntSharedBox.IsChecked() ) { USHORT nResId = ( nId == SID_ATTR_PAGE_HEADERSET ) ? RID_SCDLG_HFED_HEADER : RID_SCDLG_HFED_FOOTER; ScHFEditDlg* pDlg = new ScHFEditDlg( pViewSh->GetViewFrame(), this, aDataSet, aStrPageStyle, nResId ); if ( pDlg->Execute() == RET_OK ) { aDataSet.Put( *pDlg->GetOutputItemSet() ); } delete pDlg; } else { String aText; SfxSingleTabDialog* pDlg = new SfxSingleTabDialog( pViewSh->GetViewFrame(), this, aDataSet, 42 ); BOOL bRightPage = aCntSharedBox.IsChecked() || ( SVX_PAGE_LEFT != SvxPageUsage(nPageUsage) ); if ( nId == SID_ATTR_PAGE_HEADERSET ) { aText = ScGlobal::GetRscString( STR_PAGEHEADER ); if ( bRightPage ) pDlg->SetTabPage( ScRightHeaderEditPage::Create( pDlg, aDataSet ) ); else pDlg->SetTabPage( ScLeftHeaderEditPage::Create( pDlg, aDataSet ) ); } else { aText = ScGlobal::GetRscString( STR_PAGEFOOTER ); if ( bRightPage ) pDlg->SetTabPage( ScRightFooterEditPage::Create( pDlg, aDataSet ) ); else pDlg->SetTabPage( ScLeftFooterEditPage::Create( pDlg, aDataSet ) ); } SvxNumType eNumType = ((const SvxPageItem&)aDataSet.Get(ATTR_PAGE)).GetNumType(); ((ScHFEditPage*)pDlg->GetTabPage())->SetNumType(eNumType); aText.AppendAscii(RTL_CONSTASCII_STRINGPARAM( " (" )); aText += ScGlobal::GetRscString( STR_PAGESTYLE ); aText.AppendAscii(RTL_CONSTASCII_STRINGPARAM( ": " )); aText += aStrPageStyle; aText += ')'; pDlg->SetText( aText ); if ( pDlg->Execute() == RET_OK ) { aDataSet.Put( *pDlg->GetOutputItemSet() ); } delete pDlg; } return 0; } //================================================================== // class ScHeaderPage //================================================================== ScHeaderPage::ScHeaderPage( Window* pParent, const SfxItemSet& rSet ) : ScHFPage( pParent, RID_SVXPAGE_HEADER, rSet, SID_ATTR_PAGE_HEADERSET ) { } //------------------------------------------------------------------ SfxTabPage* __EXPORT ScHeaderPage::Create( Window* pParent, const SfxItemSet& rCoreSet ) { return ( new ScHeaderPage( pParent, rCoreSet ) ); } //------------------------------------------------------------------ USHORT* __EXPORT ScHeaderPage::GetRanges() { return SvxHeaderPage::GetRanges(); } //================================================================== // class ScFooterPage //================================================================== ScFooterPage::ScFooterPage( Window* pParent, const SfxItemSet& rSet ) : ScHFPage( pParent, RID_SVXPAGE_FOOTER, rSet, SID_ATTR_PAGE_FOOTERSET ) { } //------------------------------------------------------------------ SfxTabPage* __EXPORT ScFooterPage::Create( Window* pParent, const SfxItemSet& rCoreSet ) { return ( new ScFooterPage( pParent, rCoreSet ) ); } //------------------------------------------------------------------ USHORT* __EXPORT ScFooterPage::GetRanges() { return SvxHeaderPage::GetRanges(); } <|endoftext|>
<commit_before>// Copyright (c) 2013 GitHub, Inc. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "common/node_bindings.h" #include "base/command_line.h" #include "base/logging.h" #include "base/message_loop.h" #include "common/v8_conversions.h" #include "content/public/browser/browser_thread.h" #include "net/base/escape.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebDocument.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h" #include "vendor/node/src/node.h" #include "vendor/node/src/node_internals.h" #include "vendor/node/src/node_javascript.h" #if defined(OS_WIN) #include "base/strings/utf_string_conversions.h" #endif using content::BrowserThread; namespace atom { namespace { void UvNoOp(uv_async_t* handle, int status) { } } // namespace NodeBindings::NodeBindings(bool is_browser) : is_browser_(is_browser), message_loop_(NULL), uv_loop_(uv_default_loop()), embed_closed_(false) { } NodeBindings::~NodeBindings() { // Clear uv. embed_closed_ = true; WakeupEmbedThread(); uv_thread_join(&embed_thread_); uv_sem_destroy(&embed_sem_); uv_timer_stop(&idle_timer_); } void NodeBindings::Initialize() { CommandLine::StringVector str_argv = CommandLine::ForCurrentProcess()->argv(); #if defined(OS_WIN) std::vector<std::string> utf8_str_argv; utf8_str_argv.reserve(str_argv.size()); #endif // Convert string vector to char* array. std::vector<char*> argv(str_argv.size(), NULL); for (size_t i = 0; i < str_argv.size(); ++i) { #if defined(OS_WIN) utf8_str_argv.push_back(UTF16ToUTF8(str_argv[i])); argv[i] = const_cast<char*>(utf8_str_argv[i].c_str()); #else argv[i] = const_cast<char*>(str_argv[i].c_str()); #endif } // Init idle GC. uv_timer_init(uv_default_loop(), &idle_timer_); uv_timer_start(&idle_timer_, IdleCallback, 5000, 5000); // Open node's error reporting system for browser process. node::g_standalone_mode = is_browser_; node::g_upstream_node_mode = false; // Init node. node::Init(argv.size(), &argv[0]); v8::V8::Initialize(); // Load node.js. v8::HandleScope scope; node::g_context = v8::Persistent<v8::Context>::New( node::node_isolate, v8::Context::New(node::node_isolate)); { v8::Context::Scope context_scope(node::g_context); v8::Handle<v8::Object> process = node::SetupProcessObject( argv.size(), &argv[0]); // Tell node.js we are in browser or renderer. v8::Handle<v8::String> type = is_browser_ ? v8::String::New("browser") : v8::String::New("renderer"); process->Set(v8::String::New("__atom_type"), type); } } void NodeBindings::Load() { v8::HandleScope scope; v8::Context::Scope context_scope(node::g_context); node::Load(node::process); } void NodeBindings::BindTo(WebKit::WebFrame* frame) { v8::HandleScope handle_scope; v8::Handle<v8::Context> context = frame->mainWorldScriptContext(); if (context.IsEmpty()) return; v8::Context::Scope scope(context); // Erase security token. context->SetSecurityToken(node::g_context->GetSecurityToken()); // Evaluate cefode.js. v8::Handle<v8::Script> script = node::CompileCefodeMainSource(); v8::Local<v8::Value> result = script->Run(); // Run the script of cefode.js. std::string script_path(GURL(frame->document().url()).path()); script_path = net::UnescapeURLComponent( script_path, net::UnescapeRule::SPACES | net::UnescapeRule::URL_SPECIAL_CHARS); v8::Handle<v8::Value> args[2] = { v8::Local<v8::Value>::New(node::process), ToV8Value(script_path), }; v8::Local<v8::Function>::Cast(result)->Call(context->Global(), 2, args); } void NodeBindings::PrepareMessageLoop() { DCHECK(!is_browser_ || BrowserThread::CurrentlyOn(BrowserThread::UI)); // Add dummy handle for libuv, otherwise libuv would quit when there is // nothing to do. uv_async_init(uv_loop_, &dummy_uv_handle_, UvNoOp); // Start worker that will interrupt main loop when having uv events. uv_sem_init(&embed_sem_, 0); uv_thread_create(&embed_thread_, EmbedThreadRunner, this); } void NodeBindings::RunMessageLoop() { DCHECK(!is_browser_ || BrowserThread::CurrentlyOn(BrowserThread::UI)); // The MessageLoop should have been created, remember the one in main thread. message_loop_ = base::MessageLoop::current(); // Run uv loop for once to give the uv__io_poll a chance to add all events. UvRunOnce(); } void NodeBindings::UvRunOnce() { DCHECK(!is_browser_ || BrowserThread::CurrentlyOn(BrowserThread::UI)); // Enter node context while dealing with uv events. v8::HandleScope scope; v8::Context::Scope context_scope(node::g_context); // Deal with uv events. int r = uv_run(uv_loop_, (uv_run_mode)(UV_RUN_ONCE | UV_RUN_NOWAIT)); if (r == 0 || uv_loop_->stop_flag != 0) message_loop_->QuitWhenIdle(); // Quit from uv. // Tell the worker thread to continue polling. uv_sem_post(&embed_sem_); } void NodeBindings::WakeupMainThread() { DCHECK(message_loop_); message_loop_->PostTask(FROM_HERE, base::Bind(&NodeBindings::UvRunOnce, base::Unretained(this))); } void NodeBindings::WakeupEmbedThread() { uv_async_send(&dummy_uv_handle_); } // static void NodeBindings::EmbedThreadRunner(void *arg) { NodeBindings* self = static_cast<NodeBindings*>(arg); while (!self->embed_closed_) { // Wait for the main loop to deal with events. uv_sem_wait(&self->embed_sem_); self->PollEvents(); // Deal with event in main thread. self->WakeupMainThread(); } } // static void NodeBindings::IdleCallback(uv_timer_t*, int) { v8::V8::IdleNotification(); } } // namespace atom <commit_msg>Fix a possible dead lock when quiting.<commit_after>// Copyright (c) 2013 GitHub, Inc. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "common/node_bindings.h" #include "base/command_line.h" #include "base/logging.h" #include "base/message_loop.h" #include "common/v8_conversions.h" #include "content/public/browser/browser_thread.h" #include "net/base/escape.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebDocument.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h" #include "vendor/node/src/node.h" #include "vendor/node/src/node_internals.h" #include "vendor/node/src/node_javascript.h" #if defined(OS_WIN) #include "base/strings/utf_string_conversions.h" #endif using content::BrowserThread; namespace atom { namespace { void UvNoOp(uv_async_t* handle, int status) { } } // namespace NodeBindings::NodeBindings(bool is_browser) : is_browser_(is_browser), message_loop_(NULL), uv_loop_(uv_default_loop()), embed_closed_(false) { } NodeBindings::~NodeBindings() { // Quit the embed thread. embed_closed_ = true; uv_sem_post(&embed_sem_); WakeupEmbedThread(); // Wait for everything to be done. uv_thread_join(&embed_thread_); message_loop_->RunUntilIdle(); // Clear uv. uv_sem_destroy(&embed_sem_); uv_timer_stop(&idle_timer_); } void NodeBindings::Initialize() { CommandLine::StringVector str_argv = CommandLine::ForCurrentProcess()->argv(); #if defined(OS_WIN) std::vector<std::string> utf8_str_argv; utf8_str_argv.reserve(str_argv.size()); #endif // Convert string vector to char* array. std::vector<char*> argv(str_argv.size(), NULL); for (size_t i = 0; i < str_argv.size(); ++i) { #if defined(OS_WIN) utf8_str_argv.push_back(UTF16ToUTF8(str_argv[i])); argv[i] = const_cast<char*>(utf8_str_argv[i].c_str()); #else argv[i] = const_cast<char*>(str_argv[i].c_str()); #endif } // Init idle GC. uv_timer_init(uv_default_loop(), &idle_timer_); uv_timer_start(&idle_timer_, IdleCallback, 5000, 5000); // Open node's error reporting system for browser process. node::g_standalone_mode = is_browser_; node::g_upstream_node_mode = false; // Init node. node::Init(argv.size(), &argv[0]); v8::V8::Initialize(); // Load node.js. v8::HandleScope scope; node::g_context = v8::Persistent<v8::Context>::New( node::node_isolate, v8::Context::New(node::node_isolate)); { v8::Context::Scope context_scope(node::g_context); v8::Handle<v8::Object> process = node::SetupProcessObject( argv.size(), &argv[0]); // Tell node.js we are in browser or renderer. v8::Handle<v8::String> type = is_browser_ ? v8::String::New("browser") : v8::String::New("renderer"); process->Set(v8::String::New("__atom_type"), type); } } void NodeBindings::Load() { v8::HandleScope scope; v8::Context::Scope context_scope(node::g_context); node::Load(node::process); } void NodeBindings::BindTo(WebKit::WebFrame* frame) { v8::HandleScope handle_scope; v8::Handle<v8::Context> context = frame->mainWorldScriptContext(); if (context.IsEmpty()) return; v8::Context::Scope scope(context); // Erase security token. context->SetSecurityToken(node::g_context->GetSecurityToken()); // Evaluate cefode.js. v8::Handle<v8::Script> script = node::CompileCefodeMainSource(); v8::Local<v8::Value> result = script->Run(); // Run the script of cefode.js. std::string script_path(GURL(frame->document().url()).path()); script_path = net::UnescapeURLComponent( script_path, net::UnescapeRule::SPACES | net::UnescapeRule::URL_SPECIAL_CHARS); v8::Handle<v8::Value> args[2] = { v8::Local<v8::Value>::New(node::process), ToV8Value(script_path), }; v8::Local<v8::Function>::Cast(result)->Call(context->Global(), 2, args); } void NodeBindings::PrepareMessageLoop() { DCHECK(!is_browser_ || BrowserThread::CurrentlyOn(BrowserThread::UI)); // Add dummy handle for libuv, otherwise libuv would quit when there is // nothing to do. uv_async_init(uv_loop_, &dummy_uv_handle_, UvNoOp); // Start worker that will interrupt main loop when having uv events. uv_sem_init(&embed_sem_, 0); uv_thread_create(&embed_thread_, EmbedThreadRunner, this); } void NodeBindings::RunMessageLoop() { DCHECK(!is_browser_ || BrowserThread::CurrentlyOn(BrowserThread::UI)); // The MessageLoop should have been created, remember the one in main thread. message_loop_ = base::MessageLoop::current(); // Run uv loop for once to give the uv__io_poll a chance to add all events. UvRunOnce(); } void NodeBindings::UvRunOnce() { DCHECK(!is_browser_ || BrowserThread::CurrentlyOn(BrowserThread::UI)); // Enter node context while dealing with uv events. v8::HandleScope scope; v8::Context::Scope context_scope(node::g_context); // Deal with uv events. int r = uv_run(uv_loop_, (uv_run_mode)(UV_RUN_ONCE | UV_RUN_NOWAIT)); if (r == 0 || uv_loop_->stop_flag != 0) message_loop_->QuitWhenIdle(); // Quit from uv. // Tell the worker thread to continue polling. uv_sem_post(&embed_sem_); } void NodeBindings::WakeupMainThread() { DCHECK(message_loop_); message_loop_->PostTask(FROM_HERE, base::Bind(&NodeBindings::UvRunOnce, base::Unretained(this))); } void NodeBindings::WakeupEmbedThread() { uv_async_send(&dummy_uv_handle_); } // static void NodeBindings::EmbedThreadRunner(void *arg) { NodeBindings* self = static_cast<NodeBindings*>(arg); while (!self->embed_closed_) { // Wait for the main loop to deal with events. uv_sem_wait(&self->embed_sem_); self->PollEvents(); // Deal with event in main thread. self->WakeupMainThread(); } } // static void NodeBindings::IdleCallback(uv_timer_t*, int) { v8::V8::IdleNotification(); } } // namespace atom <|endoftext|>
<commit_before><commit_msg>one more fix for fdo#58686<commit_after><|endoftext|>
<commit_before><commit_msg>Fix PetscODESolver callbacks in the matrix free case<commit_after><|endoftext|>
<commit_before>// Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved. // Copyright (c) 2021 by Apex.AI Inc. 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. // // SPDX-License-Identifier: Apache-2.0 #ifndef IOX_HOOFS_UNITS_DURATION_HPP #define IOX_HOOFS_UNITS_DURATION_HPP #include "iceoryx_hoofs/cxx/expected.hpp" #include "iceoryx_hoofs/platform/time.hpp" // required for QNX #include <chrono> #include <cmath> #include <iostream> #include <numeric> namespace iox { namespace units { enum class TimeSpecReference : uint8_t { None, Epoch, Monotonic }; class Duration; namespace duration_literals { /// @brief Constructs a new Duration object from nanoseconds constexpr Duration operator"" _ns(unsigned long long int) noexcept; // PRQA S 48 /// @brief Constructs a new Duration object from microseconds constexpr Duration operator"" _us(unsigned long long int) noexcept; // PRQA S 48 /// @brief Constructs a new Duration object from milliseconds constexpr Duration operator"" _ms(unsigned long long int) noexcept; // PRQA S 48 /// @brief Constructs a new Duration object from seconds constexpr Duration operator"" _s(unsigned long long int) noexcept; // PRQA S 48 /// @brief Constructs a new Duration object from minutes constexpr Duration operator"" _m(unsigned long long int) noexcept; // PRQA S 48 /// @brief Constructs a new Duration object from hours constexpr Duration operator"" _h(unsigned long long int) noexcept; // PRQA S 48 /// @brief Constructs a new Duration object from days constexpr Duration operator"" _d(unsigned long long int) noexcept; // PRQA S 48 } // namespace duration_literals /// @code /// #include <iostream> /// // ... /// using namespace units; /// using namespace units::duration_literals; /// auto someDays = 2 * 7_d + 5_ns; /// auto someSeconds = 42_s + 500_ms; /// std::cout << someDays << std::endl; /// std::cout << someDays.nanoSeconds<uint64_t>() << " ns" << std::endl; /// std::cout << someSeconds.milliSeconds<int64_t>() << " ms" << std::endl; /// @endcode class Duration { public: // BEGIN CREATION FROM STATIC FUNCTIONS /// @brief Constructs a new Duration object from nanoseconds /// @tparam T is an integer type for the value /// @param[in] value as nanoseconds /// @return a new Duration object /// @attention Since negative durations are not allowed, the duration will be clamped to 0 template <typename T> static constexpr Duration fromNanoseconds(const T value) noexcept; /// @brief Constructs a new Duration object from microseconds /// @tparam T is an integer type for the value /// @param[in] value as microseconds /// @return a new Duration object /// @attention Since negative durations are not allowed, the duration will be clamped to 0 template <typename T> static constexpr Duration fromMicroseconds(const T value) noexcept; /// @brief Constructs a new Duration object from milliseconds /// @tparam T is an integer type for the value /// @param[in] value as milliseconds /// @return a new Duration object /// @attention Since negative durations are not allowed, the duration will be clamped to 0 template <typename T> static constexpr Duration fromMilliseconds(const T value) noexcept; /// @brief Constructs a new Duration object from seconds /// @tparam T is an integer type for the value /// @param[in] value as seconds /// @return a new Duration object /// @attention Since negative durations are not allowed, the duration will be clamped to 0 template <typename T> static constexpr Duration fromSeconds(const T value) noexcept; /// @brief Constructs a new Duration object from minutes /// @tparam T is an integer type for the value /// @param[in] value as minutes /// @return a new Duration object /// @attention Since negative durations are not allowed, the duration will be clamped to 0 template <typename T> static constexpr Duration fromMinutes(const T value) noexcept; /// @brief Constructs a new Duration object from hours /// @tparam T is an integer type for the value /// @param[in] value as hours /// @return a new Duration object /// @attention Since negative durations are not allowed, the duration will be clamped to 0 template <typename T> static constexpr Duration fromHours(const T value) noexcept; /// @brief Constructs a new Duration object from days /// @tparam T is an integer type for the value /// @param[in] value as days /// @return a new Duration object /// @attention Since negative durations are not allowed, the duration will be clamped to 0 template <typename T> static constexpr Duration fromDays(const T value) noexcept; /// @brief Constructs a new Duration object of maximum allowed length. Useful for functions which should have an /// "infinite" timeout. static constexpr Duration max() noexcept; /// @brief Constructs a new Duration object with a duration of zero static constexpr Duration zero() noexcept; // END CREATION FROM STATIC FUNCTIONS // BEGIN CONSTRUCTORS AND ASSIGNMENT /// @brief Construct a Duration object from timeval /// @param[in] value as timeval constexpr explicit Duration(const struct timeval& value) noexcept; /// @brief Construct a Duration object from timespec /// @param[in] value as timespec constexpr explicit Duration(const struct timespec& value) noexcept; /// @brief Construct a Duration object from itimerspec /// @param[in] value as itimerspec /// @note only it_interval from the itimerspec is used constexpr explicit Duration(const struct itimerspec& value) noexcept; /// @brief Construct a Duration object from std::chrono::milliseconds /// @param[in] value as milliseconds /// @attention Since negative durations are not allowed, the duration will be clamped to 0 constexpr explicit Duration(const std::chrono::milliseconds& value) noexcept; /// @brief Construct a Duration object from std::chrono::nanoseconds /// @param[in] value as nanoseconds /// @attention Since negative durations are not allowed, the duration will be clamped to 0 constexpr explicit Duration(const std::chrono::nanoseconds& value) noexcept; /// @brief Assigns a std::chrono::milliseconds to an duration object /// @param[in] rhs is the right hand side of the assignment /// @return a reference to the Duration object with the assigned millisecond value /// @attention Since negative durations are not allowed, the duration will be clamped to 0 Duration& operator=(const std::chrono::milliseconds& rhs) noexcept; // END CONSTRUCTORS AND ASSIGNMENT // BEGIN COMPARISON /// @brief Equal to operator /// @param[in] rhs is the right hand side of the comparison /// @return true if duration equal to rhs constexpr bool operator==(const Duration& rhs) const noexcept; /// @brief Not equal to operator /// @param[in] rhs is the right hand side of the comparison /// @return true if duration not equal to rhs constexpr bool operator!=(const Duration& rhs) const noexcept; /// @brief Less than operator /// @param[in] rhs is the right hand side of the comparison /// @return true if duration is less than rhs constexpr bool operator<(const Duration& rhs) const noexcept; /// @brief Less than or equal to operator /// @param[in] rhs is the right hand side of the comparison /// @return true if duration is less than or equal to rhs constexpr bool operator<=(const Duration& rhs) const noexcept; /// @brief Greater than operator /// @param[in] rhs is the right hand side of the comparison /// @return true if duration is greater than rhs constexpr bool operator>(const Duration& rhs) const noexcept; /// @brief Greater than or equal to operator /// @param[in] rhs is the right hand side of the comparison /// @return true if duration is greater than or equal to rhs constexpr bool operator>=(const Duration& rhs) const noexcept; // END COMPARISON // BEGIN ARITHMETIC /// @brief Creates Duration object by addition. On overflow duration /// saturates to Duration::max(). /// @param[in] rhs is the second summand /// @return a new Duration object constexpr Duration operator+(const Duration& rhs) const noexcept; /// @brief Creates Duration object by subtraction. On underflow duration /// saturates to Duration::zero(). /// @param[in] rhs is the subtrahend /// @return a new Duration object /// @attention Since negative durations are not allowed, the duration will be clamped to 0 constexpr Duration operator-(const Duration& rhs) const noexcept; /// @brief Creates Duration object by multiplication. /// @tparam T is an arithmetic type for the multiplicator /// @param[in] rhs is the multiplicator /// @return a new Duration object /// @attention Since negative durations are not allowed, the duration will be clamped to 0 /// @note A duration of 0 will always result in 0, no matter if multiplied with NaN or +Inf /// @note There is no explicit division operator! This can be achieved by multiplication with the inverse of the /// divisor. /// @note Multiplication of a non-zero duration with NaN and +Inf results in a saturated max duration template <typename T> constexpr Duration operator*(const T& rhs) const noexcept; // END ARITHMETIC // BEGIN CONVERSION /// @brief returns the duration in nanoseconds /// @note If the duration in nanoseconds is larger than an uint64_t can represent, it will be clamped to the /// uint64_t max value. constexpr uint64_t toNanoseconds() const noexcept; /// @brief returns the duration in microseconds /// @note If the duration in microseconds is larger than an uint64_t can represent, it will be clamped to the /// uint64_t max value. /// @note The remaining nanoseconds are truncated, similar to the casting behavior of a float to an int. constexpr uint64_t toMicroseconds() const noexcept; /// @brief returns the duration in milliseconds /// @note If the duration in milliseconds is larger than an uint64_t can represent, it will be clamped to the /// uint64_t max value. /// @note The remaining microseconds are truncated, similar to the casting behavior of a float to an int. constexpr uint64_t toMilliseconds() const noexcept; /// @brief returns the duration in seconds /// @note The remaining milliseconds are truncated, similar to the casting behavior of a float to an int. constexpr uint64_t toSeconds() const noexcept; /// @brief returns the duration in minutes /// @note The remaining seconds are truncated, similar to the casting behavior of a float to an int. constexpr uint64_t toMinutes() const noexcept; /// @brief returns the duration in hours /// @note The remaining minutes are truncated, similar to the casting behavior of a float to an int. constexpr uint64_t toHours() const noexcept; /// @brief returns the duration in days /// @note The remaining hours are truncated, similar to the casting behavior of a float to an int. constexpr uint64_t toDays() const noexcept; /// @brief converts duration in a timespec c struct struct timespec timespec(const TimeSpecReference& reference = TimeSpecReference::None) const noexcept; /// @brief converts duration in a timeval c struct /// timeval::tv_sec = seconds since the Epoch (01.01.1970) /// timeval::tv_usec = microseconds constexpr struct timeval timeval() const noexcept; // END CONVERSION friend constexpr Duration duration_literals::operator"" _ns(unsigned long long int) noexcept; // PRQA S 48 friend constexpr Duration duration_literals::operator"" _us(unsigned long long int) noexcept; // PRQA S 48 friend constexpr Duration duration_literals::operator"" _ms(unsigned long long int) noexcept; // PRQA S 48 friend constexpr Duration duration_literals::operator"" _s(unsigned long long int) noexcept; // PRQA S 48 friend constexpr Duration duration_literals::operator"" _m(unsigned long long int) noexcept; // PRQA S 48 friend constexpr Duration duration_literals::operator"" _h(unsigned long long int) noexcept; // PRQA S 48 friend constexpr Duration duration_literals::operator"" _d(unsigned long long int) noexcept; // PRQA S 48 template <typename T> friend constexpr Duration operator*(const T& lhs, const Duration& rhs) noexcept; friend std::ostream& operator<<(std::ostream& stream, const Duration& t) noexcept; static constexpr uint32_t SECS_PER_MINUTE{60U}; static constexpr uint32_t SECS_PER_HOUR{3600U}; static constexpr uint32_t HOURS_PER_DAY{24U}; static constexpr uint32_t MILLISECS_PER_SEC{1000U}; static constexpr uint32_t MICROSECS_PER_SEC{MILLISECS_PER_SEC * 1000U}; static constexpr uint32_t NANOSECS_PER_MICROSEC{1000U}; static constexpr uint32_t NANOSECS_PER_MILLISEC{NANOSECS_PER_MICROSEC * 1000U}; static constexpr uint32_t NANOSECS_PER_SEC{NANOSECS_PER_MILLISEC * 1000U}; protected: using Seconds_t = uint64_t; using Nanoseconds_t = uint32_t; /// @brief Constructs a Duration from seconds and nanoseconds /// @param[in] seconds portion of the duration /// @param[in] nanoseconds portion of the duration /// @note this is protected to be able to use it in unit tests constexpr Duration(const Seconds_t seconds, const Nanoseconds_t nanoseconds) noexcept; /// @note this is factory method is necessary to build with msvc due to issues calling a protected constexpr ctor /// from public methods static constexpr Duration createDuration(const Seconds_t seconds, const Nanoseconds_t nanoseconds) noexcept; private: template <typename T, typename String> static constexpr unsigned long long int positiveValueOrClampToZero(const T value, const String fromMethod) noexcept; template <typename T> constexpr Duration fromFloatingPointSeconds(const T floatingPointSeconds) const noexcept; template <typename From, typename To> constexpr bool wouldCastFromFloatingPointProbablyOverflow(const From floatingPoint) const noexcept; template <typename T> constexpr Duration multiplyWith(const std::enable_if_t<!std::is_floating_point<T>::value, T>& rhs) const noexcept; template <typename T> constexpr Duration multiplyWith(const std::enable_if_t<std::is_floating_point<T>::value, T>& rhs) const noexcept; private: Seconds_t m_seconds{0U}; Nanoseconds_t m_nanoseconds{0U}; }; /// @brief creates Duration object by multiplying object T with a duration. On overflow /// duration will saturate to Duration::max() /// @tparam T is an arithmetic type for the multiplicator /// @param[in] lhs is the multiplicator /// @param[in] rhs is the multiplicant /// @return a new Duration object /// @attention Since negative durations are not allowed, the duration will be clamped to 0 template <typename T> constexpr Duration operator*(const T& lhs, const Duration& rhs) noexcept; /// @brief stream operator for the Duration class std::ostream& operator<<(std::ostream& stream, const Duration& t) noexcept; } // namespace units } // namespace iox #include "iceoryx_hoofs/internal/units/duration.inl" #endif // IOX_HOOFS_UNITS_DURATION_HPP <commit_msg>iox-#1196 Add paramenter name to function declaration<commit_after>// Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved. // Copyright (c) 2021 by Apex.AI Inc. 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. // // SPDX-License-Identifier: Apache-2.0 #ifndef IOX_HOOFS_UNITS_DURATION_HPP #define IOX_HOOFS_UNITS_DURATION_HPP #include "iceoryx_hoofs/cxx/expected.hpp" #include "iceoryx_hoofs/platform/time.hpp" // required for QNX #include <chrono> #include <cmath> #include <iostream> #include <numeric> namespace iox { namespace units { enum class TimeSpecReference : uint8_t { None, Epoch, Monotonic }; class Duration; namespace duration_literals { /// @brief Constructs a new Duration object from nanoseconds constexpr Duration operator"" _ns(unsigned long long int value) noexcept; /// @brief Constructs a new Duration object from microseconds constexpr Duration operator"" _us(unsigned long long int value) noexcept; /// @brief Constructs a new Duration object from milliseconds constexpr Duration operator"" _ms(unsigned long long int value) noexcept; /// @brief Constructs a new Duration object from seconds constexpr Duration operator"" _s(unsigned long long int value) noexcept; /// @brief Constructs a new Duration object from minutes constexpr Duration operator"" _m(unsigned long long int value) noexcept; /// @brief Constructs a new Duration object from hours constexpr Duration operator"" _h(unsigned long long int value) noexcept; /// @brief Constructs a new Duration object from days constexpr Duration operator"" _d(unsigned long long intvalue) noexcept; } // namespace duration_literals /// @code /// #include <iostream> /// // ... /// using namespace units; /// using namespace units::duration_literals; /// auto someDays = 2 * 7_d + 5_ns; /// auto someSeconds = 42_s + 500_ms; /// std::cout << someDays << std::endl; /// std::cout << someDays.nanoSeconds<uint64_t>() << " ns" << std::endl; /// std::cout << someSeconds.milliSeconds<int64_t>() << " ms" << std::endl; /// @endcode class Duration { public: // BEGIN CREATION FROM STATIC FUNCTIONS /// @brief Constructs a new Duration object from nanoseconds /// @tparam T is an integer type for the value /// @param[in] value as nanoseconds /// @return a new Duration object /// @attention Since negative durations are not allowed, the duration will be clamped to 0 template <typename T> static constexpr Duration fromNanoseconds(const T value) noexcept; /// @brief Constructs a new Duration object from microseconds /// @tparam T is an integer type for the value /// @param[in] value as microseconds /// @return a new Duration object /// @attention Since negative durations are not allowed, the duration will be clamped to 0 template <typename T> static constexpr Duration fromMicroseconds(const T value) noexcept; /// @brief Constructs a new Duration object from milliseconds /// @tparam T is an integer type for the value /// @param[in] value as milliseconds /// @return a new Duration object /// @attention Since negative durations are not allowed, the duration will be clamped to 0 template <typename T> static constexpr Duration fromMilliseconds(const T value) noexcept; /// @brief Constructs a new Duration object from seconds /// @tparam T is an integer type for the value /// @param[in] value as seconds /// @return a new Duration object /// @attention Since negative durations are not allowed, the duration will be clamped to 0 template <typename T> static constexpr Duration fromSeconds(const T value) noexcept; /// @brief Constructs a new Duration object from minutes /// @tparam T is an integer type for the value /// @param[in] value as minutes /// @return a new Duration object /// @attention Since negative durations are not allowed, the duration will be clamped to 0 template <typename T> static constexpr Duration fromMinutes(const T value) noexcept; /// @brief Constructs a new Duration object from hours /// @tparam T is an integer type for the value /// @param[in] value as hours /// @return a new Duration object /// @attention Since negative durations are not allowed, the duration will be clamped to 0 template <typename T> static constexpr Duration fromHours(const T value) noexcept; /// @brief Constructs a new Duration object from days /// @tparam T is an integer type for the value /// @param[in] value as days /// @return a new Duration object /// @attention Since negative durations are not allowed, the duration will be clamped to 0 template <typename T> static constexpr Duration fromDays(const T value) noexcept; /// @brief Constructs a new Duration object of maximum allowed length. Useful for functions which should have an /// "infinite" timeout. static constexpr Duration max() noexcept; /// @brief Constructs a new Duration object with a duration of zero static constexpr Duration zero() noexcept; // END CREATION FROM STATIC FUNCTIONS // BEGIN CONSTRUCTORS AND ASSIGNMENT /// @brief Construct a Duration object from timeval /// @param[in] value as timeval constexpr explicit Duration(const struct timeval& value) noexcept; /// @brief Construct a Duration object from timespec /// @param[in] value as timespec constexpr explicit Duration(const struct timespec& value) noexcept; /// @brief Construct a Duration object from itimerspec /// @param[in] value as itimerspec /// @note only it_interval from the itimerspec is used constexpr explicit Duration(const struct itimerspec& value) noexcept; /// @brief Construct a Duration object from std::chrono::milliseconds /// @param[in] value as milliseconds /// @attention Since negative durations are not allowed, the duration will be clamped to 0 constexpr explicit Duration(const std::chrono::milliseconds& value) noexcept; /// @brief Construct a Duration object from std::chrono::nanoseconds /// @param[in] value as nanoseconds /// @attention Since negative durations are not allowed, the duration will be clamped to 0 constexpr explicit Duration(const std::chrono::nanoseconds& value) noexcept; /// @brief Assigns a std::chrono::milliseconds to an duration object /// @param[in] rhs is the right hand side of the assignment /// @return a reference to the Duration object with the assigned millisecond value /// @attention Since negative durations are not allowed, the duration will be clamped to 0 Duration& operator=(const std::chrono::milliseconds& rhs) noexcept; // END CONSTRUCTORS AND ASSIGNMENT // BEGIN COMPARISON /// @brief Equal to operator /// @param[in] rhs is the right hand side of the comparison /// @return true if duration equal to rhs constexpr bool operator==(const Duration& rhs) const noexcept; /// @brief Not equal to operator /// @param[in] rhs is the right hand side of the comparison /// @return true if duration not equal to rhs constexpr bool operator!=(const Duration& rhs) const noexcept; /// @brief Less than operator /// @param[in] rhs is the right hand side of the comparison /// @return true if duration is less than rhs constexpr bool operator<(const Duration& rhs) const noexcept; /// @brief Less than or equal to operator /// @param[in] rhs is the right hand side of the comparison /// @return true if duration is less than or equal to rhs constexpr bool operator<=(const Duration& rhs) const noexcept; /// @brief Greater than operator /// @param[in] rhs is the right hand side of the comparison /// @return true if duration is greater than rhs constexpr bool operator>(const Duration& rhs) const noexcept; /// @brief Greater than or equal to operator /// @param[in] rhs is the right hand side of the comparison /// @return true if duration is greater than or equal to rhs constexpr bool operator>=(const Duration& rhs) const noexcept; // END COMPARISON // BEGIN ARITHMETIC /// @brief Creates Duration object by addition. On overflow duration /// saturates to Duration::max(). /// @param[in] rhs is the second summand /// @return a new Duration object constexpr Duration operator+(const Duration& rhs) const noexcept; /// @brief Creates Duration object by subtraction. On underflow duration /// saturates to Duration::zero(). /// @param[in] rhs is the subtrahend /// @return a new Duration object /// @attention Since negative durations are not allowed, the duration will be clamped to 0 constexpr Duration operator-(const Duration& rhs) const noexcept; /// @brief Creates Duration object by multiplication. /// @tparam T is an arithmetic type for the multiplicator /// @param[in] rhs is the multiplicator /// @return a new Duration object /// @attention Since negative durations are not allowed, the duration will be clamped to 0 /// @note A duration of 0 will always result in 0, no matter if multiplied with NaN or +Inf /// @note There is no explicit division operator! This can be achieved by multiplication with the inverse of the /// divisor. /// @note Multiplication of a non-zero duration with NaN and +Inf results in a saturated max duration template <typename T> constexpr Duration operator*(const T& rhs) const noexcept; // END ARITHMETIC // BEGIN CONVERSION /// @brief returns the duration in nanoseconds /// @note If the duration in nanoseconds is larger than an uint64_t can represent, it will be clamped to the /// uint64_t max value. constexpr uint64_t toNanoseconds() const noexcept; /// @brief returns the duration in microseconds /// @note If the duration in microseconds is larger than an uint64_t can represent, it will be clamped to the /// uint64_t max value. /// @note The remaining nanoseconds are truncated, similar to the casting behavior of a float to an int. constexpr uint64_t toMicroseconds() const noexcept; /// @brief returns the duration in milliseconds /// @note If the duration in milliseconds is larger than an uint64_t can represent, it will be clamped to the /// uint64_t max value. /// @note The remaining microseconds are truncated, similar to the casting behavior of a float to an int. constexpr uint64_t toMilliseconds() const noexcept; /// @brief returns the duration in seconds /// @note The remaining milliseconds are truncated, similar to the casting behavior of a float to an int. constexpr uint64_t toSeconds() const noexcept; /// @brief returns the duration in minutes /// @note The remaining seconds are truncated, similar to the casting behavior of a float to an int. constexpr uint64_t toMinutes() const noexcept; /// @brief returns the duration in hours /// @note The remaining minutes are truncated, similar to the casting behavior of a float to an int. constexpr uint64_t toHours() const noexcept; /// @brief returns the duration in days /// @note The remaining hours are truncated, similar to the casting behavior of a float to an int. constexpr uint64_t toDays() const noexcept; /// @brief converts duration in a timespec c struct struct timespec timespec(const TimeSpecReference& reference = TimeSpecReference::None) const noexcept; /// @brief converts duration in a timeval c struct /// timeval::tv_sec = seconds since the Epoch (01.01.1970) /// timeval::tv_usec = microseconds constexpr struct timeval timeval() const noexcept; // END CONVERSION friend constexpr Duration duration_literals::operator"" _ns(unsigned long long int value) noexcept; friend constexpr Duration duration_literals::operator"" _us(unsigned long long int value) noexcept; friend constexpr Duration duration_literals::operator"" _ms(unsigned long long int value) noexcept; friend constexpr Duration duration_literals::operator"" _s(unsigned long long int value) noexcept; friend constexpr Duration duration_literals::operator"" _m(unsigned long long int value) noexcept; friend constexpr Duration duration_literals::operator"" _h(unsigned long long int value) noexcept; friend constexpr Duration duration_literals::operator"" _d(unsigned long long int value) noexcept; template <typename T> friend constexpr Duration operator*(const T& lhs, const Duration& rhs) noexcept; friend std::ostream& operator<<(std::ostream& stream, const Duration& t) noexcept; static constexpr uint32_t SECS_PER_MINUTE{60U}; static constexpr uint32_t SECS_PER_HOUR{3600U}; static constexpr uint32_t HOURS_PER_DAY{24U}; static constexpr uint32_t MILLISECS_PER_SEC{1000U}; static constexpr uint32_t MICROSECS_PER_SEC{MILLISECS_PER_SEC * 1000U}; static constexpr uint32_t NANOSECS_PER_MICROSEC{1000U}; static constexpr uint32_t NANOSECS_PER_MILLISEC{NANOSECS_PER_MICROSEC * 1000U}; static constexpr uint32_t NANOSECS_PER_SEC{NANOSECS_PER_MILLISEC * 1000U}; protected: using Seconds_t = uint64_t; using Nanoseconds_t = uint32_t; /// @brief Constructs a Duration from seconds and nanoseconds /// @param[in] seconds portion of the duration /// @param[in] nanoseconds portion of the duration /// @note this is protected to be able to use it in unit tests constexpr Duration(const Seconds_t seconds, const Nanoseconds_t nanoseconds) noexcept; /// @note this is factory method is necessary to build with msvc due to issues calling a protected constexpr ctor /// from public methods static constexpr Duration createDuration(const Seconds_t seconds, const Nanoseconds_t nanoseconds) noexcept; private: template <typename T, typename String> static constexpr unsigned long long int positiveValueOrClampToZero(const T value, const String fromMethod) noexcept; template <typename T> constexpr Duration fromFloatingPointSeconds(const T floatingPointSeconds) const noexcept; template <typename From, typename To> constexpr bool wouldCastFromFloatingPointProbablyOverflow(const From floatingPoint) const noexcept; template <typename T> constexpr Duration multiplyWith(const std::enable_if_t<!std::is_floating_point<T>::value, T>& rhs) const noexcept; template <typename T> constexpr Duration multiplyWith(const std::enable_if_t<std::is_floating_point<T>::value, T>& rhs) const noexcept; private: Seconds_t m_seconds{0U}; Nanoseconds_t m_nanoseconds{0U}; }; /// @brief creates Duration object by multiplying object T with a duration. On overflow /// duration will saturate to Duration::max() /// @tparam T is an arithmetic type for the multiplicator /// @param[in] lhs is the multiplicator /// @param[in] rhs is the multiplicant /// @return a new Duration object /// @attention Since negative durations are not allowed, the duration will be clamped to 0 template <typename T> constexpr Duration operator*(const T& lhs, const Duration& rhs) noexcept; /// @brief stream operator for the Duration class std::ostream& operator<<(std::ostream& stream, const Duration& t) noexcept; } // namespace units } // namespace iox #include "iceoryx_hoofs/internal/units/duration.inl" #endif // IOX_HOOFS_UNITS_DURATION_HPP <|endoftext|>
<commit_before>#include "openlcb/If.hxx" #include "address.h" extern const openlcb::NodeID NODE_ID; const openlcb::NodeID NODE_ID = 0x050101011400ULL | NODEID_LOW_BITS; extern const uint16_t DEFAULT_ALIAS; const uint16_t DEFAULT_ALIAS = 0x400 | NODEID_LOW_BITS; #define BOOTLOADER_DATAGRAM #include "openlcb/Bootloader.hxx" <commit_msg>Adds support for nodeid high bits.<commit_after>#include "openlcb/If.hxx" #include "address.h" #ifndef NODEID_HIGH_BITS #define NODEID_HIGH_BITS 0x18 #endif extern const openlcb::NodeID NODE_ID; const openlcb::NodeID NODE_ID = 0x050101010000ULL | (NODEID_HIGH_BITS << 8) | NODEID_LOW_BITS; extern const uint16_t DEFAULT_ALIAS; const uint16_t DEFAULT_ALIAS = 0x400 | NODEID_LOW_BITS; #define BOOTLOADER_DATAGRAM #include "openlcb/Bootloader.hxx" <|endoftext|>
<commit_before>/** \copyright * Copyright (c) 2013, Balazs Racz * 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * \file main.cxx * * Main file for the io board application on the Tiva Launchpad board. * * @author Balazs Racz * @date 5 Jun 2015 */ #include "os/os.h" #include "nmranet_config.h" #include "nmranet/SimpleStack.hxx" #include "nmranet/ConfiguredConsumer.hxx" #include "nmranet/ConfiguredProducer.hxx" #include "freertos_drivers/ti/TivaGPIO.hxx" #include "freertos_drivers/common/BlinkerGPIO.hxx" #include "config.hxx" #include "hardware.hxx" // These preprocessor symbols are used to select which physical connections // will be enabled in the main(). See @ref appl_main below. #define SNIFF_ON_SERIAL //#define SNIFF_ON_USB //#define HAVE_PHYSICAL_CAN_PORT // Changes the default behavior by adding a newline after each gridconnect // packet. Makes it easier for debugging the raw device. OVERRIDE_CONST(gc_generate_newlines, 1); // Specifies how much RAM (in bytes) we allocate to the stack of the main // thread. Useful tuning parameter in case the application runs out of memory. OVERRIDE_CONST(main_thread_stack_size, 2500); // Specifies the 48-bit OpenLCB node identifier. This must be unique for every // hardware manufactured, so in production this should be replaced by some // easily incrementable method. extern const nmranet::NodeID NODE_ID = 0x050101011412ULL; // Sets up a comprehensive OpenLCB stack for a single virtual node. This stack // contains everything needed for a usual peripheral node -- all // CAN-bus-specific components, a virtual node, PIP, SNIP, Memory configuration // protocol, ACDI, CDI, a bunch of memory spaces, etc. nmranet::SimpleCanStack stack(NODE_ID); // ConfigDef comes from config.hxx and is specific to the particular device and // target. It defines the layout of the configuration memory space and is also // used to generate the cdi.xml file. Here we instantiate the configuration // layout. The argument of offset zero is ignored and will be removed later. nmranet::ConfigDef cfg(0); // Defines weak constants used by the stack to tell it which device contains // the volatile configuration information. This device name appears in // HwInit.cxx that creates the device drivers. extern const char *const nmranet::CONFIG_FILENAME = "/dev/eeprom"; // The size of the memory space to export over the above device. extern const size_t nmranet::CONFIG_FILE_SIZE = cfg.seg().size() + cfg.seg().offset(); static_assert(nmranet::CONFIG_FILE_SIZE <= 300, "Need to adjust eeprom size"); // The SNIP user-changeable information in also stored in the above eeprom // device. In general this could come from different eeprom segments, but it is // simpler to keep them together. extern const char *const nmranet::SNIP_DYNAMIC_FILENAME = nmranet::CONFIG_FILENAME; // Defines the GPIO ports used for the producers and the consumers. // The first LED is driven by the blinker device from BlinkerGPIO.hxx. We just // create an alias for symmetry. typedef BLINKER_Pin LED_RED_Pin; // Instantiates the actual producer and consumer objects for the given GPIO // pins from above. The ConfiguredConsumer class takes care of most of the // complicated setup and operation requirements. We need to give it the virtual // node pointer, the configuration configuration from the CDI definition, and // the hardware pin definition. The virtual node pointer comes from the stack // object. The configuration structure comes from the CDI definition object, // segment 'seg', in which there is a repeated group 'consumers', and we assign // the individual entries to the individual consumers. Each consumer gets its // own GPIO pin. nmranet::ConfiguredConsumer consumer_red( stack.node(), cfg.seg().consumers().entry<0>(), LED_RED_Pin()); nmranet::ConfiguredConsumer consumer_green( stack.node(), cfg.seg().consumers().entry<1>(), LED_GREEN_Pin()); nmranet::ConfiguredConsumer consumer_blue( stack.node(), cfg.seg().consumers().entry<2>(), LED_BLUE_Pin()); // Similar syntax for the producers. nmranet::ConfiguredProducer producer_sw1( stack.node(), cfg.seg().producers().entry<0>(), SW1_Pin()); nmranet::ConfiguredProducer producer_sw2( stack.node(), cfg.seg().producers().entry<1>(), SW2_Pin()); // The producers need to be polled repeatedly for changes and to execute the // debouncing algorithm. This class instantiates a refreshloop and adds the two // producers to it. nmranet::RefreshLoop loop( stack.node(), {producer_sw1.polling(), producer_sw2.polling()}); /** Entry point to application. * @param argc number of command line arguments * @param argv array of command line arguments * @return 0, should never return */ int appl_main(int argc, char *argv[]) { // The necessary physical ports must be added to the stack. // // It is okay to enable multiple physical ports, in which case the stack // will behave as a bridge between them. For example enabling both the // physical CAN port and the USB port will make this firmware act as an // USB-CAN adapter in addition to the producers/consumers created above. // // If a port is enabled, it must be functional or else the stack will // freeze waiting for that port to send the packets out. #if defined(HAVE_PHYSICAL_CAN_PORT) stack.add_can_port_select("/dev/can0"); #endif #if defined(SNIFF_ON_USB) stack.add_gridconnect_port("/dev/serUSB0"); #endif #if defined(SNIFF_ON_SERIAL) stack.add_gridconnect_port("/dev/ser0"); #endif // This command donates the main thread to the operation of the // stack. Alternatively the stack could be started in a separate stack and // then application-specific business logic could be executed ion a busy // loop in the main thread. stack.loop_executor(); return 0; } <commit_msg>Updates io_board target tm4c123 to use the MultiConfiguredConsumer object.<commit_after>/** \copyright * Copyright (c) 2013, Balazs Racz * 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * \file main.cxx * * Main file for the io board application on the Tiva Launchpad board. * * @author Balazs Racz * @date 5 Jun 2015 */ #include "os/os.h" #include "nmranet_config.h" #include "nmranet/SimpleStack.hxx" #include "nmranet/ConfiguredConsumer.hxx" #include "nmranet/MultiConfiguredConsumer.hxx" #include "nmranet/ConfiguredProducer.hxx" #include "freertos_drivers/ti/TivaGPIO.hxx" #include "freertos_drivers/common/BlinkerGPIO.hxx" #include "config.hxx" #include "hardware.hxx" // These preprocessor symbols are used to select which physical connections // will be enabled in the main(). See @ref appl_main below. #define SNIFF_ON_SERIAL //#define SNIFF_ON_USB //#define HAVE_PHYSICAL_CAN_PORT // Changes the default behavior by adding a newline after each gridconnect // packet. Makes it easier for debugging the raw device. OVERRIDE_CONST(gc_generate_newlines, 1); // Specifies how much RAM (in bytes) we allocate to the stack of the main // thread. Useful tuning parameter in case the application runs out of memory. OVERRIDE_CONST(main_thread_stack_size, 2500); // Specifies the 48-bit OpenLCB node identifier. This must be unique for every // hardware manufactured, so in production this should be replaced by some // easily incrementable method. extern const nmranet::NodeID NODE_ID = 0x050101011412ULL; // Sets up a comprehensive OpenLCB stack for a single virtual node. This stack // contains everything needed for a usual peripheral node -- all // CAN-bus-specific components, a virtual node, PIP, SNIP, Memory configuration // protocol, ACDI, CDI, a bunch of memory spaces, etc. nmranet::SimpleCanStack stack(NODE_ID); // ConfigDef comes from config.hxx and is specific to the particular device and // target. It defines the layout of the configuration memory space and is also // used to generate the cdi.xml file. Here we instantiate the configuration // layout. The argument of offset zero is ignored and will be removed later. nmranet::ConfigDef cfg(0); // Defines weak constants used by the stack to tell it which device contains // the volatile configuration information. This device name appears in // HwInit.cxx that creates the device drivers. extern const char *const nmranet::CONFIG_FILENAME = "/dev/eeprom"; // The size of the memory space to export over the above device. extern const size_t nmranet::CONFIG_FILE_SIZE = cfg.seg().size() + cfg.seg().offset(); static_assert(nmranet::CONFIG_FILE_SIZE <= 300, "Need to adjust eeprom size"); // The SNIP user-changeable information in also stored in the above eeprom // device. In general this could come from different eeprom segments, but it is // simpler to keep them together. extern const char *const nmranet::SNIP_DYNAMIC_FILENAME = nmranet::CONFIG_FILENAME; // Defines the GPIO ports used for the producers and the consumers. // The first LED is driven by the blinker device from BlinkerGPIO.hxx. We just // create an alias for symmetry. typedef BLINKER_Pin LED_RED_Pin; // List of GPIO objects that will be used for the output pins. You should keep // the constexpr declaration, because it will produce a compile error in case // the list of pointers cannot be compiled into a compiler constant and thus // would be placed into RAM instead of ROM. constexpr const Gpio *const kOutputGpio[] = {LED_RED_Pin::instance(), LED_GREEN_Pin::instance(), LED_BLUE_Pin::instance()}; // Instantiates the actual producer and consumer objects for the given GPIO // pins from above. The MultiConfiguredConsumer class takes care of most of the // complicated setup and operation requirements. We need to give it the virtual // node pointer, the hardware pin definition and the configuration from the CDI // definition. The virtual node pointer comes from the stack object. The // configuration structure comes from the CDI definition object, segment 'seg', // in which there is a repeated group 'consumers'. The GPIO pins get assigned // to the repetitions in the group in order. nmranet::MultiConfiguredConsumer consumers(kOutputGpio, ARRAYSIZE(kOutputGpio), cfg.seg().consumers()); // Similar syntax for the producers. nmranet::ConfiguredProducer producer_sw1( stack.node(), cfg.seg().producers().entry<0>(), SW1_Pin()); nmranet::ConfiguredProducer producer_sw2( stack.node(), cfg.seg().producers().entry<1>(), SW2_Pin()); // The producers need to be polled repeatedly for changes and to execute the // debouncing algorithm. This class instantiates a refreshloop and adds the two // producers to it. nmranet::RefreshLoop loop( stack.node(), {producer_sw1.polling(), producer_sw2.polling()}); /** Entry point to application. * @param argc number of command line arguments * @param argv array of command line arguments * @return 0, should never return */ int appl_main(int argc, char *argv[]) { // The necessary physical ports must be added to the stack. // // It is okay to enable multiple physical ports, in which case the stack // will behave as a bridge between them. For example enabling both the // physical CAN port and the USB port will make this firmware act as an // USB-CAN adapter in addition to the producers/consumers created above. // // If a port is enabled, it must be functional or else the stack will // freeze waiting for that port to send the packets out. #if defined(HAVE_PHYSICAL_CAN_PORT) stack.add_can_port_select("/dev/can0"); #endif #if defined(SNIFF_ON_USB) stack.add_gridconnect_port("/dev/serUSB0"); #endif #if defined(SNIFF_ON_SERIAL) stack.add_gridconnect_port("/dev/ser0"); #endif // This command donates the main thread to the operation of the // stack. Alternatively the stack could be started in a separate stack and // then application-specific business logic could be executed ion a busy // loop in the main thread. stack.loop_executor(); return 0; } <|endoftext|>
<commit_before> // Author: Enric Tejedor CERN 08/2019 /************************************************************************* * Copyright (C) 1995-2019, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "TMemoryRegulator.h" #include "ProxyWrappers.h" #include "CPPInstance.h" #include "CPPInstance.h" using namespace CPyCppyy; PyROOT::ObjectMap_t PyROOT::TMemoryRegulator::fObjectMap = PyROOT::ObjectMap_t(); //////////////////////////////////////////////////////////////////////////// /// \brief Constructor. Registers the hooks to run on Cppyy's object /// construction and destruction PyROOT::TMemoryRegulator::TMemoryRegulator() { MemoryRegulator::SetRegisterHook(PyROOT::TMemoryRegulator::RegisterHook); MemoryRegulator::SetUnregisterHook(PyROOT::TMemoryRegulator::UnregisterHook); } //////////////////////////////////////////////////////////////////////////// /// \brief Register a hook that Cppyy runs when constructing an object. /// \param[in] cppobj Address of the object. /// \param[in] klass Class id of the object. /// \return Pair of two booleans. First indicates success, second tells /// Cppyy if we want to continue running RegisterPyObject std::pair<bool, bool> PyROOT::TMemoryRegulator::RegisterHook(Cppyy::TCppObject_t cppobj, Cppyy::TCppType_t klass) { static Cppyy::TCppType_t tobjectTypeID = (Cppyy::TCppType_t)Cppyy::GetScope("TObject"); if (Cppyy::IsSubtype(klass, tobjectTypeID)) { ObjectMap_t::iterator ppo = fObjectMap.find(cppobj); if (ppo == fObjectMap.end()) { fObjectMap.insert({cppobj, klass}); } } return {true, true}; } //////////////////////////////////////////////////////////////////////////// /// \brief Register a hook that Cppyy runs when deleting an object. /// \param[in] cppobj Address of the object. /// \param[in] klass Class id of the object. /// \return Pair of two booleans. First indicates success, second tells /// Cppyy if we want to continue running UnRegisterPyObject std::pair<bool, bool> PyROOT::TMemoryRegulator::UnregisterHook(Cppyy::TCppObject_t cppobj, Cppyy::TCppType_t klass) { static Cppyy::TCppType_t tobjectTypeID = (Cppyy::TCppType_t)Cppyy::GetScope("TObject"); if (Cppyy::IsSubtype(klass, tobjectTypeID)) { ObjectMap_t::iterator ppo = fObjectMap.find(cppobj); if (ppo != fObjectMap.end()) { fObjectMap.erase(ppo); } } return {true, true}; } //////////////////////////////////////////////////////////////////////////// /// \brief Get the class id of the TObject being deleted and run Cppyy's /// RecursiveRemove. /// \param[in] object Object being destructed. void PyROOT::TMemoryRegulator::RecursiveRemove(TObject *object) { auto cppobj = (Cppyy::TCppObject_t)object; Cppyy::TCppType_t klass = 0; ObjectMap_t::iterator ppo = fObjectMap.find(cppobj); if (ppo != fObjectMap.end()) { klass = ppo->second; MemoryRegulator::RecursiveRemove(cppobj, klass); fObjectMap.erase(ppo); } } //////////////////////////////////////////////////////////////////////////// /// \brief Clean up all tracked objects. void PyROOT::TMemoryRegulator::ClearProxiedObjects() { while (!fObjectMap.empty()) { auto elem = fObjectMap.begin(); auto cppobj = elem->first; auto klassid = elem->second; auto pyclass = CreateScopeProxy(klassid); auto pyobj = (CPPInstance *)MemoryRegulator::RetrievePyObject(cppobj, pyclass); if (pyobj && (pyobj->fFlags & CPPInstance::kIsOwner)) { // Only delete the C++ object if the Python proxy owns it. // Invoke RecursiveRemove on it first so that proxy cleanup is done auto o = static_cast<TObject *>(cppobj); RecursiveRemove(o); delete o; } else { // Non-owning proxy, just unregister to clean tables. // The proxy deletion by Python will have no effect on C++, so all good MemoryRegulator::UnregisterPyObject(pyobj, pyclass); } } } <commit_msg>[Exp PyROOT][ROOT-9516] Do not delete proxied object if cppyy does it<commit_after> // Author: Enric Tejedor CERN 08/2019 /************************************************************************* * Copyright (C) 1995-2019, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "TMemoryRegulator.h" #include "ProxyWrappers.h" #include "CPPInstance.h" #include "CPPInstance.h" using namespace CPyCppyy; PyROOT::ObjectMap_t PyROOT::TMemoryRegulator::fObjectMap = PyROOT::ObjectMap_t(); //////////////////////////////////////////////////////////////////////////// /// \brief Constructor. Registers the hooks to run on Cppyy's object /// construction and destruction PyROOT::TMemoryRegulator::TMemoryRegulator() { MemoryRegulator::SetRegisterHook(PyROOT::TMemoryRegulator::RegisterHook); MemoryRegulator::SetUnregisterHook(PyROOT::TMemoryRegulator::UnregisterHook); } //////////////////////////////////////////////////////////////////////////// /// \brief Register a hook that Cppyy runs when constructing an object. /// \param[in] cppobj Address of the object. /// \param[in] klass Class id of the object. /// \return Pair of two booleans. First indicates success, second tells /// Cppyy if we want to continue running RegisterPyObject std::pair<bool, bool> PyROOT::TMemoryRegulator::RegisterHook(Cppyy::TCppObject_t cppobj, Cppyy::TCppType_t klass) { static Cppyy::TCppType_t tobjectTypeID = (Cppyy::TCppType_t)Cppyy::GetScope("TObject"); if (Cppyy::IsSubtype(klass, tobjectTypeID)) { ObjectMap_t::iterator ppo = fObjectMap.find(cppobj); if (ppo == fObjectMap.end()) { fObjectMap.insert({cppobj, klass}); } } return {true, true}; } //////////////////////////////////////////////////////////////////////////// /// \brief Register a hook that Cppyy runs when deleting an object. /// \param[in] cppobj Address of the object. /// \param[in] klass Class id of the object. /// \return Pair of two booleans. First indicates success, second tells /// Cppyy if we want to continue running UnRegisterPyObject std::pair<bool, bool> PyROOT::TMemoryRegulator::UnregisterHook(Cppyy::TCppObject_t cppobj, Cppyy::TCppType_t klass) { static Cppyy::TCppType_t tobjectTypeID = (Cppyy::TCppType_t)Cppyy::GetScope("TObject"); if (Cppyy::IsSubtype(klass, tobjectTypeID)) { ObjectMap_t::iterator ppo = fObjectMap.find(cppobj); if (ppo != fObjectMap.end()) { fObjectMap.erase(ppo); } } return {true, true}; } //////////////////////////////////////////////////////////////////////////// /// \brief Get the class id of the TObject being deleted and run Cppyy's /// RecursiveRemove. /// \param[in] object Object being destructed. void PyROOT::TMemoryRegulator::RecursiveRemove(TObject *object) { auto cppobj = (Cppyy::TCppObject_t)object; Cppyy::TCppType_t klass = 0; ObjectMap_t::iterator ppo = fObjectMap.find(cppobj); if (ppo != fObjectMap.end()) { klass = ppo->second; MemoryRegulator::RecursiveRemove(cppobj, klass); fObjectMap.erase(ppo); } } //////////////////////////////////////////////////////////////////////////// /// \brief Clean up all tracked objects. void PyROOT::TMemoryRegulator::ClearProxiedObjects() { while (!fObjectMap.empty()) { auto elem = fObjectMap.begin(); auto cppobj = elem->first; auto klassid = elem->second; auto pyclass = CreateScopeProxy(klassid); auto pyobj = (CPPInstance *)MemoryRegulator::RetrievePyObject(cppobj, pyclass); if (pyobj && (pyobj->fFlags & CPPInstance::kIsOwner)) { // Only delete the C++ object if the Python proxy owns it. // If it is a value, cppyy deletes it in RecursiveRemove as part of // the proxy cleanup. auto o = static_cast<TObject *>(cppobj); bool isValue = pyobj->fFlags & CPPInstance::kIsValue; RecursiveRemove(o); if (!isValue) delete o; } else { // Non-owning proxy, just unregister to clean tables. // The proxy deletion by Python will have no effect on C++, so all good MemoryRegulator::UnregisterPyObject(pyobj, pyclass); } } } <|endoftext|>
<commit_before>/* * Copyright (c) 2010, Willow Garage, 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 the Willow Garage, 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 <stdio.h> #include <tf2/buffer_core.h> #include "tf2/time.h" #include <boost/lexical_cast.hpp> #include <chrono> using std::chrono::system_clock; using std::chrono::steady_clock; using std::chrono::high_resolution_clock; int main(int argc, char** argv) { uint32_t num_levels = 10; // if (argc > 1) // { // num_levels = boost::lexical_cast<uint32_t>(argv[1]); // } tf2::BufferCore bc; geometry_msgs::TransformStamped t; t.header.stamp = 1; t.header.frame_id = "root"; t.child_frame_id = "0"; t.transform.translation.x = 1; t.transform.rotation.w = 1.0; bc.setTransform(t, "me"); t.header.stamp = 2; bc.setTransform(t, "me"); for (uint32_t i = 1; i < num_levels/2; ++i) { for (uint32_t j = 1; j < 3; ++j) { std::stringstream parent_ss; parent_ss << (i - 1); std::stringstream child_ss; child_ss << i; t.header.stamp = tf2::Time(j); t.header.frame_id = parent_ss.str(); t.child_frame_id = child_ss.str(); bc.setTransform(t, "me"); } } t.header.frame_id = "root"; std::stringstream ss; ss << num_levels/2; t.header.stamp = 1; t.child_frame_id = ss.str(); bc.setTransform(t, "me"); t.header.stamp = 2; bc.setTransform(t, "me"); for (uint32_t i = num_levels/2 + 1; i < num_levels; ++i) { for (uint32_t j = 1; j < 3; ++j) { std::stringstream parent_ss; parent_ss << (i - 1); std::stringstream child_ss; child_ss << i; t.header.stamp = tf2::Time(j); t.header.frame_id = parent_ss.str(); t.child_frame_id = child_ss.str(); bc.setTransform(t, "me"); } } //logInfo_STREAM(bc.allFramesAsYAML()); std::string v_frame0 = boost::lexical_cast<std::string>(num_levels - 1); std::string v_frame1 = boost::lexical_cast<std::string>(num_levels/2 - 1); printf("%s to %s\n", v_frame0.c_str(), v_frame1.c_str()); geometry_msgs::TransformStamped out_t; const uint32_t count = 1000000; printf("Doing %d %d-level tests\n", count, num_levels); #if 01 { steady_clock::time_point start = steady_clock::now(); for (uint32_t i = 0; i < count; ++i) { out_t = bc.lookupTransform(v_frame1, v_frame0, 0); } steady_clock::time_point end = steady_clock::now(); double dur = std::chrono::duration_cast<std::chrono::duration<double>>(end - start).count(); printf("lookupTransform at Time(0) took: %f (secs) for an average of: %.9f (secs)\n", dur, dur / (double)count); } #endif #if 01 { steady_clock::time_point start = steady_clock::now(); for (uint32_t i = 0; i < count; ++i) { out_t = bc.lookupTransform(v_frame1, v_frame0, tf2::Time(1)); } steady_clock::time_point end = steady_clock::now(); double dur = std::chrono::duration_cast<std::chrono::duration<double>>(end - start).count(); printf("lookupTransform at Time(1) took: %f for an average of: %.9f\n", dur, dur / (double)count); } #endif #if 01 { steady_clock::time_point start = steady_clock::now(); for (uint32_t i = 0; i < count; ++i) { out_t = bc.lookupTransform(v_frame1, v_frame0, tf2::Time(1.5)); } steady_clock::time_point end = steady_clock::now(); double dur = std::chrono::duration_cast<std::chrono::duration<double>>(end - start).count(); printf("lookupTransform at Time(1.5) took %f for an average of %.9f\n", dur, dur / (double)count); } #endif #if 01 { steady_clock::time_point start = steady_clock::now(); for (uint32_t i = 0; i < count; ++i) { out_t = bc.lookupTransform(v_frame1, v_frame0, tf2::Time(2)); } steady_clock::time_point end = steady_clock::now(); double dur = std::chrono::duration_cast<std::chrono::duration<double>>(end - start).count(); printf("lookupTransform at Time(2) took %f for an average of %.9f\n", dur, dur / (double)count); } #endif #if 01 { steady_clock::time_point start = steady_clock::now(); for (uint32_t i = 0; i < count; ++i) { bc.canTransform(v_frame1, v_frame0, tf2::Time(0)); } steady_clock::time_point end = steady_clock::now(); double dur = std::chrono::duration_cast<std::chrono::duration<double>>(end - start).count(); printf("canTransform at Time(0) took %f for an average of %.9f\n", dur, dur / (double)count); } #endif #if 01 { steady_clock::time_point start = steady_clock::now(); for (uint32_t i = 0; i < count; ++i) { bc.canTransform(v_frame1, v_frame0, tf2::Time(1)); } steady_clock::time_point end = steady_clock::now(); double dur = std::chrono::duration_cast<std::chrono::duration<double>>(end - start).count(); printf("canTransform at Time(1) took %f for an average of %.9f\n", dur, dur / (double)count); } #endif #if 01 { steady_clock::time_point start = steady_clock::now(); for (uint32_t i = 0; i < count; ++i) { bc.canTransform(v_frame1, v_frame0, tf2::Time(1.5 * 1e9)); } steady_clock::time_point end = steady_clock::now(); double dur = std::chrono::duration_cast<std::chrono::duration<double>>(end - start).count(); printf("canTransform at Time(1.5) took %f for an average of %.9f\n", dur, dur / (double)count); } #endif #if 01 { steady_clock::time_point start = steady_clock::now(); for (uint32_t i = 0; i < count; ++i) { bc.canTransform(v_frame1, v_frame0, tf2::Time(2)); } steady_clock::time_point end = steady_clock::now(); double dur = std::chrono::duration_cast<std::chrono::duration<double>>(end - start).count(); printf("canTransform at Time(2) took %f for an average of %.9f\n", dur, dur / (double)count); } #endif } <commit_msg>third_party: fix tf2 invalid printf arg type<commit_after>/* * Copyright (c) 2010, Willow Garage, 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 the Willow Garage, 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 <stdio.h> #include <tf2/buffer_core.h> #include "tf2/time.h" #include <boost/lexical_cast.hpp> #include <chrono> using std::chrono::system_clock; using std::chrono::steady_clock; using std::chrono::high_resolution_clock; int main(int argc, char** argv) { int num_levels = 10; // if (argc > 1) // { // num_levels = boost::lexical_cast<uint32_t>(argv[1]); // } tf2::BufferCore bc; geometry_msgs::TransformStamped t; t.header.stamp = 1; t.header.frame_id = "root"; t.child_frame_id = "0"; t.transform.translation.x = 1; t.transform.rotation.w = 1.0; bc.setTransform(t, "me"); t.header.stamp = 2; bc.setTransform(t, "me"); for (uint32_t i = 1; i < num_levels/2; ++i) { for (uint32_t j = 1; j < 3; ++j) { std::stringstream parent_ss; parent_ss << (i - 1); std::stringstream child_ss; child_ss << i; t.header.stamp = tf2::Time(j); t.header.frame_id = parent_ss.str(); t.child_frame_id = child_ss.str(); bc.setTransform(t, "me"); } } t.header.frame_id = "root"; std::stringstream ss; ss << num_levels/2; t.header.stamp = 1; t.child_frame_id = ss.str(); bc.setTransform(t, "me"); t.header.stamp = 2; bc.setTransform(t, "me"); for (uint32_t i = num_levels/2 + 1; i < num_levels; ++i) { for (uint32_t j = 1; j < 3; ++j) { std::stringstream parent_ss; parent_ss << (i - 1); std::stringstream child_ss; child_ss << i; t.header.stamp = tf2::Time(j); t.header.frame_id = parent_ss.str(); t.child_frame_id = child_ss.str(); bc.setTransform(t, "me"); } } //logInfo_STREAM(bc.allFramesAsYAML()); std::string v_frame0 = boost::lexical_cast<std::string>(num_levels - 1); std::string v_frame1 = boost::lexical_cast<std::string>(num_levels/2 - 1); printf("%s to %s\n", v_frame0.c_str(), v_frame1.c_str()); geometry_msgs::TransformStamped out_t; const int count = 1000000; printf("Doing %d %d-level tests\n", count, num_levels); #if 01 { steady_clock::time_point start = steady_clock::now(); for (uint32_t i = 0; i < count; ++i) { out_t = bc.lookupTransform(v_frame1, v_frame0, 0); } steady_clock::time_point end = steady_clock::now(); double dur = std::chrono::duration_cast<std::chrono::duration<double>>(end - start).count(); printf("lookupTransform at Time(0) took: %f (secs) for an average of: %.9f (secs)\n", dur, dur / (double)count); } #endif #if 01 { steady_clock::time_point start = steady_clock::now(); for (uint32_t i = 0; i < count; ++i) { out_t = bc.lookupTransform(v_frame1, v_frame0, tf2::Time(1)); } steady_clock::time_point end = steady_clock::now(); double dur = std::chrono::duration_cast<std::chrono::duration<double>>(end - start).count(); printf("lookupTransform at Time(1) took: %f for an average of: %.9f\n", dur, dur / (double)count); } #endif #if 01 { steady_clock::time_point start = steady_clock::now(); for (uint32_t i = 0; i < count; ++i) { out_t = bc.lookupTransform(v_frame1, v_frame0, tf2::Time(1.5)); } steady_clock::time_point end = steady_clock::now(); double dur = std::chrono::duration_cast<std::chrono::duration<double>>(end - start).count(); printf("lookupTransform at Time(1.5) took %f for an average of %.9f\n", dur, dur / (double)count); } #endif #if 01 { steady_clock::time_point start = steady_clock::now(); for (uint32_t i = 0; i < count; ++i) { out_t = bc.lookupTransform(v_frame1, v_frame0, tf2::Time(2)); } steady_clock::time_point end = steady_clock::now(); double dur = std::chrono::duration_cast<std::chrono::duration<double>>(end - start).count(); printf("lookupTransform at Time(2) took %f for an average of %.9f\n", dur, dur / (double)count); } #endif #if 01 { steady_clock::time_point start = steady_clock::now(); for (uint32_t i = 0; i < count; ++i) { bc.canTransform(v_frame1, v_frame0, tf2::Time(0)); } steady_clock::time_point end = steady_clock::now(); double dur = std::chrono::duration_cast<std::chrono::duration<double>>(end - start).count(); printf("canTransform at Time(0) took %f for an average of %.9f\n", dur, dur / (double)count); } #endif #if 01 { steady_clock::time_point start = steady_clock::now(); for (uint32_t i = 0; i < count; ++i) { bc.canTransform(v_frame1, v_frame0, tf2::Time(1)); } steady_clock::time_point end = steady_clock::now(); double dur = std::chrono::duration_cast<std::chrono::duration<double>>(end - start).count(); printf("canTransform at Time(1) took %f for an average of %.9f\n", dur, dur / (double)count); } #endif #if 01 { steady_clock::time_point start = steady_clock::now(); for (uint32_t i = 0; i < count; ++i) { bc.canTransform(v_frame1, v_frame0, tf2::Time(1.5 * 1e9)); } steady_clock::time_point end = steady_clock::now(); double dur = std::chrono::duration_cast<std::chrono::duration<double>>(end - start).count(); printf("canTransform at Time(1.5) took %f for an average of %.9f\n", dur, dur / (double)count); } #endif #if 01 { steady_clock::time_point start = steady_clock::now(); for (uint32_t i = 0; i < count; ++i) { bc.canTransform(v_frame1, v_frame0, tf2::Time(2)); } steady_clock::time_point end = steady_clock::now(); double dur = std::chrono::duration_cast<std::chrono::duration<double>>(end - start).count(); printf("canTransform at Time(2) took %f for an average of %.9f\n", dur, dur / (double)count); } #endif } <|endoftext|>
<commit_before>/* * Copyright 2008-2010 NVIDIA Corporation * * 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. */ #pragma once #include <thrust/detail/segmented_storage.h> #include <thrust/for_each.h> #include <thrust/reduce.h> #include <functional> namespace thrust { namespace detail { template<typename T, typename Allocator> segmented_storage<T,Allocator> ::segmented_storage(void) :m_storage(choose_number_of_segments()) { ; } // end segmented_storage::segmented_storage() template<typename T, typename Allocator> segmented_storage<T,Allocator> ::segmented_storage(size_type n) :m_storage(choose_number_of_segments()) { allocate(n); } // end segmented_storage::segmented_storage() template<typename T, typename Allocator> segmented_storage<T,Allocator> ::~segmented_storage(void) { deallocate(); } // end segmented_storage::~segmented_storage() template<typename T, typename Allocator> typename segmented_storage<T,Allocator>::size_type segmented_storage<T,Allocator> ::size(void) const { // return the sum of the sizes of the individual storages return thrust::reduce(m_storage.begin(), m_storage.end(), std::mem_fun_ref(&storage_type::size)); } // end segmented_storage::size() template<typename T, typename Allocator> typename segmented_storage<T,Allocator>::size_type segmented_storage<T,Allocator> ::max_size(void) const { // return the sum of the max_sizes of the individual storages return thrust::reduce(m_storage.begin(), m_storage.end(), std::mem_fun_ref(&storage_type::max_size)); } // end segmented_storage::max_size() template<typename T, typename Allocator> typename segmented_storage<T,Allocator>::iterator segmented_storage<T,Allocator> ::begin(void) { return thrust::detail::make_segmented_iterator(m_storage.begin(), m_storage.end()); } // end segmented_storage::begin() template<typename T, typename Allocator> typename segmented_storage<T,Allocator>::const_iterator segmented_storage<T,Allocator> ::begin(void) const { return thrust::detail::make_segmented_iterator(m_storage.begin(), m_storage.end()); } // end segmented_storage::begin() template<typename T, typename Allocator> typename segmented_storage<T,Allocator>::iterator segmented_storage<T,Allocator> ::end(void) { return thrust::detail::make_segmented_iterator(m_storage.end(), m_storage.end()); } // end segmented_storage::end() template<typename T, typename Allocator> typename segmented_storage<T,Allocator>::const_iterator segmented_storage<T,Allocator> ::end(void) const { return thrust::detail::make_segmented_iterator(m_storage.end(), m_storage.end()); } // end segmented_storage::end() template<typename T, typename Allocator> typename segmented_storage<T,Allocator>::allocator_type segmented_storage<T,Allocator> ::get_allocator(void) const { // return the first storage's allocator i guess return m_storage[0].get_allocator(); } // end segmented_storage::get_allocator() template<typename T, typename Allocator> void segmented_storage<T,Allocator> ::allocate(size_type n) { const size_type m = m_storage.size(); // break up n into m chunks of n/m (except possibly the last one) // if n is small, just give it all to the first segment const size_type size_per_segment = (n > m) ? (n / m) : n; // if there are leftovers, give them to the first segment size_type num_leftover = 0; if(n > m * size_per_segment) { num_leftover = n - (m * size_per_segment); } // XXX might want to parallelize this with for_each size_type i = 0; while(n > 0) { // XXX don't use thrust::min here to avoid bringing in all of extrema.h const size_type size_to_allocate = ((size_per_segment < n) ? size_per_segment : n) + num_leftover; m_storage[i].allocate(size_to_allocate); n -= size_to_allocate; ++i; num_leftover = 0; } // end while } // segmented_storage::allocate() template<typename T, typename Allocator> void segmented_storage<T,Allocator> ::deallocate(void) { thrust::for_each(m_storage.begin(), m_storage.end(), std::mem_fun_ref(&storage_type::deallocate)); } // end segmented_storage::deallocate(); template<typename T, typename Allocator> void segmented_storage<T,Allocator> ::swap(segmented_storage &x) { thrust::swap(m_storage, x.m_storage); } // end segmented_storage::swap() template<typename T, typename Allocator> typename segmented_storage<T,Allocator>::size_type segmented_storage<T,Allocator> ::choose_number_of_segments(void) { return 2; } // end segmented_storage::choose_number_of_segments() } // end detail } // end thrust <commit_msg>backout<commit_after>/* * Copyright 2008-2010 NVIDIA Corporation * * 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. */ #pragma once #include <thrust/detail/segmented_storage.h> #include <thrust/for_each.h> #include <thrust/reduce.h> #include <functional> namespace thrust { namespace detail { template<typename T, typename Allocator> segmented_storage<T,Allocator> ::segmented_storage(void) :m_storage(choose_number_of_segments()) { ; } // end segmented_storage::segmented_storage() template<typename T, typename Allocator> segmented_storage<T,Allocator> ::segmented_storage(size_type n) :m_storage(choose_number_of_segments()) { std::cout << "Allocator: " << typeid(Allocator).name() << std::endl; allocate(n); } // end segmented_storage::segmented_storage() template<typename T, typename Allocator> segmented_storage<T,Allocator> ::~segmented_storage(void) { deallocate(); } // end segmented_storage::~segmented_storage() template<typename T, typename Allocator> typename segmented_storage<T,Allocator>::size_type segmented_storage<T,Allocator> ::size(void) const { // return the sum of the sizes of the individual storages return thrust::reduce(m_storage.begin(), m_storage.end(), std::mem_fun_ref(&storage_type::size)); } // end segmented_storage::size() template<typename T, typename Allocator> typename segmented_storage<T,Allocator>::size_type segmented_storage<T,Allocator> ::max_size(void) const { // return the sum of the max_sizes of the individual storages return thrust::reduce(m_storage.begin(), m_storage.end(), std::mem_fun_ref(&storage_type::max_size)); } // end segmented_storage::max_size() template<typename T, typename Allocator> typename segmented_storage<T,Allocator>::iterator segmented_storage<T,Allocator> ::begin(void) { return thrust::detail::make_segmented_iterator(m_storage.begin(), m_storage.end()); } // end segmented_storage::begin() template<typename T, typename Allocator> typename segmented_storage<T,Allocator>::const_iterator segmented_storage<T,Allocator> ::begin(void) const { return thrust::detail::make_segmented_iterator(m_storage.begin(), m_storage.end()); } // end segmented_storage::begin() template<typename T, typename Allocator> typename segmented_storage<T,Allocator>::iterator segmented_storage<T,Allocator> ::end(void) { return thrust::detail::make_segmented_iterator(m_storage.end(), m_storage.end()); } // end segmented_storage::end() template<typename T, typename Allocator> typename segmented_storage<T,Allocator>::const_iterator segmented_storage<T,Allocator> ::end(void) const { return thrust::detail::make_segmented_iterator(m_storage.end(), m_storage.end()); } // end segmented_storage::end() template<typename T, typename Allocator> typename segmented_storage<T,Allocator>::allocator_type segmented_storage<T,Allocator> ::get_allocator(void) const { // return the first storage's allocator i guess return m_storage[0].get_allocator(); } // end segmented_storage::get_allocator() template<typename T, typename Allocator> void segmented_storage<T,Allocator> ::allocate(size_type n) { const size_type m = m_storage.size(); // break up n into m chunks of n/m (except possibly the last one) // if n is small, just give it all to the first segment const size_type size_per_segment = (n > m) ? (n / m) : n; // if there are leftovers, give them to the first segment size_type num_leftover = 0; if(n > m * size_per_segment) { num_leftover = n - (m * size_per_segment); } // XXX might want to parallelize this with for_each size_type i = 0; while(n > 0) { // XXX don't use thrust::min here to avoid bringing in all of extrema.h const size_type size_to_allocate = ((size_per_segment < n) ? size_per_segment : n) + num_leftover; m_storage[i].allocate(size_to_allocate); n -= size_to_allocate; ++i; num_leftover = 0; } // end while } // segmented_storage::allocate() template<typename T, typename Allocator> void segmented_storage<T,Allocator> ::deallocate(void) { thrust::for_each(m_storage.begin(), m_storage.end(), std::mem_fun_ref(&storage_type::deallocate)); } // end segmented_storage::deallocate(); template<typename T, typename Allocator> void segmented_storage<T,Allocator> ::swap(segmented_storage &x) { thrust::swap(m_storage, x.m_storage); } // end segmented_storage::swap() template<typename T, typename Allocator> typename segmented_storage<T,Allocator>::size_type segmented_storage<T,Allocator> ::choose_number_of_segments(void) { return 2; } // end segmented_storage::choose_number_of_segments() } // end detail } // end thrust <|endoftext|>
<commit_before>/* worker.cpp * Copyright (C) 2003-2005 Tommi Maekitalo * * 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 * is provided AS IS, WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, and * NON-INFRINGEMENT. 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 St, Fifth Floor, Boston, MA 02110-1301 USA * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, 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 OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #include "tnt/worker.h" #include "tnt/dispatcher.h" #include "tnt/job.h" #include <tnt/httprequest.h> #include <tnt/httpreply.h> #include <tnt/httperror.h> #include <tnt/http.h> #include <tnt/poller.h> #include <tnt/sessionscope.h> #include <cxxtools/log.h> #include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> #include <locale> #include <errno.h> log_define("tntnet.worker") namespace { class ComponentUnloadLock { tnt::Component& comp; public: ComponentUnloadLock(tnt::Component& c) : comp(c) { comp.lock(); } ~ComponentUnloadLock() { comp.unlock(); } }; static const char stateStarting[] = "0 starting"; static const char stateWaitingForJob[] = "1 waiting for job"; static const char stateParsing[] = "2 parsing request"; static const char statePostParsing[] = "3 post parsing"; static const char stateDispatch[] = "4 dispatch"; static const char stateProcessingRequest[] = "5 processing request"; static const char stateFlush[] = "6 flush"; static const char stateSendReply[] = "7 send reply"; static const char stateSendError[] = "8 send error"; static const char stateStopping[] = "9 stopping"; } namespace tnt { cxxtools::Mutex Worker::mutex; unsigned Worker::nextThreadNumber = 0; Worker::workers_type Worker::workers; unsigned Worker::compLifetime = 600; unsigned Worker::maxRequestTime = 600; unsigned Worker::reportStateTime = 0; time_t Worker::nextReportStateTime = 0; unsigned Worker::minThreads = 5; bool Worker::enableCompression = true; Worker::ComploaderPoolType Worker::comploaderPool; Worker::Worker(Tntnet& app) : application(app), comploaderObject(comploaderPool.get()), comploader(comploaderObject), threadId(0), state(stateStarting), lastWaitTime(0) { log_debug("initialize thread " << threadId); cxxtools::MutexLock lock(mutex); workers.insert(this); } Worker::~Worker() { cxxtools::MutexLock lock(mutex); workers.erase(this); comploader.cleanup(0); log_debug("delete worker " << threadId << " - " << workers.size() << " threads left - " << application.getQueue().getWaitThreadCount() << " waiting threads"); } void Worker::run() { threadId = pthread_self(); Jobqueue& queue = application.getQueue(); log_debug("start thread " << threadId); while (queue.getWaitThreadCount() < minThreads) { log_debug("waiting for job"); state = stateWaitingForJob; Jobqueue::JobPtr j = queue.get(); if (Tntnet::shouldStop()) { log_warn("stop worker"); break; } log_debug("got job - fd=" << j->getFd()); std::iostream& socket = j->getStream(); try { bool keepAlive; do { time(&lastWaitTime); log_debug("read request"); keepAlive = false; state = stateParsing; j->getParser().parse(socket); state = statePostParsing; if (socket.eof()) log_debug("eof"); else if (j->getParser().failed()) { state = stateSendError; log_warn("bad request"); socket << "HTTP/1.0 500 bad request\r\n" "Content-Type: text/html\r\n" "\r\n" "<html><body><h1>Error</h1><p>bad request</p></body></html>" << std::endl; } else if (socket.fail()) log_error("socket failed"); else { j->getRequest().doPostParse(); j->setWrite(); keepAlive = processRequest(j->getRequest(), socket, j->decrementKeepAliveCounter()); if (keepAlive) { j->setRead(); j->clear(); // if there is something to do and no threads waiting, we take // the next job just to improve resposiveness. if (queue.getWaitThreadCount() == 0 && !queue.empty()) { application.getPoller().addIdleJob(j); keepAlive = false; } else { struct pollfd fd; fd.fd = j->getFd(); fd.events = POLLIN; if (::poll(&fd, 1, Job::getSocketReadTimeout()) == 0) { application.getPoller().addIdleJob(j); keepAlive = false; } } } } } while (keepAlive); } catch (const cxxtools::net::Timeout& e) { log_debug("timeout - put job in poller"); application.getPoller().addIdleJob(j); } catch (const cxxtools::net::Exception& e) { if (e.getErrno() != ENOENT) log_warn("unexpected exception: " << e.what()); } catch (const std::exception& e) { log_warn("unexpected exception: " << e.what()); } } time(&lastWaitTime); log_debug("end worker-thread " << threadId); state = stateStopping; } bool Worker::processRequest(HttpRequest& request, std::iostream& socket, unsigned keepAliveCount) { // log message log_info("process request: " << request.getMethod() << ' ' << request.getQuery() << " from client " << request.getPeerIp() << " user-Agent \"" << request.getUserAgent() << '"'); // create reply-object HttpReply reply(socket); reply.setVersion(request.getMajorVersion(), request.getMinorVersion()); reply.setMethod(request.getMethod()); std::locale loc = request.getLocale(); reply.out().imbue(loc); reply.sout().imbue(loc); if (request.keepAlive()) reply.setKeepAliveCounter(keepAliveCount); if (enableCompression) reply.setAcceptEncoding(request.getEncoding()); // process request try { try { dispatch(request, reply); if (!request.keepAlive() || !reply.keepAlive()) keepAliveCount = 0; if (keepAliveCount > 0) log_debug("keep alive"); else { log_debug("no keep alive request/reply=" << request.keepAlive() << '/' << reply.keepAlive()); } } catch (const HttpError& e) { throw; } catch (const std::exception& e) { throw HttpError(HTTP_INTERNAL_SERVER_ERROR, e.what()); } } catch (const HttpError& e) { state = stateSendError; log_warn("http-Error: " << e.what()); HttpReply reply(socket); reply.setVersion(request.getMajorVersion(), request.getMinorVersion()); if (request.keepAlive()) reply.setKeepAliveCounter(keepAliveCount); else keepAliveCount = 0; reply.out() << "<html><body><h1>Error</h1><p>" << e.what() << "</p></body></html>" << std::endl; reply.sendReply(e.getErrcode(), e.getErrmsg()); } return keepAliveCount > 0; } void Worker::dispatch(HttpRequest& request, HttpReply& reply) { state = stateDispatch; const std::string& url = request.getUrl(); log_debug("dispatch " << request.getQuery()); if (!HttpRequest::checkUrl(url)) throw HttpError(HTTP_BAD_REQUEST, "illegal url"); Dispatcher::PosType pos(application.getDispatcher(), request.getUrl()); while (true) { state = stateDispatch; // pos.getNext() throws NotFoundException at end Dispatcher::CompidentType ci = pos.getNext(); try { log_debug("load component " << ci); Component& comp = comploader.fetchComp(ci, application.getDispatcher()); ComponentUnloadLock unload_lock(comp); request.setPathInfo(ci.hasPathInfo() ? ci.getPathInfo() : url); request.setArgs(ci.getArgs()); application.getScopemanager().preCall(request, ci.libname); log_debug("call component " << ci << " path " << request.getPathInfo()); state = stateProcessingRequest; unsigned http_return = comp(request, reply, request.getQueryParams()); if (http_return != DECLINED) { if (reply.isDirectMode()) { log_info("request ready, returncode " << http_return); state = stateFlush; reply.out().flush(); } else { log_info("request ready, returncode " << http_return << " - ContentSize: " << reply.getContentSize()); application.getScopemanager().postCall(request, reply, ci.libname); state = stateSendReply; reply.sendReply(http_return); } if (reply.out()) log_debug("reply sent"); else log_warn("stream error"); return; } else log_debug("component " << ci << " returned DECLINED"); } catch (const cxxtools::dl::DlopenError& e) { log_warn("dl::DlopenError catched - libname " << e.getLibname()); } catch (const cxxtools::dl::SymbolNotFound& e) { log_warn("dl::SymbolNotFound catched - symbol " << e.getSymbol()); } } throw NotFoundException(request.getUrl()); } void Worker::timer() { time_t currentTime; time(&currentTime); bool reportState = false; if (reportStateTime > 0 && currentTime > nextReportStateTime) { if (nextReportStateTime) reportState = true; nextReportStateTime = currentTime + reportStateTime; } cxxtools::MutexLock lock(mutex); for (workers_type::iterator it = workers.begin(); it != workers.end(); ++it) { (*it)->healthCheck(currentTime); (*it)->cleanup(compLifetime); if (reportState) log_info("threadstate " << (*it)->threadId << ": " << (*it)->state); } } void Worker::healthCheck(time_t currentTime) { if (state != stateWaitingForJob && lastWaitTime != 0 && maxRequestTime > 0) { if (currentTime - lastWaitTime > maxRequestTime) { log_fatal("requesttime " << maxRequestTime << " seconds in thread " << threadId << " exceeded - exit process"); log_info("current state: " << state); exit(111); } } } Worker::workers_type::size_type Worker::getCountThreads() { cxxtools::MutexLock lock(mutex); return workers.size(); } } <commit_msg>remove unused include<commit_after>/* worker.cpp * Copyright (C) 2003-2005 Tommi Maekitalo * * 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 * is provided AS IS, WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, and * NON-INFRINGEMENT. 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 St, Fifth Floor, Boston, MA 02110-1301 USA * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, 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 OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #include "tnt/worker.h" #include "tnt/dispatcher.h" #include "tnt/job.h" #include <tnt/httprequest.h> #include <tnt/httpreply.h> #include <tnt/httperror.h> #include <tnt/http.h> #include <tnt/poller.h> #include <cxxtools/log.h> #include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> #include <locale> #include <errno.h> log_define("tntnet.worker") namespace { class ComponentUnloadLock { tnt::Component& comp; public: ComponentUnloadLock(tnt::Component& c) : comp(c) { comp.lock(); } ~ComponentUnloadLock() { comp.unlock(); } }; static const char stateStarting[] = "0 starting"; static const char stateWaitingForJob[] = "1 waiting for job"; static const char stateParsing[] = "2 parsing request"; static const char statePostParsing[] = "3 post parsing"; static const char stateDispatch[] = "4 dispatch"; static const char stateProcessingRequest[] = "5 processing request"; static const char stateFlush[] = "6 flush"; static const char stateSendReply[] = "7 send reply"; static const char stateSendError[] = "8 send error"; static const char stateStopping[] = "9 stopping"; } namespace tnt { cxxtools::Mutex Worker::mutex; unsigned Worker::nextThreadNumber = 0; Worker::workers_type Worker::workers; unsigned Worker::compLifetime = 600; unsigned Worker::maxRequestTime = 600; unsigned Worker::reportStateTime = 0; time_t Worker::nextReportStateTime = 0; unsigned Worker::minThreads = 5; bool Worker::enableCompression = true; Worker::ComploaderPoolType Worker::comploaderPool; Worker::Worker(Tntnet& app) : application(app), comploaderObject(comploaderPool.get()), comploader(comploaderObject), threadId(0), state(stateStarting), lastWaitTime(0) { log_debug("initialize thread " << threadId); cxxtools::MutexLock lock(mutex); workers.insert(this); } Worker::~Worker() { cxxtools::MutexLock lock(mutex); workers.erase(this); comploader.cleanup(0); log_debug("delete worker " << threadId << " - " << workers.size() << " threads left - " << application.getQueue().getWaitThreadCount() << " waiting threads"); } void Worker::run() { threadId = pthread_self(); Jobqueue& queue = application.getQueue(); log_debug("start thread " << threadId); while (queue.getWaitThreadCount() < minThreads) { log_debug("waiting for job"); state = stateWaitingForJob; Jobqueue::JobPtr j = queue.get(); if (Tntnet::shouldStop()) { log_warn("stop worker"); break; } log_debug("got job - fd=" << j->getFd()); std::iostream& socket = j->getStream(); try { bool keepAlive; do { time(&lastWaitTime); log_debug("read request"); keepAlive = false; state = stateParsing; j->getParser().parse(socket); state = statePostParsing; if (socket.eof()) log_debug("eof"); else if (j->getParser().failed()) { state = stateSendError; log_warn("bad request"); socket << "HTTP/1.0 500 bad request\r\n" "Content-Type: text/html\r\n" "\r\n" "<html><body><h1>Error</h1><p>bad request</p></body></html>" << std::endl; } else if (socket.fail()) log_error("socket failed"); else { j->getRequest().doPostParse(); j->setWrite(); keepAlive = processRequest(j->getRequest(), socket, j->decrementKeepAliveCounter()); if (keepAlive) { j->setRead(); j->clear(); // if there is something to do and no threads waiting, we take // the next job just to improve resposiveness. if (queue.getWaitThreadCount() == 0 && !queue.empty()) { application.getPoller().addIdleJob(j); keepAlive = false; } else { struct pollfd fd; fd.fd = j->getFd(); fd.events = POLLIN; if (::poll(&fd, 1, Job::getSocketReadTimeout()) == 0) { application.getPoller().addIdleJob(j); keepAlive = false; } } } } } while (keepAlive); } catch (const cxxtools::net::Timeout& e) { log_debug("timeout - put job in poller"); application.getPoller().addIdleJob(j); } catch (const cxxtools::net::Exception& e) { if (e.getErrno() != ENOENT) log_warn("unexpected exception: " << e.what()); } catch (const std::exception& e) { log_warn("unexpected exception: " << e.what()); } } time(&lastWaitTime); log_debug("end worker-thread " << threadId); state = stateStopping; } bool Worker::processRequest(HttpRequest& request, std::iostream& socket, unsigned keepAliveCount) { // log message log_info("process request: " << request.getMethod() << ' ' << request.getQuery() << " from client " << request.getPeerIp() << " user-Agent \"" << request.getUserAgent() << '"'); // create reply-object HttpReply reply(socket); reply.setVersion(request.getMajorVersion(), request.getMinorVersion()); reply.setMethod(request.getMethod()); std::locale loc = request.getLocale(); reply.out().imbue(loc); reply.sout().imbue(loc); if (request.keepAlive()) reply.setKeepAliveCounter(keepAliveCount); if (enableCompression) reply.setAcceptEncoding(request.getEncoding()); // process request try { try { dispatch(request, reply); if (!request.keepAlive() || !reply.keepAlive()) keepAliveCount = 0; if (keepAliveCount > 0) log_debug("keep alive"); else { log_debug("no keep alive request/reply=" << request.keepAlive() << '/' << reply.keepAlive()); } } catch (const HttpError& e) { throw; } catch (const std::exception& e) { throw HttpError(HTTP_INTERNAL_SERVER_ERROR, e.what()); } } catch (const HttpError& e) { state = stateSendError; log_warn("http-Error: " << e.what()); HttpReply reply(socket); reply.setVersion(request.getMajorVersion(), request.getMinorVersion()); if (request.keepAlive()) reply.setKeepAliveCounter(keepAliveCount); else keepAliveCount = 0; reply.out() << "<html><body><h1>Error</h1><p>" << e.what() << "</p></body></html>" << std::endl; reply.sendReply(e.getErrcode(), e.getErrmsg()); } return keepAliveCount > 0; } void Worker::dispatch(HttpRequest& request, HttpReply& reply) { state = stateDispatch; const std::string& url = request.getUrl(); log_debug("dispatch " << request.getQuery()); if (!HttpRequest::checkUrl(url)) throw HttpError(HTTP_BAD_REQUEST, "illegal url"); Dispatcher::PosType pos(application.getDispatcher(), request.getUrl()); while (true) { state = stateDispatch; // pos.getNext() throws NotFoundException at end Dispatcher::CompidentType ci = pos.getNext(); try { log_debug("load component " << ci); Component& comp = comploader.fetchComp(ci, application.getDispatcher()); ComponentUnloadLock unload_lock(comp); request.setPathInfo(ci.hasPathInfo() ? ci.getPathInfo() : url); request.setArgs(ci.getArgs()); application.getScopemanager().preCall(request, ci.libname); log_debug("call component " << ci << " path " << request.getPathInfo()); state = stateProcessingRequest; unsigned http_return = comp(request, reply, request.getQueryParams()); if (http_return != DECLINED) { if (reply.isDirectMode()) { log_info("request ready, returncode " << http_return); state = stateFlush; reply.out().flush(); } else { log_info("request ready, returncode " << http_return << " - ContentSize: " << reply.getContentSize()); application.getScopemanager().postCall(request, reply, ci.libname); state = stateSendReply; reply.sendReply(http_return); } if (reply.out()) log_debug("reply sent"); else log_warn("stream error"); return; } else log_debug("component " << ci << " returned DECLINED"); } catch (const cxxtools::dl::DlopenError& e) { log_warn("dl::DlopenError catched - libname " << e.getLibname()); } catch (const cxxtools::dl::SymbolNotFound& e) { log_warn("dl::SymbolNotFound catched - symbol " << e.getSymbol()); } } throw NotFoundException(request.getUrl()); } void Worker::timer() { time_t currentTime; time(&currentTime); bool reportState = false; if (reportStateTime > 0 && currentTime > nextReportStateTime) { if (nextReportStateTime) reportState = true; nextReportStateTime = currentTime + reportStateTime; } cxxtools::MutexLock lock(mutex); for (workers_type::iterator it = workers.begin(); it != workers.end(); ++it) { (*it)->healthCheck(currentTime); (*it)->cleanup(compLifetime); if (reportState) log_info("threadstate " << (*it)->threadId << ": " << (*it)->state); } } void Worker::healthCheck(time_t currentTime) { if (state != stateWaitingForJob && lastWaitTime != 0 && maxRequestTime > 0) { if (currentTime - lastWaitTime > maxRequestTime) { log_fatal("requesttime " << maxRequestTime << " seconds in thread " << threadId << " exceeded - exit process"); log_info("current state: " << state); exit(111); } } } Worker::workers_type::size_type Worker::getCountThreads() { cxxtools::MutexLock lock(mutex); return workers.size(); } } <|endoftext|>
<commit_before>/* worker.cpp Copyright (C) 2003-2005 Tommi Maekitalo This file is part of tntnet. Tntnet 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. Tntnet 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 tntnet; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "tnt/worker.h" #include "tnt/dispatcher.h" #include "tnt/job.h" #include <tnt/httprequest.h> #include <tnt/httpreply.h> #include <tnt/httperror.h> #include <tnt/http.h> #include <tnt/poller.h> #include <tnt/sessionscope.h> #include <cxxtools/log.h> #include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> #include <locale> log_define("tntnet.worker") namespace { class ComponentUnloadLock { tnt::Component& comp; public: ComponentUnloadLock(tnt::Component& c) : comp(c) { comp.lock(); } ~ComponentUnloadLock() { comp.unlock(); } }; static const char stateStarting[] = "0 starting"; static const char stateWaitingForJob[] = "1 waiting for job"; static const char stateParsing[] = "2 parsing request"; static const char statePostParsing[] = "3 post parsing"; static const char stateDispatch[] = "4 dispatch"; static const char stateProcessingRequest[] = "5 processing request"; static const char stateFlush[] = "6 flush"; static const char stateSendReply[] = "7 send reply"; static const char stateSendError[] = "8 send error"; static const char stateStopping[] = "9 stopping"; } namespace tnt { cxxtools::Mutex Worker::mutex; unsigned Worker::nextThreadNumber = 0; Worker::workers_type Worker::workers; unsigned Worker::compLifetime = 600; unsigned Worker::maxRequestTime = 600; unsigned Worker::reportStateTime = 0; time_t Worker::nextReportStateTime = 0; unsigned Worker::minThreads = 5; bool Worker::enableCompression = false; Worker::ComploaderPoolType Worker::comploaderPool; Worker::Worker(Tntnet& app) : application(app), comploaderObject(comploaderPool.get()), comploader(comploaderObject), threadId(0), state(stateStarting), lastWaitTime(0) { log_debug("initialize thread " << threadId); cxxtools::MutexLock lock(mutex); workers.insert(this); } Worker::~Worker() { cxxtools::MutexLock lock(mutex); workers.erase(this); comploader.cleanup(0); log_debug("delete worker " << threadId << " - " << workers.size() << " threads left - " << application.getQueue().getWaitThreadCount() << " waiting threads"); } void Worker::run() { threadId = pthread_self(); Jobqueue& queue = application.getQueue(); log_debug("start thread " << threadId); while (queue.getWaitThreadCount() < minThreads) { log_debug("waiting for job"); state = stateWaitingForJob; Jobqueue::JobPtr j = queue.get(); log_debug("got job - fd=" << j->getFd()); std::iostream& socket = j->getStream(); try { bool keepAlive; do { time(&lastWaitTime); keepAlive = false; log_debug("call parser"); state = stateParsing; j->getParser().parse(socket); state = statePostParsing; if (socket.eof()) log_debug("eof"); else if (j->getParser().failed()) { state = stateSendError; log_warn("bad request"); socket << "HTTP/1.0 500 bad request\r\n" "Content-Type: text/html\r\n" "\r\n" "<html><body><h1>Error</h1><p>bad request</p></body></html>" << std::endl; } else if (socket.fail()) log_error("socket failed"); else { j->getRequest().doPostParse(); j->setWrite(); keepAlive = processRequest(j->getRequest(), socket, j->decrementKeepAliveCounter()); if (keepAlive) { j->setRead(); j->clear(); // if there is something to do and no threads waiting, we take // the next job just to improve resposiveness. if (queue.getWaitThreadCount() == 0 && !queue.empty()) { application.getPoller().addIdleJob(j); keepAlive = false; } } } } while (keepAlive); } catch (const cxxtools::net::Timeout& e) { log_debug("timeout - put job in poller"); application.getPoller().addIdleJob(j); } catch (const std::exception& e) { log_warn("unexpected exception: " << e.what()); } } time(&lastWaitTime); log_debug("end worker-thread " << threadId); state = stateStopping; } bool Worker::processRequest(HttpRequest& request, std::iostream& socket, unsigned keepAliveCount) { // log message log_info("process request: " << request.getMethod() << ' ' << request.getUrl() << " from client " << request.getPeerIp() << " user-Agent \"" << request.getUserAgent() << '"'); // create reply-object HttpReply reply(socket); reply.setVersion(request.getMajorVersion(), request.getMinorVersion()); reply.setMethod(request.getMethod()); std::string LANG = request.getLang(); if (!LANG.empty()) { try { std::locale loc(LANG.c_str()); reply.out().imbue(loc); reply.sout().imbue(loc); } catch (const std::exception& e) { log_warn("unknown locale " << LANG); } } if (request.keepAlive()) reply.setKeepAliveCounter(keepAliveCount); // process request try { try { dispatch(request, reply); if (!request.keepAlive() || !reply.keepAlive()) keepAliveCount = 0; if (keepAliveCount > 0) log_debug("keep alive"); else { log_debug("no keep alive request/reply=" << request.keepAlive() << '/' << reply.keepAlive()); } } catch (const HttpError& e) { throw; } catch (const std::exception& e) { throw HttpError(HTTP_INTERNAL_SERVER_ERROR, e.what()); } } catch (const HttpError& e) { state = stateSendError; log_warn("http-Error: " << e.what()); socket << "HTTP/1.0 " << std::string(e.what(), 3) << "\r\n" "Content-Type: text/html\r\n" "\r\n" "<html><body><h1>Error</h1><p>" << e.what() << "</p></body></html>" << std::endl; return false; } return keepAliveCount > 0; } void Worker::dispatch(HttpRequest& request, HttpReply& reply) { state = stateDispatch; const std::string& url = request.getUrl(); log_info("dispatch " << request.getQuery()); if (!HttpRequest::checkUrl(url)) throw HttpError(HTTP_BAD_REQUEST, "illegal url"); Dispatcher::PosType pos(application.getDispatcher(), request.getUrl()); while (true) { state = stateDispatch; // pos.getNext() throws NotFoundException at end Dispatcher::CompidentType ci = pos.getNext(); try { log_debug("load component " << ci); Component& comp = comploader.fetchComp(ci, application.getDispatcher()); ComponentUnloadLock unload_lock(comp); request.setPathInfo(ci.hasPathInfo() ? ci.getPathInfo() : url); request.setArgs(ci.getArgs()); application.getScopemanager().preCall(request, ci.libname); log_info("call component " << ci << " path " << request.getPathInfo()); state = stateProcessingRequest; unsigned http_return = comp(request, reply, request.getQueryParams()); if (http_return != DECLINED) { if (reply.isDirectMode()) { log_info("request ready, returncode " << http_return); state = stateFlush; reply.out().flush(); } else { log_info("request ready, returncode " << http_return << " - ContentSize: " << reply.getContentSize()); application.getScopemanager().postCall(request, reply, ci.libname); if (enableCompression) reply.setAcceptEncoding(request.getEncoding()); state = stateSendReply; reply.sendReply(http_return); } if (reply.out()) log_info("reply sent"); return; } else log_debug("component " << ci << " returned DECLINED"); } catch (const cxxtools::dl::DlopenError& e) { log_warn("dl::DlopenError catched - libname " << e.getLibname()); } catch (const cxxtools::dl::SymbolNotFound& e) { log_warn("dl::SymbolNotFound catched - symbol " << e.getSymbol()); } } throw NotFoundException(request.getUrl()); } void Worker::timer() { time_t currentTime; time(&currentTime); bool reportState = false; if (reportStateTime > 0 && currentTime > nextReportStateTime) { if (nextReportStateTime) reportState = true; nextReportStateTime = currentTime + reportStateTime; } cxxtools::MutexLock lock(mutex); for (workers_type::iterator it = workers.begin(); it != workers.end(); ++it) { (*it)->healthCheck(currentTime); (*it)->cleanup(compLifetime); if (reportState) log_info("threadstate " << (*it)->threadId << ": " << (*it)->state); } } void Worker::healthCheck(time_t currentTime) { if (state != stateWaitingForJob && lastWaitTime != 0 && maxRequestTime > 0) { if (currentTime - lastWaitTime > maxRequestTime) { log_fatal("requesttime " << maxRequestTime << " seconds in thread " << threadId << " exceeded - exit process"); log_info("current state: " << state); exit(111); } } } Worker::workers_type::size_type Worker::getCountThreads() { cxxtools::MutexLock lock(mutex); return workers.size(); } } <commit_msg>enable compression by default<commit_after>/* worker.cpp Copyright (C) 2003-2005 Tommi Maekitalo This file is part of tntnet. Tntnet 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. Tntnet 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 tntnet; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "tnt/worker.h" #include "tnt/dispatcher.h" #include "tnt/job.h" #include <tnt/httprequest.h> #include <tnt/httpreply.h> #include <tnt/httperror.h> #include <tnt/http.h> #include <tnt/poller.h> #include <tnt/sessionscope.h> #include <cxxtools/log.h> #include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> #include <locale> log_define("tntnet.worker") namespace { class ComponentUnloadLock { tnt::Component& comp; public: ComponentUnloadLock(tnt::Component& c) : comp(c) { comp.lock(); } ~ComponentUnloadLock() { comp.unlock(); } }; static const char stateStarting[] = "0 starting"; static const char stateWaitingForJob[] = "1 waiting for job"; static const char stateParsing[] = "2 parsing request"; static const char statePostParsing[] = "3 post parsing"; static const char stateDispatch[] = "4 dispatch"; static const char stateProcessingRequest[] = "5 processing request"; static const char stateFlush[] = "6 flush"; static const char stateSendReply[] = "7 send reply"; static const char stateSendError[] = "8 send error"; static const char stateStopping[] = "9 stopping"; } namespace tnt { cxxtools::Mutex Worker::mutex; unsigned Worker::nextThreadNumber = 0; Worker::workers_type Worker::workers; unsigned Worker::compLifetime = 600; unsigned Worker::maxRequestTime = 600; unsigned Worker::reportStateTime = 0; time_t Worker::nextReportStateTime = 0; unsigned Worker::minThreads = 5; bool Worker::enableCompression = true; Worker::ComploaderPoolType Worker::comploaderPool; Worker::Worker(Tntnet& app) : application(app), comploaderObject(comploaderPool.get()), comploader(comploaderObject), threadId(0), state(stateStarting), lastWaitTime(0) { log_debug("initialize thread " << threadId); cxxtools::MutexLock lock(mutex); workers.insert(this); } Worker::~Worker() { cxxtools::MutexLock lock(mutex); workers.erase(this); comploader.cleanup(0); log_debug("delete worker " << threadId << " - " << workers.size() << " threads left - " << application.getQueue().getWaitThreadCount() << " waiting threads"); } void Worker::run() { threadId = pthread_self(); Jobqueue& queue = application.getQueue(); log_debug("start thread " << threadId); while (queue.getWaitThreadCount() < minThreads) { log_debug("waiting for job"); state = stateWaitingForJob; Jobqueue::JobPtr j = queue.get(); log_debug("got job - fd=" << j->getFd()); std::iostream& socket = j->getStream(); try { bool keepAlive; do { time(&lastWaitTime); keepAlive = false; log_debug("call parser"); state = stateParsing; j->getParser().parse(socket); state = statePostParsing; if (socket.eof()) log_debug("eof"); else if (j->getParser().failed()) { state = stateSendError; log_warn("bad request"); socket << "HTTP/1.0 500 bad request\r\n" "Content-Type: text/html\r\n" "\r\n" "<html><body><h1>Error</h1><p>bad request</p></body></html>" << std::endl; } else if (socket.fail()) log_error("socket failed"); else { j->getRequest().doPostParse(); j->setWrite(); keepAlive = processRequest(j->getRequest(), socket, j->decrementKeepAliveCounter()); if (keepAlive) { j->setRead(); j->clear(); // if there is something to do and no threads waiting, we take // the next job just to improve resposiveness. if (queue.getWaitThreadCount() == 0 && !queue.empty()) { application.getPoller().addIdleJob(j); keepAlive = false; } } } } while (keepAlive); } catch (const cxxtools::net::Timeout& e) { log_debug("timeout - put job in poller"); application.getPoller().addIdleJob(j); } catch (const std::exception& e) { log_warn("unexpected exception: " << e.what()); } } time(&lastWaitTime); log_debug("end worker-thread " << threadId); state = stateStopping; } bool Worker::processRequest(HttpRequest& request, std::iostream& socket, unsigned keepAliveCount) { // log message log_info("process request: " << request.getMethod() << ' ' << request.getUrl() << " from client " << request.getPeerIp() << " user-Agent \"" << request.getUserAgent() << '"'); // create reply-object HttpReply reply(socket); reply.setVersion(request.getMajorVersion(), request.getMinorVersion()); reply.setMethod(request.getMethod()); std::string LANG = request.getLang(); if (!LANG.empty()) { try { std::locale loc(LANG.c_str()); reply.out().imbue(loc); reply.sout().imbue(loc); } catch (const std::exception& e) { log_warn("unknown locale " << LANG); } } if (request.keepAlive()) reply.setKeepAliveCounter(keepAliveCount); // process request try { try { dispatch(request, reply); if (!request.keepAlive() || !reply.keepAlive()) keepAliveCount = 0; if (keepAliveCount > 0) log_debug("keep alive"); else { log_debug("no keep alive request/reply=" << request.keepAlive() << '/' << reply.keepAlive()); } } catch (const HttpError& e) { throw; } catch (const std::exception& e) { throw HttpError(HTTP_INTERNAL_SERVER_ERROR, e.what()); } } catch (const HttpError& e) { state = stateSendError; log_warn("http-Error: " << e.what()); socket << "HTTP/1.0 " << std::string(e.what(), 3) << "\r\n" "Content-Type: text/html\r\n" "\r\n" "<html><body><h1>Error</h1><p>" << e.what() << "</p></body></html>" << std::endl; return false; } return keepAliveCount > 0; } void Worker::dispatch(HttpRequest& request, HttpReply& reply) { state = stateDispatch; const std::string& url = request.getUrl(); log_info("dispatch " << request.getQuery()); if (!HttpRequest::checkUrl(url)) throw HttpError(HTTP_BAD_REQUEST, "illegal url"); Dispatcher::PosType pos(application.getDispatcher(), request.getUrl()); while (true) { state = stateDispatch; // pos.getNext() throws NotFoundException at end Dispatcher::CompidentType ci = pos.getNext(); try { log_debug("load component " << ci); Component& comp = comploader.fetchComp(ci, application.getDispatcher()); ComponentUnloadLock unload_lock(comp); request.setPathInfo(ci.hasPathInfo() ? ci.getPathInfo() : url); request.setArgs(ci.getArgs()); application.getScopemanager().preCall(request, ci.libname); log_info("call component " << ci << " path " << request.getPathInfo()); state = stateProcessingRequest; unsigned http_return = comp(request, reply, request.getQueryParams()); if (http_return != DECLINED) { if (reply.isDirectMode()) { log_info("request ready, returncode " << http_return); state = stateFlush; reply.out().flush(); } else { log_info("request ready, returncode " << http_return << " - ContentSize: " << reply.getContentSize()); application.getScopemanager().postCall(request, reply, ci.libname); if (enableCompression) reply.setAcceptEncoding(request.getEncoding()); state = stateSendReply; reply.sendReply(http_return); } if (reply.out()) log_info("reply sent"); return; } else log_debug("component " << ci << " returned DECLINED"); } catch (const cxxtools::dl::DlopenError& e) { log_warn("dl::DlopenError catched - libname " << e.getLibname()); } catch (const cxxtools::dl::SymbolNotFound& e) { log_warn("dl::SymbolNotFound catched - symbol " << e.getSymbol()); } } throw NotFoundException(request.getUrl()); } void Worker::timer() { time_t currentTime; time(&currentTime); bool reportState = false; if (reportStateTime > 0 && currentTime > nextReportStateTime) { if (nextReportStateTime) reportState = true; nextReportStateTime = currentTime + reportStateTime; } cxxtools::MutexLock lock(mutex); for (workers_type::iterator it = workers.begin(); it != workers.end(); ++it) { (*it)->healthCheck(currentTime); (*it)->cleanup(compLifetime); if (reportState) log_info("threadstate " << (*it)->threadId << ": " << (*it)->state); } } void Worker::healthCheck(time_t currentTime) { if (state != stateWaitingForJob && lastWaitTime != 0 && maxRequestTime > 0) { if (currentTime - lastWaitTime > maxRequestTime) { log_fatal("requesttime " << maxRequestTime << " seconds in thread " << threadId << " exceeded - exit process"); log_info("current state: " << state); exit(111); } } } Worker::workers_type::size_type Worker::getCountThreads() { cxxtools::MutexLock lock(mutex); return workers.size(); } } <|endoftext|>
<commit_before>/* variable.cpp * Copyright (C) 2003 Tommi Maekitalo * * This program 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 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser 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 * */ #include "tnt/ecppc/variable.h" #include <sstream> #include <locale> namespace tnt { namespace ecppc { Variable::Variable(const std::string& arg, const std::string& value_) { // 'name' might be prefixed by a type // the variablename is the last word in 'name' // type is the rest before the variablename // examples: // " int var " // " var" // " ns :: someclass param" std::ostringstream a; std::string::size_type e = arg.size(); while (e > 0 && std::isspace(arg.at(e - 1))) --e; // e points past the last character of our arg if (e > 1 && arg.at(e - 2) == '[' && arg.at(e-1) == ']') { isvector = true; e -= 2; while (e > 0 && std::isspace(arg.at(e - 1))) --e; } else isvector = false; std::string::size_type b = e; while (b > 0 && !std::isspace(arg.at(b - 1))) --b; // b points to the first character of our arg std::string::size_type t = b; while (t > 0 && std::isspace(arg.at(t - 1))) --t; // t points past the last character of the type name = std::string(arg.begin() + b, arg.begin() + e); type = std::string(arg.begin(), arg.begin() + t); value = value_; } void Variable::getParamCodeVector(std::ostream& o) const { if (type.empty()) { o << "typedef std::vector<std::string> " << name << "_type;\n" << name << "_type " << name << "(qparam.begin(\"" << name << "\"), qparam.end());\n"; } else { o << "typedef std::vector<" << type << "> " << name << "_type;\n" << name << "_type " << name << ";\n" << "std::transform(qparam.begin(\"" << name << "\"), qparam.end(), std::back_inserter(" << name << "), tnt::stringToConverter<" << type << ">(reply.out().getloc()));\n"; } } void Variable::getParamCode(std::ostream& o) const { if (isvector) getParamCodeVector(o); else if (!type.empty()) { // we have a type // print out type and name o << type << ' ' << name << " = "; if (value.empty()) { // no default-value o << "tnt::stringToConverter<" << type << ">(reply.out().getloc())( qparam.param(\"" << name << "\") );\n"; } else { // with default-value o << "qparam.has(\"" << name << "\") ? tnt::stringToWithDefaultConverter<" << type << ">(" << value << ", reply.out().getloc())(qparam.param(\"" << name << "\")) : " << value << ";\n"; } } else { // type defaults to std::string o << "std::string " << name << " = qparam.param(\"" << name << '"'; if (!value.empty()) o << ", " << value; o << ");\n"; } } void Variable::getConfigInit(std::ostream& o, const std::string& classname) const { if (!type.empty()) { // we have a type o << " if (config.hasValue(\"" << name << "\"))\n" << " " << classname << "::" << name << " = tnt::stringTo<" << type << ">( config.getValue(\"" << name << "\") );\n"; } else { // type defaults to std::string if (value.empty()) o << " " << classname << "::" << name << " = config.getValue(\"" << name << "\");\n"; else o << " if (config.hasValue(\"" << name << "\"))\n" << " " << classname << "::" << name << " = config.getValue(\"" << name << "\");\n"; } } void Variable::getConfigDecl(std::ostream& o, const std::string& classname) const { std::string t = type.empty() ? "std::string" : type; o << t << ' ' << classname << "::" << name; if (!value.empty()) o << " = " << value; o << ";\n"; } void Variable::getConfigHDecl(std::ostream& o) const { std::string t = type.empty() ? "std::string" : type; o << " static " << t << " " << name << ";\n"; } } } <commit_msg>fix include<commit_after>/* variable.cpp * Copyright (C) 2003 Tommi Maekitalo * * This program 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 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser 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 * */ #include "tnt/ecppc/variable.h" #include <sstream> #include <cctype> namespace tnt { namespace ecppc { Variable::Variable(const std::string& arg, const std::string& value_) { // 'name' might be prefixed by a type // the variablename is the last word in 'name' // type is the rest before the variablename // examples: // " int var " // " var" // " ns :: someclass param" std::ostringstream a; std::string::size_type e = arg.size(); while (e > 0 && std::isspace(arg.at(e - 1))) --e; // e points past the last character of our arg if (e > 1 && arg.at(e - 2) == '[' && arg.at(e-1) == ']') { isvector = true; e -= 2; while (e > 0 && std::isspace(arg.at(e - 1))) --e; } else isvector = false; std::string::size_type b = e; while (b > 0 && !std::isspace(arg.at(b - 1))) --b; // b points to the first character of our arg std::string::size_type t = b; while (t > 0 && std::isspace(arg.at(t - 1))) --t; // t points past the last character of the type name = std::string(arg.begin() + b, arg.begin() + e); type = std::string(arg.begin(), arg.begin() + t); value = value_; } void Variable::getParamCodeVector(std::ostream& o) const { if (type.empty()) { o << "typedef std::vector<std::string> " << name << "_type;\n" << name << "_type " << name << "(qparam.begin(\"" << name << "\"), qparam.end());\n"; } else { o << "typedef std::vector<" << type << "> " << name << "_type;\n" << name << "_type " << name << ";\n" << "std::transform(qparam.begin(\"" << name << "\"), qparam.end(), std::back_inserter(" << name << "), tnt::stringToConverter<" << type << ">(reply.out().getloc()));\n"; } } void Variable::getParamCode(std::ostream& o) const { if (isvector) getParamCodeVector(o); else if (!type.empty()) { // we have a type // print out type and name o << type << ' ' << name << " = "; if (value.empty()) { // no default-value o << "tnt::stringToConverter<" << type << ">(reply.out().getloc())( qparam.param(\"" << name << "\") );\n"; } else { // with default-value o << "qparam.has(\"" << name << "\") ? tnt::stringToWithDefaultConverter<" << type << ">(" << value << ", reply.out().getloc())(qparam.param(\"" << name << "\")) : " << value << ";\n"; } } else { // type defaults to std::string o << "std::string " << name << " = qparam.param(\"" << name << '"'; if (!value.empty()) o << ", " << value; o << ");\n"; } } void Variable::getConfigInit(std::ostream& o, const std::string& classname) const { if (!type.empty()) { // we have a type o << " if (config.hasValue(\"" << name << "\"))\n" << " " << classname << "::" << name << " = tnt::stringTo<" << type << ">( config.getValue(\"" << name << "\") );\n"; } else { // type defaults to std::string if (value.empty()) o << " " << classname << "::" << name << " = config.getValue(\"" << name << "\");\n"; else o << " if (config.hasValue(\"" << name << "\"))\n" << " " << classname << "::" << name << " = config.getValue(\"" << name << "\");\n"; } } void Variable::getConfigDecl(std::ostream& o, const std::string& classname) const { std::string t = type.empty() ? "std::string" : type; o << t << ' ' << classname << "::" << name; if (!value.empty()) o << " = " << value; o << ";\n"; } void Variable::getConfigHDecl(std::ostream& o) const { std::string t = type.empty() ? "std::string" : type; o << " static " << t << " " << name << ";\n"; } } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: dlgolbul.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: kz $ $Date: 2005-01-13 17:26:36 $ * * 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 SD_DLLIMPLEMENTATION #undef SD_DLLIMPLEMENTATION #endif #include "OutlineBulletDlg.hxx" #ifndef _SVX_SVXIDS_HRC #include <svx/svxids.hrc> #endif #ifndef _SFX_OBJSH_HXX //autogen #include <sfx2/objsh.hxx> #endif #define ITEMID_COLOR_TABLE SID_COLOR_TABLE #ifndef _SVX_DRAWITEM_HXX //autogen #include <svx/drawitem.hxx> #endif #ifndef _SVX_BULITEM_HXX #include <svx/bulitem.hxx> #endif #ifndef _EEITEM_HXX #include <svx/eeitem.hxx> #endif //CHINA001 #include <svx/numpages.hxx> #include <svx/numitem.hxx> #include <svx/dialogs.hrc> #ifndef _SFXINTITEM_HXX //autogen #include <svtools/intitem.hxx> #endif #ifndef _SVDMARK_HXX //autogen #include <svx/svdmark.hxx> #endif #ifndef SD_VIEW_HXX #include "View.hxx" #endif #ifndef _SVDOBJ_HXX //autogen #include <svx/svdobj.hxx> #endif #ifndef _SFXSTYLE_HXX //autogen #include <svtools/style.hxx> #endif #ifndef _DRAWDOC_HXX #include <drawdoc.hxx> #endif #ifndef _SD_SDRESID_HXX #include "sdresid.hxx" #endif #include "glob.hrc" #include "dlgolbul.hrc" //#include "enumdlg.hxx" #include "bulmaper.hxx" #include "DrawDocShell.hxx" #include <svx/svxids.hrc> //add CHINA001 #include <svtools/aeitem.hxx> //add CHINA001 namespace sd { /************************************************************************* |* |* Konstruktor des Tab-Dialogs: Fuegt die Seiten zum Dialog hinzu |* \************************************************************************/ OutlineBulletDlg::OutlineBulletDlg( ::Window* pParent, const SfxItemSet* pAttr, ::sd::View* pView ) : SfxTabDialog ( pParent, SdResId(TAB_OUTLINEBULLET) ), aInputSet ( *pAttr ), bTitle ( FALSE ), pSdView ( pView ) { FreeResource(); aInputSet.MergeRange( SID_PARAM_NUM_PRESET, SID_PARAM_CUR_NUM_LEVEL ); aInputSet.Put( *pAttr ); pOutputSet = new SfxItemSet( *pAttr ); pOutputSet->ClearItem(); BOOL bOutliner = FALSE; // Sonderbehandlung wenn eine Title Objekt selektiert wurde if( pView ) { const SdrMarkList& rMarkList = pView->GetMarkedObjectList(); const ULONG nCount = rMarkList.GetMarkCount(); for(ULONG nNum = 0; nNum < nCount; nNum++) { SdrObject* pObj = rMarkList.GetMark(nNum)->GetObj(); if( pObj->GetObjInventor() == SdrInventor ) { switch(pObj->GetObjIdentifier()) { case OBJ_TITLETEXT: bTitle = TRUE; break; case OBJ_OUTLINETEXT: bOutliner = TRUE; break; } } } } if( SFX_ITEM_SET != aInputSet.GetItemState(EE_PARA_NUMBULLET)) { const SvxNumBulletItem *pItem = NULL; if(bOutliner) { SfxStyleSheetBasePool* pSSPool = pView->GetDocSh()->GetStyleSheetPool(); String aStyleName((SdResId(STR_LAYOUT_OUTLINE))); aStyleName.AppendAscii( RTL_CONSTASCII_STRINGPARAM( " 1" ) ); SfxStyleSheetBase* pFirstStyleSheet = pSSPool->Find( aStyleName, SFX_STYLE_FAMILY_PSEUDO); if( pFirstStyleSheet ) pFirstStyleSheet->GetItemSet().GetItemState(EE_PARA_NUMBULLET, FALSE, (const SfxPoolItem**)&pItem); } if( pItem == NULL ) pItem = (SvxNumBulletItem*) aInputSet.GetPool()->GetSecondaryPool()->GetPoolDefaultItem(EE_PARA_NUMBULLET); DBG_ASSERT( pItem, "Kein EE_PARA_NUMBULLET im Pool! [CL]" ); aInputSet.Put(*pItem, EE_PARA_NUMBULLET); } /* debug if( SFX_ITEM_SET == aInputSet.GetItemState(EE_PARA_NUMBULLET, FALSE, &pItem )) { SvxNumRule& rItem = *((SvxNumBulletItem*)pItem)->GetNumRule(); for( int i = 0; i < 9; i++ ) { SvxNumberFormat aNumberFormat = rItem.GetLevel(i); } } */ if(bTitle && aInputSet.GetItemState(EE_PARA_NUMBULLET,TRUE) == SFX_ITEM_ON ) { SvxNumBulletItem* pItem = (SvxNumBulletItem*)aInputSet.GetItem(EE_PARA_NUMBULLET,TRUE); SvxNumRule* pRule = pItem->GetNumRule(); if(pRule) { SvxNumRule aNewRule( *pRule ); aNewRule.SetFeatureFlag( NUM_NO_NUMBERS, TRUE ); SvxNumBulletItem aNewItem( aNewRule, EE_PARA_NUMBULLET ); aInputSet.Put(aNewItem); } } SdBulletMapper::PreMapNumBulletForDialog( aInputSet ); SetInputSet( &aInputSet ); if(!bTitle) AddTabPage(RID_SVXPAGE_PICK_SINGLE_NUM);//CHINA001 AddTabPage(RID_SVXPAGE_PICK_SINGLE_NUM, &SvxSingleNumPickTabPage::Create, 0); else RemoveTabPage( RID_SVXPAGE_PICK_SINGLE_NUM ); AddTabPage( RID_SVXPAGE_PICK_BULLET ); //CHINA001 AddTabPage(RID_SVXPAGE_PICK_BULLET , &SvxBulletPickTabPage::Create, 0); AddTabPage( RID_SVXPAGE_PICK_BMP ); //CHINA001 AddTabPage(RID_SVXPAGE_PICK_BMP , &SvxBitmapPickTabPage::Create, 0); AddTabPage(RID_SVXPAGE_NUM_OPTIONS ); //CHINA001 AddTabPage(RID_SVXPAGE_NUM_OPTIONS , &SvxNumOptionsTabPage::Create, 0); AddTabPage(RID_SVXPAGE_NUM_POSITION ); //CHINA001 AddTabPage(RID_SVXPAGE_NUM_POSITION , &SvxNumPositionTabPage::Create, 0); } OutlineBulletDlg::~OutlineBulletDlg() { delete pOutputSet; } void OutlineBulletDlg::PageCreated( USHORT nId, SfxTabPage &rPage ) { switch ( nId ) { case RID_SVXPAGE_NUM_OPTIONS: { if( pSdView ) { FieldUnit eMetric = pSdView->GetDoc()->GetUIUnit(); //CHINA001 ((SvxNumOptionsTabPage&)rPage).SetMetric(eMetric); SfxAllItemSet aSet(*(GetInputSetImpl()->GetPool()));//add CHINA001 aSet.Put ( SfxAllEnumItem(SID_METRIC_ITEM,eMetric));//add CHINA001 rPage.PageCreated(aSet);//add CHINA001 } } break; case RID_SVXPAGE_NUM_POSITION: { if( pSdView ) { FieldUnit eMetric = pSdView->GetDoc()->GetUIUnit(); //CHINA001 ((SvxNumPositionTabPage&)rPage).SetMetric(eMetric); SfxAllItemSet aSet(*(GetInputSetImpl()->GetPool()));//add CHINA001 aSet.Put ( SfxAllEnumItem(SID_METRIC_ITEM,eMetric));//add CHINA001 rPage.PageCreated(aSet);//add CHINA001 } } break; } } const SfxItemSet* OutlineBulletDlg::GetOutputItemSet() const { SfxItemSet aSet( *SfxTabDialog::GetOutputItemSet() ); pOutputSet->Put( aSet ); const SfxPoolItem *pItem = NULL; if( SFX_ITEM_SET == pOutputSet->GetItemState(pOutputSet->GetPool()->GetWhich(SID_ATTR_NUMBERING_RULE), FALSE, &pItem )) { SdBulletMapper::MapFontsInNumRule( *((SvxNumBulletItem*)pItem)->GetNumRule(), *pOutputSet ); SfxUInt16Item aBulletState( EE_PARA_BULLETSTATE, 1 ); pOutputSet->Put(aBulletState); } SdBulletMapper::PostMapNumBulletForDialog( *pOutputSet ); if(bTitle && pOutputSet->GetItemState(EE_PARA_NUMBULLET,TRUE) == SFX_ITEM_ON ) { SvxNumBulletItem* pItem = (SvxNumBulletItem*)pOutputSet->GetItem(EE_PARA_NUMBULLET,TRUE); SvxNumRule* pRule = pItem->GetNumRule(); if(pRule) pRule->SetFeatureFlag( NUM_NO_NUMBERS, FALSE ); } return pOutputSet; } } // end of namespace sd <commit_msg>INTEGRATION: CWS ooo19126 (1.7.242); FILE MERGED 2005/09/05 13:21:47 rt 1.7.242.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: dlgolbul.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: rt $ $Date: 2005-09-09 03:57:39 $ * * 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 * ************************************************************************/ #ifdef SD_DLLIMPLEMENTATION #undef SD_DLLIMPLEMENTATION #endif #include "OutlineBulletDlg.hxx" #ifndef _SVX_SVXIDS_HRC #include <svx/svxids.hrc> #endif #ifndef _SFX_OBJSH_HXX //autogen #include <sfx2/objsh.hxx> #endif #define ITEMID_COLOR_TABLE SID_COLOR_TABLE #ifndef _SVX_DRAWITEM_HXX //autogen #include <svx/drawitem.hxx> #endif #ifndef _SVX_BULITEM_HXX #include <svx/bulitem.hxx> #endif #ifndef _EEITEM_HXX #include <svx/eeitem.hxx> #endif //CHINA001 #include <svx/numpages.hxx> #include <svx/numitem.hxx> #include <svx/dialogs.hrc> #ifndef _SFXINTITEM_HXX //autogen #include <svtools/intitem.hxx> #endif #ifndef _SVDMARK_HXX //autogen #include <svx/svdmark.hxx> #endif #ifndef SD_VIEW_HXX #include "View.hxx" #endif #ifndef _SVDOBJ_HXX //autogen #include <svx/svdobj.hxx> #endif #ifndef _SFXSTYLE_HXX //autogen #include <svtools/style.hxx> #endif #ifndef _DRAWDOC_HXX #include <drawdoc.hxx> #endif #ifndef _SD_SDRESID_HXX #include "sdresid.hxx" #endif #include "glob.hrc" #include "dlgolbul.hrc" //#include "enumdlg.hxx" #include "bulmaper.hxx" #include "DrawDocShell.hxx" #include <svx/svxids.hrc> //add CHINA001 #include <svtools/aeitem.hxx> //add CHINA001 namespace sd { /************************************************************************* |* |* Konstruktor des Tab-Dialogs: Fuegt die Seiten zum Dialog hinzu |* \************************************************************************/ OutlineBulletDlg::OutlineBulletDlg( ::Window* pParent, const SfxItemSet* pAttr, ::sd::View* pView ) : SfxTabDialog ( pParent, SdResId(TAB_OUTLINEBULLET) ), aInputSet ( *pAttr ), bTitle ( FALSE ), pSdView ( pView ) { FreeResource(); aInputSet.MergeRange( SID_PARAM_NUM_PRESET, SID_PARAM_CUR_NUM_LEVEL ); aInputSet.Put( *pAttr ); pOutputSet = new SfxItemSet( *pAttr ); pOutputSet->ClearItem(); BOOL bOutliner = FALSE; // Sonderbehandlung wenn eine Title Objekt selektiert wurde if( pView ) { const SdrMarkList& rMarkList = pView->GetMarkedObjectList(); const ULONG nCount = rMarkList.GetMarkCount(); for(ULONG nNum = 0; nNum < nCount; nNum++) { SdrObject* pObj = rMarkList.GetMark(nNum)->GetObj(); if( pObj->GetObjInventor() == SdrInventor ) { switch(pObj->GetObjIdentifier()) { case OBJ_TITLETEXT: bTitle = TRUE; break; case OBJ_OUTLINETEXT: bOutliner = TRUE; break; } } } } if( SFX_ITEM_SET != aInputSet.GetItemState(EE_PARA_NUMBULLET)) { const SvxNumBulletItem *pItem = NULL; if(bOutliner) { SfxStyleSheetBasePool* pSSPool = pView->GetDocSh()->GetStyleSheetPool(); String aStyleName((SdResId(STR_LAYOUT_OUTLINE))); aStyleName.AppendAscii( RTL_CONSTASCII_STRINGPARAM( " 1" ) ); SfxStyleSheetBase* pFirstStyleSheet = pSSPool->Find( aStyleName, SFX_STYLE_FAMILY_PSEUDO); if( pFirstStyleSheet ) pFirstStyleSheet->GetItemSet().GetItemState(EE_PARA_NUMBULLET, FALSE, (const SfxPoolItem**)&pItem); } if( pItem == NULL ) pItem = (SvxNumBulletItem*) aInputSet.GetPool()->GetSecondaryPool()->GetPoolDefaultItem(EE_PARA_NUMBULLET); DBG_ASSERT( pItem, "Kein EE_PARA_NUMBULLET im Pool! [CL]" ); aInputSet.Put(*pItem, EE_PARA_NUMBULLET); } /* debug if( SFX_ITEM_SET == aInputSet.GetItemState(EE_PARA_NUMBULLET, FALSE, &pItem )) { SvxNumRule& rItem = *((SvxNumBulletItem*)pItem)->GetNumRule(); for( int i = 0; i < 9; i++ ) { SvxNumberFormat aNumberFormat = rItem.GetLevel(i); } } */ if(bTitle && aInputSet.GetItemState(EE_PARA_NUMBULLET,TRUE) == SFX_ITEM_ON ) { SvxNumBulletItem* pItem = (SvxNumBulletItem*)aInputSet.GetItem(EE_PARA_NUMBULLET,TRUE); SvxNumRule* pRule = pItem->GetNumRule(); if(pRule) { SvxNumRule aNewRule( *pRule ); aNewRule.SetFeatureFlag( NUM_NO_NUMBERS, TRUE ); SvxNumBulletItem aNewItem( aNewRule, EE_PARA_NUMBULLET ); aInputSet.Put(aNewItem); } } SdBulletMapper::PreMapNumBulletForDialog( aInputSet ); SetInputSet( &aInputSet ); if(!bTitle) AddTabPage(RID_SVXPAGE_PICK_SINGLE_NUM);//CHINA001 AddTabPage(RID_SVXPAGE_PICK_SINGLE_NUM, &SvxSingleNumPickTabPage::Create, 0); else RemoveTabPage( RID_SVXPAGE_PICK_SINGLE_NUM ); AddTabPage( RID_SVXPAGE_PICK_BULLET ); //CHINA001 AddTabPage(RID_SVXPAGE_PICK_BULLET , &SvxBulletPickTabPage::Create, 0); AddTabPage( RID_SVXPAGE_PICK_BMP ); //CHINA001 AddTabPage(RID_SVXPAGE_PICK_BMP , &SvxBitmapPickTabPage::Create, 0); AddTabPage(RID_SVXPAGE_NUM_OPTIONS ); //CHINA001 AddTabPage(RID_SVXPAGE_NUM_OPTIONS , &SvxNumOptionsTabPage::Create, 0); AddTabPage(RID_SVXPAGE_NUM_POSITION ); //CHINA001 AddTabPage(RID_SVXPAGE_NUM_POSITION , &SvxNumPositionTabPage::Create, 0); } OutlineBulletDlg::~OutlineBulletDlg() { delete pOutputSet; } void OutlineBulletDlg::PageCreated( USHORT nId, SfxTabPage &rPage ) { switch ( nId ) { case RID_SVXPAGE_NUM_OPTIONS: { if( pSdView ) { FieldUnit eMetric = pSdView->GetDoc()->GetUIUnit(); //CHINA001 ((SvxNumOptionsTabPage&)rPage).SetMetric(eMetric); SfxAllItemSet aSet(*(GetInputSetImpl()->GetPool()));//add CHINA001 aSet.Put ( SfxAllEnumItem(SID_METRIC_ITEM,eMetric));//add CHINA001 rPage.PageCreated(aSet);//add CHINA001 } } break; case RID_SVXPAGE_NUM_POSITION: { if( pSdView ) { FieldUnit eMetric = pSdView->GetDoc()->GetUIUnit(); //CHINA001 ((SvxNumPositionTabPage&)rPage).SetMetric(eMetric); SfxAllItemSet aSet(*(GetInputSetImpl()->GetPool()));//add CHINA001 aSet.Put ( SfxAllEnumItem(SID_METRIC_ITEM,eMetric));//add CHINA001 rPage.PageCreated(aSet);//add CHINA001 } } break; } } const SfxItemSet* OutlineBulletDlg::GetOutputItemSet() const { SfxItemSet aSet( *SfxTabDialog::GetOutputItemSet() ); pOutputSet->Put( aSet ); const SfxPoolItem *pItem = NULL; if( SFX_ITEM_SET == pOutputSet->GetItemState(pOutputSet->GetPool()->GetWhich(SID_ATTR_NUMBERING_RULE), FALSE, &pItem )) { SdBulletMapper::MapFontsInNumRule( *((SvxNumBulletItem*)pItem)->GetNumRule(), *pOutputSet ); SfxUInt16Item aBulletState( EE_PARA_BULLETSTATE, 1 ); pOutputSet->Put(aBulletState); } SdBulletMapper::PostMapNumBulletForDialog( *pOutputSet ); if(bTitle && pOutputSet->GetItemState(EE_PARA_NUMBULLET,TRUE) == SFX_ITEM_ON ) { SvxNumBulletItem* pItem = (SvxNumBulletItem*)pOutputSet->GetItem(EE_PARA_NUMBULLET,TRUE); SvxNumRule* pRule = pItem->GetNumRule(); if(pRule) pRule->SetFeatureFlag( NUM_NO_NUMBERS, FALSE ); } return pOutputSet; } } // end of namespace sd <|endoftext|>
<commit_before><commit_msg>fdo#39528: do not lose height of tree list box in Navigator<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: unoprnms.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2004-11-26 20:19:29 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SD_UNOPRNMS_HXX #define _SD_UNOPRNMS_HXX #define UNO_NAME_MODEL_LANGUAGE "CharLocale" #define UNO_NAME_MODEL_TABSTOP "TabStop" #define UNO_NAME_PAGE_BACKGROUND "Background" #define UNO_NAME_PAGE_LEFT "BorderLeft" #define UNO_NAME_PAGE_RIGHT "BorderRight" #define UNO_NAME_PAGE_TOP "BorderTop" #define UNO_NAME_PAGE_BOTTOM "BorderBottom" #define UNO_NAME_PAGE_CHANGE "Change" #define UNO_NAME_PAGE_DURATION "Duration" #define UNO_NAME_PAGE_EFFECT "Effect" #define UNO_NAME_PAGE_HEIGHT "Height" #define UNO_NAME_PAGE_LAYOUT "Layout" #define UNO_NAME_PAGE_NUMBER "Number" #define UNO_NAME_PAGE_OBJECTS "Objects" #define UNO_NAME_PAGE_ORIENTATION "Orientation" #define UNO_NAME_PAGE_SPEED "Speed" #define UNO_NAME_PAGE_WIDTH "Width" #define UNO_NAME_PAGE_PREVIEW "Preview" #define UNO_NAME_PAGE_VISIBLE "Visible" #define UNO_NAME_OBJ_BOOKMARK "Bookmark" #define UNO_NAME_OBJ_DIMCOLOR "DimColor" #define UNO_NAME_OBJ_DIMHIDE "DimHide" #define UNO_NAME_OBJ_DIMPREV "DimPrevious" #define UNO_NAME_OBJ_EFFECT "Effect" #define UNO_NAME_OBJ_ISEMPTYPRESOBJ "IsEmptyPresentationObject" #define UNO_NAME_OBJ_ISPRESOBJ "IsPresentationObject" #define UNO_NAME_OBJ_CLICKACTION "OnClick" #define UNO_NAME_OBJ_PLAYFULL "PlayFull" #define UNO_NAME_OBJ_PRESORDER "PresentationOrder" #define UNO_NAME_OBJ_SOUNDFILE "Sound" #define UNO_NAME_OBJ_SOUNDON "SoundOn" #define UNO_NAME_OBJ_SPEED "Speed" #define UNO_NAME_OBJ_TEXTEFFECT "TextEffect" #define UNO_NAME_OBJ_BLUESCREEN "TransparentColor" #define UNO_NAME_OBJ_VERB "Verb" #define UNO_NAME_OBJ_STYLE "Style" #define UNO_NAME_OBJ_MASTERDEPENDENT "IsPlaceholderDependent" #define UNO_NAME_OBJ_ANIMATIONPATH "AnimationPath" #define UNO_NAME_LAYER_LOCKED "IsLocked" #define UNO_NAME_LAYER_PRINTABLE "IsPrintable" #define UNO_NAME_LAYER_VISIBLE "IsVisible" #define UNO_NAME_LAYER_NAME "Name" #define UNO_NAME_SHOW_ALLOWANIM "AllowAnimations" #define UNO_NAME_SHOW_CUSTOMSHOW "CustomShow" #define UNO_NAME_SHOW_FIRSTPAGE "FirstPage" #define UNO_NAME_SHOW_ONTOP "IsAlwaysOnTop" #define UNO_NAME_SHOW_AUTOMATIC "IsAutomatic" #define UNO_NAME_SHOW_ENDLESS "IsEndless" #define UNO_NAME_SHOW_FULLSCREEN "IsFullScreen" #define UNO_NAME_SHOW_MOUSEVISIBLE "IsMouseVisible" #define UNO_NAME_SHOW_PAGERANGE "PageRange" #define UNO_NAME_SHOW_PAUSE "Pause" #define UNO_NAME_SHOW_STARTWITHNAV "StartWithNavigator" #define UNO_NAME_SHOW_USEPEN "UsePen" #define UNO_NAME_SEARCH_BACKWARDS "SearchBackwards" #define UNO_NAME_SEARCH_CASE "SearchCaseSensitive" #define UNO_NAME_SEARCH_WORDS "SearchWords" #define UNO_NAME_LINKDISPLAYNAME "LinkDisplayName" #define UNO_NAME_LINKDISPLAYBITMAP "LinkDisplayBitmap" #define UNO_NAME_STYLE_FAMILY "Family" #endif <commit_msg>INTEGRATION: CWS ooo19126 (1.4.288); FILE MERGED 2005/09/05 13:23:33 rt 1.4.288.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: unoprnms.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2005-09-09 05:59:49 $ * * 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 _SD_UNOPRNMS_HXX #define _SD_UNOPRNMS_HXX #define UNO_NAME_MODEL_LANGUAGE "CharLocale" #define UNO_NAME_MODEL_TABSTOP "TabStop" #define UNO_NAME_PAGE_BACKGROUND "Background" #define UNO_NAME_PAGE_LEFT "BorderLeft" #define UNO_NAME_PAGE_RIGHT "BorderRight" #define UNO_NAME_PAGE_TOP "BorderTop" #define UNO_NAME_PAGE_BOTTOM "BorderBottom" #define UNO_NAME_PAGE_CHANGE "Change" #define UNO_NAME_PAGE_DURATION "Duration" #define UNO_NAME_PAGE_EFFECT "Effect" #define UNO_NAME_PAGE_HEIGHT "Height" #define UNO_NAME_PAGE_LAYOUT "Layout" #define UNO_NAME_PAGE_NUMBER "Number" #define UNO_NAME_PAGE_OBJECTS "Objects" #define UNO_NAME_PAGE_ORIENTATION "Orientation" #define UNO_NAME_PAGE_SPEED "Speed" #define UNO_NAME_PAGE_WIDTH "Width" #define UNO_NAME_PAGE_PREVIEW "Preview" #define UNO_NAME_PAGE_VISIBLE "Visible" #define UNO_NAME_OBJ_BOOKMARK "Bookmark" #define UNO_NAME_OBJ_DIMCOLOR "DimColor" #define UNO_NAME_OBJ_DIMHIDE "DimHide" #define UNO_NAME_OBJ_DIMPREV "DimPrevious" #define UNO_NAME_OBJ_EFFECT "Effect" #define UNO_NAME_OBJ_ISEMPTYPRESOBJ "IsEmptyPresentationObject" #define UNO_NAME_OBJ_ISPRESOBJ "IsPresentationObject" #define UNO_NAME_OBJ_CLICKACTION "OnClick" #define UNO_NAME_OBJ_PLAYFULL "PlayFull" #define UNO_NAME_OBJ_PRESORDER "PresentationOrder" #define UNO_NAME_OBJ_SOUNDFILE "Sound" #define UNO_NAME_OBJ_SOUNDON "SoundOn" #define UNO_NAME_OBJ_SPEED "Speed" #define UNO_NAME_OBJ_TEXTEFFECT "TextEffect" #define UNO_NAME_OBJ_BLUESCREEN "TransparentColor" #define UNO_NAME_OBJ_VERB "Verb" #define UNO_NAME_OBJ_STYLE "Style" #define UNO_NAME_OBJ_MASTERDEPENDENT "IsPlaceholderDependent" #define UNO_NAME_OBJ_ANIMATIONPATH "AnimationPath" #define UNO_NAME_LAYER_LOCKED "IsLocked" #define UNO_NAME_LAYER_PRINTABLE "IsPrintable" #define UNO_NAME_LAYER_VISIBLE "IsVisible" #define UNO_NAME_LAYER_NAME "Name" #define UNO_NAME_SHOW_ALLOWANIM "AllowAnimations" #define UNO_NAME_SHOW_CUSTOMSHOW "CustomShow" #define UNO_NAME_SHOW_FIRSTPAGE "FirstPage" #define UNO_NAME_SHOW_ONTOP "IsAlwaysOnTop" #define UNO_NAME_SHOW_AUTOMATIC "IsAutomatic" #define UNO_NAME_SHOW_ENDLESS "IsEndless" #define UNO_NAME_SHOW_FULLSCREEN "IsFullScreen" #define UNO_NAME_SHOW_MOUSEVISIBLE "IsMouseVisible" #define UNO_NAME_SHOW_PAGERANGE "PageRange" #define UNO_NAME_SHOW_PAUSE "Pause" #define UNO_NAME_SHOW_STARTWITHNAV "StartWithNavigator" #define UNO_NAME_SHOW_USEPEN "UsePen" #define UNO_NAME_SEARCH_BACKWARDS "SearchBackwards" #define UNO_NAME_SEARCH_CASE "SearchCaseSensitive" #define UNO_NAME_SEARCH_WORDS "SearchWords" #define UNO_NAME_LINKDISPLAYNAME "LinkDisplayName" #define UNO_NAME_LINKDISPLAYBITMAP "LinkDisplayBitmap" #define UNO_NAME_STYLE_FAMILY "Family" #endif <|endoftext|>
<commit_before>// Copyright (c) 2013 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/component_updater/widevine_cdm_component_installer.h" #include <string.h> #include <vector> #include "base/base_paths.h" #include "base/bind.h" #include "base/command_line.h" #include "base/compiler_specific.h" #include "base/file_util.h" #include "base/files/file_enumerator.h" #include "base/files/file_path.h" #include "base/logging.h" #include "base/path_service.h" #include "base/strings/string_util.h" #include "base/values.h" #include "base/version.h" #include "build/build_config.h" #include "chrome/browser/component_updater/component_updater_service.h" #include "chrome/browser/plugins/plugin_prefs.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/widevine_cdm_constants.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/plugin_service.h" #include "content/public/common/pepper_plugin_info.h" #include "third_party/widevine/cdm/widevine_cdm_common.h" #include "widevine_cdm_version.h" // In SHARED_INTERMEDIATE_DIR. using content::BrowserThread; using content::PluginService; namespace { // TODO(xhwang): Move duplicate code among all component installer // implementations to some common place. #if defined(WIDEVINE_CDM_AVAILABLE) && defined(WIDEVINE_CDM_IS_COMPONENT) // CRX hash. The extension id is: oimompecagnajdejgnnjijobebaeigek. const uint8 kSha2Hash[] = { 0xe8, 0xce, 0xcf, 0x42, 0x06, 0xd0, 0x93, 0x49, 0x6d, 0xd9, 0x89, 0xe1, 0x41, 0x04, 0x86, 0x4a, 0x8f, 0xbd, 0x86, 0x12, 0xb9, 0x58, 0x9b, 0xfb, 0x4f, 0xbb, 0x1b, 0xa9, 0xd3, 0x85, 0x37, 0xef }; // File name of the Widevine CDM component manifest on different platforms. const char kWidevineCdmManifestName[] = "WidevineCdm"; // Name of the Widevine CDM OS in the component manifest. const char kWidevineCdmPlatform[] = #if defined(OS_MACOSX) "mac"; #elif defined(OS_WIN) "win"; #else // OS_LINUX, etc. TODO(viettrungluu): Separate out Chrome OS and Android? "linux"; #endif // Name of the Widevine CDM architecture in the component manifest. const char kWidevineCdmArch[] = #if defined(ARCH_CPU_X86) "x86"; #elif defined(ARCH_CPU_X86_64) "x64"; #else // TODO(viettrungluu): Support an ARM check? "???"; #endif // If we don't have a Widevine CDM component, this is the version we claim. const char kNullVersion[] = "0.0.0.0"; // The base directory on Windows looks like: // <profile>\AppData\Local\Google\Chrome\User Data\WidevineCdm\. base::FilePath GetWidevineCdmBaseDirectory() { base::FilePath result; PathService::Get(chrome::DIR_COMPONENT_WIDEVINE_CDM, &result); return result; } // Widevine CDM is packaged as a multi-CRX. Widevine CDM binaries are located in // _platform_specific/<platform_arch> folder in the package. This function // returns the platform-specific subdirectory that is part of that multi-CRX. base::FilePath GetPlatformDirectory(const base::FilePath& base_path) { std::string platform_arch = kWidevineCdmPlatform; platform_arch += '_'; platform_arch += kWidevineCdmArch; return base_path.AppendASCII("_platform_specific").AppendASCII(platform_arch); } // Widevine CDM has the version encoded in the path so we need to enumerate the // directories to find the full path. // On success, |latest_dir| returns something like: // <profile>\AppData\Local\Google\Chrome\User Data\WidevineCdm\10.3.44.555\. // |latest_version| returns the corresponding version number. |older_dirs| // returns directories of all older versions. bool GetWidevineCdmDirectory(base::FilePath* latest_dir, base::Version* latest_version, std::vector<base::FilePath>* older_dirs) { base::FilePath base_dir = GetWidevineCdmBaseDirectory(); bool found = false; base::FileEnumerator file_enumerator( base_dir, false, base::FileEnumerator::DIRECTORIES); for (base::FilePath path = file_enumerator.Next(); !path.value().empty(); path = file_enumerator.Next()) { base::Version version(path.BaseName().MaybeAsASCII()); if (!version.IsValid()) continue; if (found) { if (version.CompareTo(*latest_version) > 0) { older_dirs->push_back(*latest_dir); *latest_dir = path; *latest_version = version; } else { older_dirs->push_back(path); } } else { *latest_dir = path; *latest_version = version; found = true; } } return found; } bool MakeWidevineCdmPluginInfo(const base::FilePath& path, const base::Version& version, content::PepperPluginInfo* plugin_info) { if (!version.IsValid() || version.components().size() != static_cast<size_t>(kWidevineCdmVersionNumComponents)) { return false; } plugin_info->is_internal = false; // Widevine CDM must run out of process. plugin_info->is_out_of_process = true; plugin_info->path = path; plugin_info->name = kWidevineCdmDisplayName; plugin_info->description = kWidevineCdmDescription; plugin_info->version = version.GetString(); content::WebPluginMimeType widevine_cdm_mime_type( kWidevineCdmPluginMimeType, kWidevineCdmPluginExtension, kWidevineCdmPluginMimeTypeDescription); plugin_info->mime_types.push_back(widevine_cdm_mime_type); plugin_info->permissions = kWidevineCdmPluginPermissions; return true; } void RegisterWidevineCdmWithChrome(const base::FilePath& path, const base::Version& version) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); content::PepperPluginInfo plugin_info; if (!MakeWidevineCdmPluginInfo(path, version, &plugin_info)) return; PluginService::GetInstance()->RegisterInternalPlugin( plugin_info.ToWebPluginInfo(), true); PluginService::GetInstance()->RefreshPlugins(); } // Returns true if this browser is compatible with the given Widevine CDM // manifest, with the version specified in the manifest in |version_out|. bool CheckWidevineCdmManifest(const base::DictionaryValue& manifest, base::Version* version_out) { std::string name; manifest.GetStringASCII("name", &name); if (name != kWidevineCdmManifestName) return false; std::string proposed_version; manifest.GetStringASCII("version", &proposed_version); base::Version version(proposed_version.c_str()); if (!version.IsValid()) return false; *version_out = version; return true; } class WidevineCdmComponentInstaller : public ComponentInstaller { public: explicit WidevineCdmComponentInstaller(const base::Version& version); virtual ~WidevineCdmComponentInstaller() {} virtual void OnUpdateError(int error) OVERRIDE; virtual bool Install(const base::DictionaryValue& manifest, const base::FilePath& unpack_path) OVERRIDE; virtual bool GetInstalledFile(const std::string& file, base::FilePath* installed_file) OVERRIDE; private: base::Version current_version_; }; WidevineCdmComponentInstaller::WidevineCdmComponentInstaller( const base::Version& version) : current_version_(version) { DCHECK(version.IsValid()); } void WidevineCdmComponentInstaller::OnUpdateError(int error) { NOTREACHED() << "Widevine CDM update error: " << error; } bool WidevineCdmComponentInstaller::Install( const base::DictionaryValue& manifest, const base::FilePath& unpack_path) { base::Version version; if (!CheckWidevineCdmManifest(manifest, &version)) return false; if (current_version_.CompareTo(version) > 0) return false; if (!base::PathExists( GetPlatformDirectory(unpack_path).AppendASCII(kWidevineCdmFileName))) { return false; } base::FilePath adapter_source_path; PathService::Get(chrome::FILE_WIDEVINE_CDM_ADAPTER, &adapter_source_path); if (!base::PathExists(adapter_source_path)) return false; // Passed the basic tests. Time to install it. base::FilePath install_path = GetWidevineCdmBaseDirectory().AppendASCII(version.GetString()); if (base::PathExists(install_path)) return false; if (!base::Move(unpack_path, install_path)) return false; base::FilePath adapter_install_path = GetPlatformDirectory(install_path) .AppendASCII(kWidevineCdmAdapterFileName); if (!base::CopyFile(adapter_source_path, adapter_install_path)) return false; // Installation is done. Now register the Widevine CDM with chrome. current_version_ = version; BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, base::Bind( &RegisterWidevineCdmWithChrome, adapter_install_path, version)); return true; } // Given |file|, a path like "_platform_specific/win_x86/widevinecdm.dll", // returns the assumed install path. The path separator in |file| is '/' // for all platforms. Caller is responsible for checking that the // |installed_file| actually exists. bool WidevineCdmComponentInstaller::GetInstalledFile( const std::string& file, base::FilePath* installed_file) { if (current_version_.Equals(base::Version(kNullVersion))) return false; // No CDM has been installed yet. *installed_file = GetWidevineCdmBaseDirectory().AppendASCII( current_version_.GetString()).AppendASCII(file); return true; } void FinishWidevineCdmUpdateRegistration(ComponentUpdateService* cus, const base::Version& version) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); CrxComponent widevine_cdm; widevine_cdm.name = "WidevineCdm"; widevine_cdm.installer = new WidevineCdmComponentInstaller(version); widevine_cdm.version = version; widevine_cdm.pk_hash.assign(kSha2Hash, &kSha2Hash[sizeof(kSha2Hash)]); if (cus->RegisterComponent(widevine_cdm) != ComponentUpdateService::kOk) { NOTREACHED() << "Widevine CDM component registration failed."; return; } } void StartWidevineCdmUpdateRegistration(ComponentUpdateService* cus) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); base::FilePath base_dir = GetWidevineCdmBaseDirectory(); if (!base::PathExists(base_dir) && !file_util::CreateDirectory(base_dir)) { NOTREACHED() << "Could not create Widevine CDM directory."; return; } base::FilePath latest_dir; base::Version version(kNullVersion); std::vector<base::FilePath> older_dirs; if (GetWidevineCdmDirectory(&latest_dir, &version, &older_dirs)) { base::FilePath latest_platform_dir = GetPlatformDirectory(latest_dir); base::FilePath adapter_path = latest_platform_dir.AppendASCII(kWidevineCdmAdapterFileName); base::FilePath cdm_path = latest_platform_dir.AppendASCII(kWidevineCdmFileName); if (base::PathExists(adapter_path) && base::PathExists(cdm_path)) { BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&RegisterWidevineCdmWithChrome, adapter_path, version)); } else { base::DeleteFile(latest_dir, true); version = base::Version(kNullVersion); } } BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&FinishWidevineCdmUpdateRegistration, cus, version)); // Remove older versions of Widevine CDM. for (std::vector<base::FilePath>::iterator iter = older_dirs.begin(); iter != older_dirs.end(); ++iter) { base::DeleteFile(*iter, true); } } #endif // defined(WIDEVINE_CDM_AVAILABLE) && defined(WIDEVINE_CDM_IS_COMPONENT) } // namespace void RegisterWidevineCdmComponent(ComponentUpdateService* cus) { #if defined(WIDEVINE_CDM_AVAILABLE) && defined(WIDEVINE_CDM_IS_COMPONENT) BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE, base::Bind(&StartWidevineCdmUpdateRegistration, cus)); #endif // defined(WIDEVINE_CDM_AVAILABLE) && defined(WIDEVINE_CDM_IS_COMPONENT) } <commit_msg>Refactor Widevine component installer to use DefaultComponentInstaller.<commit_after>// Copyright (c) 2013 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/component_updater/widevine_cdm_component_installer.h" #include <string.h> #include <vector> #include "base/base_paths.h" #include "base/bind.h" #include "base/compiler_specific.h" #include "base/file_util.h" #include "base/files/file_path.h" #include "base/path_service.h" #include "base/values.h" #include "build/build_config.h" #include "chrome/browser/component_updater/component_updater_service.h" #include "chrome/browser/component_updater/default_component_installer.h" #include "chrome/browser/plugins/plugin_prefs.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/widevine_cdm_constants.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/plugin_service.h" #include "content/public/common/pepper_plugin_info.h" #include "third_party/widevine/cdm/widevine_cdm_common.h" #include "widevine_cdm_version.h" // In SHARED_INTERMEDIATE_DIR. using content::BrowserThread; using content::PluginService; #if defined(WIDEVINE_CDM_AVAILABLE) && defined(WIDEVINE_CDM_IS_COMPONENT) namespace { // CRX hash. The extension id is: oimompecagnajdejgnnjijobebaeigek. const uint8 kSha2Hash[] = { 0xe8, 0xce, 0xcf, 0x42, 0x06, 0xd0, 0x93, 0x49, 0x6d, 0xd9, 0x89, 0xe1, 0x41, 0x04, 0x86, 0x4a, 0x8f, 0xbd, 0x86, 0x12, 0xb9, 0x58, 0x9b, 0xfb, 0x4f, 0xbb, 0x1b, 0xa9, 0xd3, 0x85, 0x37, 0xef }; // File name of the Widevine CDM component manifest on different platforms. const char kWidevineCdmManifestName[] = "WidevineCdm"; // Name of the Widevine CDM OS in the component manifest. const char kWidevineCdmPlatform[] = #if defined(OS_MACOSX) "mac"; #elif defined(OS_WIN) "win"; #else // OS_LINUX, etc. TODO(viettrungluu): Separate out Chrome OS and Android? "linux"; #endif // Name of the Widevine CDM architecture in the component manifest. const char kWidevineCdmArch[] = #if defined(ARCH_CPU_X86) "x86"; #elif defined(ARCH_CPU_X86_64) "x64"; #else // TODO(viettrungluu): Support an ARM check? "???"; #endif // Widevine CDM is packaged as a multi-CRX. Widevine CDM binaries are located in // _platform_specific/<platform_arch> folder in the package. This function // returns the platform-specific subdirectory that is part of that multi-CRX. base::FilePath GetPlatformDirectory(const base::FilePath& base_path) { std::string platform_arch = kWidevineCdmPlatform; platform_arch += '_'; platform_arch += kWidevineCdmArch; return base_path.AppendASCII("_platform_specific").AppendASCII(platform_arch); } bool MakeWidevineCdmPluginInfo(const base::FilePath& path, const base::Version& version, content::PepperPluginInfo* plugin_info) { if (!version.IsValid() || version.components().size() != static_cast<size_t>(kWidevineCdmVersionNumComponents)) { return false; } plugin_info->is_internal = false; // Widevine CDM must run out of process. plugin_info->is_out_of_process = true; plugin_info->path = path; plugin_info->name = kWidevineCdmDisplayName; plugin_info->description = kWidevineCdmDescription; plugin_info->version = version.GetString(); content::WebPluginMimeType widevine_cdm_mime_type( kWidevineCdmPluginMimeType, kWidevineCdmPluginExtension, kWidevineCdmPluginMimeTypeDescription); plugin_info->mime_types.push_back(widevine_cdm_mime_type); plugin_info->permissions = kWidevineCdmPluginPermissions; return true; } void RegisterWidevineCdmWithChrome(const base::FilePath& path, const base::Version& version) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); content::PepperPluginInfo plugin_info; if (!MakeWidevineCdmPluginInfo(path, version, &plugin_info)) return; PluginService::GetInstance()->RegisterInternalPlugin( plugin_info.ToWebPluginInfo(), true); PluginService::GetInstance()->RefreshPlugins(); } } // namespace class WidevineCdmComponentInstallerTraits : public ComponentInstallerTraits { public: WidevineCdmComponentInstallerTraits(); virtual ~WidevineCdmComponentInstallerTraits() {} private: // The following methods override ComponentInstallerTraits. virtual bool CanAutoUpdate() const OVERRIDE; virtual bool OnCustomInstall(const base::DictionaryValue& manifest, const base::FilePath& install_dir) OVERRIDE; virtual bool VerifyInstallation( const base::FilePath& install_dir) const OVERRIDE; virtual void ComponentReady(const base::Version& version, const base::FilePath& path) OVERRIDE; virtual base::FilePath GetBaseDirectory() const OVERRIDE; virtual void GetHash(std::vector<uint8>* hash) const OVERRIDE; virtual std::string GetName() const OVERRIDE; DISALLOW_COPY_AND_ASSIGN(WidevineCdmComponentInstallerTraits); }; WidevineCdmComponentInstallerTraits::WidevineCdmComponentInstallerTraits() { } bool WidevineCdmComponentInstallerTraits::CanAutoUpdate() const { return true; } // The adapter is copied into the install directory as part of the installation. bool WidevineCdmComponentInstallerTraits::OnCustomInstall( const base::DictionaryValue& manifest, const base::FilePath& install_path) { base::FilePath adapter_install_path = GetPlatformDirectory(install_path) .AppendASCII(kWidevineCdmAdapterFileName); base::FilePath adapter_source_path; PathService::Get(chrome::FILE_WIDEVINE_CDM_ADAPTER, &adapter_source_path); return base::CopyFile(adapter_source_path, adapter_install_path); } // Once the component is installed, register the new version with Chrome. void WidevineCdmComponentInstallerTraits::ComponentReady( const base::Version& version, const base::FilePath& path) { base::FilePath adapter_install_path = GetPlatformDirectory(path) .AppendASCII(kWidevineCdmAdapterFileName); BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, base::Bind( &RegisterWidevineCdmWithChrome, adapter_install_path, version)); } bool WidevineCdmComponentInstallerTraits::VerifyInstallation( const base::FilePath& install_dir) const { return base::PathExists(GetPlatformDirectory(install_dir) .AppendASCII(kWidevineCdmFileName)) && base::PathExists(GetPlatformDirectory(install_dir) .AppendASCII(kWidevineCdmAdapterFileName)); } // The base directory on Windows looks like: // <profile>\AppData\Local\Google\Chrome\User Data\WidevineCdm\. base::FilePath WidevineCdmComponentInstallerTraits::GetBaseDirectory() const { base::FilePath result; PathService::Get(chrome::DIR_COMPONENT_WIDEVINE_CDM, &result); return result; } void WidevineCdmComponentInstallerTraits::GetHash( std::vector<uint8>* hash) const { hash->assign(kSha2Hash, kSha2Hash + arraysize(kSha2Hash)); } std::string WidevineCdmComponentInstallerTraits::GetName() const { return kWidevineCdmManifestName; } #endif // defined(WIDEVINE_CDM_AVAILABLE) && defined(WIDEVINE_CDM_IS_COMPONENT) void RegisterWidevineCdmComponent(ComponentUpdateService* cus) { #if defined(WIDEVINE_CDM_AVAILABLE) && defined(WIDEVINE_CDM_IS_COMPONENT) base::FilePath adapter_source_path; PathService::Get(chrome::FILE_WIDEVINE_CDM_ADAPTER, &adapter_source_path); if (!base::PathExists(adapter_source_path)) return; scoped_ptr<ComponentInstallerTraits> traits( new WidevineCdmComponentInstallerTraits); // |cus| will take ownership of |installer| during installer->Register(cus). DefaultComponentInstaller* installer = new DefaultComponentInstaller(traits.Pass()); installer->Register(cus); #else return; #endif // defined(WIDEVINE_CDM_AVAILABLE) && defined(WIDEVINE_CDM_IS_COMPONENT) } <|endoftext|>
<commit_before>/* * Handler for raw TCP connections. * * author: Max Kellermann <mk@cm4all.com> */ #include "lb_tcp.hxx" #include "filtered_socket.hxx" #include "address_list.hxx" #include "client_balancer.hxx" #include "address_sticky.h" #include "async.hxx" #include "direct.hxx" #include "pool.hxx" #include "net/ConnectSocket.hxx" #include "net/SocketDescriptor.hxx" #include "net/SocketAddress.hxx" #include <unistd.h> #include <errno.h> struct LbTcpConnection final : ConnectSocketHandler { struct pool *pool; Stock *pipe_stock; const LbTcpConnectionHandler *handler; void *handler_ctx; FilteredSocket inbound; BufferedSocket outbound; struct async_operation_ref connect; bool got_inbound_data, got_outbound_data; /* virtual methods from class ConnectSocketHandler */ void OnSocketConnectSuccess(SocketDescriptor &&fd) override; void OnSocketConnectTimeout() override; void OnSocketConnectError(GError *error) override; }; static constexpr timeval write_timeout = { 30, 0 }; static void lb_tcp_destroy_inbound(LbTcpConnection *tcp) { if (tcp->inbound.IsConnected()) tcp->inbound.Close(); tcp->inbound.Destroy(); } static void lb_tcp_destroy_outbound(LbTcpConnection *tcp) { if (tcp->outbound.IsConnected()) tcp->outbound.Close(); tcp->outbound.Destroy(); } /* * inbound BufferedSocketHandler * */ static BufferedResult inbound_buffered_socket_data(const void *buffer, size_t size, void *ctx) { LbTcpConnection *tcp = (LbTcpConnection *)ctx; tcp->got_inbound_data = true; if (tcp->connect.IsDefined()) /* outbound is not yet connected */ return BufferedResult::BLOCKING; if (!tcp->outbound.IsValid()) { lb_tcp_close(tcp); tcp->handler->error("Send error", "Broken socket", tcp->handler_ctx); return BufferedResult::CLOSED; } ssize_t nbytes = tcp->outbound.Write(buffer, size); if (nbytes > 0) { tcp->inbound.Consumed(nbytes); return (size_t)nbytes == size ? BufferedResult::OK : BufferedResult::PARTIAL; } switch ((enum write_result)nbytes) { case WRITE_SOURCE_EOF: assert(false); gcc_unreachable(); case WRITE_ERRNO: lb_tcp_close(tcp); tcp->handler->_errno("Send failed", errno, tcp->handler_ctx); return BufferedResult::CLOSED; case WRITE_BLOCKING: return BufferedResult::BLOCKING; case WRITE_DESTROYED: return BufferedResult::CLOSED; case WRITE_BROKEN: lb_tcp_close(tcp); tcp->handler->eof(tcp->handler_ctx); return BufferedResult::CLOSED; } assert(false); gcc_unreachable(); } static bool inbound_buffered_socket_closed(void *ctx) { LbTcpConnection *tcp = (LbTcpConnection *)ctx; lb_tcp_close(tcp); tcp->handler->eof(tcp->handler_ctx); return false; } static bool inbound_buffered_socket_write(void *ctx) { LbTcpConnection *tcp = (LbTcpConnection *)ctx; tcp->got_outbound_data = false; if (!tcp->outbound.Read(false)) return false; if (!tcp->got_outbound_data) tcp->inbound.UnscheduleWrite(); return true; } static bool inbound_buffered_socket_drained(void *ctx) { LbTcpConnection *tcp = (LbTcpConnection *)ctx; if (!tcp->outbound.IsValid()) { /* now that inbound's output buffers are drained, we can finally close the connection (postponed from outbound_buffered_socket_end()) */ lb_tcp_close(tcp); tcp->handler->eof(tcp->handler_ctx); return false; } return true; } static enum write_result inbound_buffered_socket_broken(void *ctx) { LbTcpConnection *tcp = (LbTcpConnection *)ctx; lb_tcp_close(tcp); tcp->handler->eof(tcp->handler_ctx); return WRITE_DESTROYED; } static void inbound_buffered_socket_error(GError *error, void *ctx) { LbTcpConnection *tcp = (LbTcpConnection *)ctx; lb_tcp_close(tcp); tcp->handler->gerror("Error", error, tcp->handler_ctx); } static constexpr BufferedSocketHandler inbound_buffered_socket_handler = { inbound_buffered_socket_data, nullptr, // TODO: inbound_buffered_socket_direct, inbound_buffered_socket_closed, nullptr, nullptr, inbound_buffered_socket_write, inbound_buffered_socket_drained, nullptr, inbound_buffered_socket_broken, inbound_buffered_socket_error, }; /* * outbound buffered_socket_handler * */ static BufferedResult outbound_buffered_socket_data(const void *buffer, size_t size, void *ctx) { LbTcpConnection *tcp = (LbTcpConnection *)ctx; tcp->got_outbound_data = true; ssize_t nbytes = tcp->inbound.Write(buffer, size); if (nbytes > 0) { tcp->outbound.Consumed(nbytes); return (size_t)nbytes == size ? BufferedResult::OK : BufferedResult::PARTIAL; } switch ((enum write_result)nbytes) { int save_errno; case WRITE_SOURCE_EOF: assert(false); gcc_unreachable(); case WRITE_ERRNO: save_errno = errno; lb_tcp_close(tcp); tcp->handler->_errno("Send failed", save_errno, tcp->handler_ctx); return BufferedResult::CLOSED; case WRITE_BLOCKING: return BufferedResult::BLOCKING; case WRITE_DESTROYED: return BufferedResult::CLOSED; case WRITE_BROKEN: lb_tcp_close(tcp); tcp->handler->eof(tcp->handler_ctx); return BufferedResult::CLOSED; } assert(false); gcc_unreachable(); } static bool outbound_buffered_socket_closed(void *ctx) { LbTcpConnection *tcp = (LbTcpConnection *)ctx; tcp->outbound.Close(); return true; } static void outbound_buffered_socket_end(void *ctx) { LbTcpConnection *tcp = (LbTcpConnection *)ctx; tcp->outbound.Destroy(); tcp->inbound.UnscheduleWrite(); if (tcp->inbound.IsDrained()) { /* all output buffers to "inbound" are drained; close the connection, because there's nothing left to do */ lb_tcp_close(tcp); tcp->handler->eof(tcp->handler_ctx); /* nothing will be done if the buffers are not yet drained; we're waiting for inbound_buffered_socket_drained() to be called */ } } static bool outbound_buffered_socket_write(void *ctx) { LbTcpConnection *tcp = (LbTcpConnection *)ctx; tcp->got_inbound_data = false; if (!tcp->inbound.Read(false)) return false; if (!tcp->got_inbound_data) tcp->outbound.UnscheduleWrite(); return true; } static enum write_result outbound_buffered_socket_broken(void *ctx) { LbTcpConnection *tcp = (LbTcpConnection *)ctx; lb_tcp_close(tcp); tcp->handler->eof(tcp->handler_ctx); return WRITE_DESTROYED; } static void outbound_buffered_socket_error(GError *error, void *ctx) { LbTcpConnection *tcp = (LbTcpConnection *)ctx; lb_tcp_close(tcp); tcp->handler->gerror("Error", error, tcp->handler_ctx); } static constexpr BufferedSocketHandler outbound_buffered_socket_handler = { outbound_buffered_socket_data, nullptr, // TODO: outbound_buffered_socket_direct, outbound_buffered_socket_closed, nullptr, outbound_buffered_socket_end, outbound_buffered_socket_write, nullptr, nullptr, outbound_buffered_socket_broken, outbound_buffered_socket_error, }; /* * ConnectSocketHandler * */ void LbTcpConnection::OnSocketConnectSuccess(SocketDescriptor &&fd) { connect.Clear(); outbound.Init(*pool, fd.Steal(), FdType::FD_TCP, nullptr, &write_timeout, outbound_buffered_socket_handler, this); /* TODO outbound.direct = pipe_stock != nullptr && (ISTREAM_TO_TCP & FdType::FD_PIPE) != 0 && (istream_direct_mask_to(inbound.base.base.fd_type) & FdType::FD_PIPE) != 0; */ if (inbound.Read(false)) outbound.Read(false); } void LbTcpConnection::OnSocketConnectTimeout() { lb_tcp_destroy_inbound(this); handler->error("Connect error", "Timeout", handler_ctx); } void LbTcpConnection::OnSocketConnectError(GError *error) { lb_tcp_destroy_inbound(this); handler->gerror("Connect error", error, handler_ctx); } /* * constructor * */ gcc_pure static unsigned lb_tcp_sticky(const AddressList &address_list, const struct sockaddr *remote_address) { switch (address_list.sticky_mode) { case StickyMode::NONE: case StickyMode::FAILOVER: break; case StickyMode::SOURCE_IP: return socket_address_sticky(remote_address); case StickyMode::SESSION_MODULO: case StickyMode::COOKIE: case StickyMode::JVM_ROUTE: /* not implemented here */ break; } return 0; } void lb_tcp_new(struct pool *pool, Stock *pipe_stock, SocketDescriptor &&fd, FdType fd_type, const SocketFilter *filter, void *filter_ctx, SocketAddress remote_address, bool transparent_source, const AddressList &address_list, struct balancer &balancer, const LbTcpConnectionHandler *handler, void *ctx, LbTcpConnection **tcp_r) { auto *tcp = NewFromPool<LbTcpConnection>(*pool); tcp->pool = pool; tcp->pipe_stock = pipe_stock; tcp->handler = handler; tcp->handler_ctx = ctx; tcp->inbound.Init(*pool, fd.Steal(), fd_type, nullptr, &write_timeout, filter, filter_ctx, inbound_buffered_socket_handler, tcp); /* TODO tcp->inbound.base.direct = pipe_stock != nullptr && (ISTREAM_TO_PIPE & fd_type) != 0 && (ISTREAM_TO_TCP & FdType::FD_PIPE) != 0; */ unsigned session_sticky = lb_tcp_sticky(address_list, remote_address.GetAddress()); SocketAddress bind_address = SocketAddress::Null(); if (transparent_source) { bind_address = remote_address; /* reset the port to 0 to allow the kernel to choose one */ if (bind_address.GetFamily() == AF_INET) { struct sockaddr_in *s_in = (struct sockaddr_in *) p_memdup(pool, bind_address.GetAddress(), bind_address.GetSize()); s_in->sin_port = 0; bind_address = SocketAddress((const struct sockaddr *)s_in, bind_address.GetSize()); } else if (bind_address.GetFamily() == AF_INET6) { struct sockaddr_in6 *s_in = (struct sockaddr_in6 *) p_memdup(pool, bind_address.GetAddress(), bind_address.GetSize()); s_in->sin6_port = 0; bind_address = SocketAddress((const struct sockaddr *)s_in, bind_address.GetSize()); } } *tcp_r = tcp; client_balancer_connect(pool, &balancer, transparent_source, bind_address, session_sticky, &address_list, 20, *tcp, &tcp->connect); } void lb_tcp_close(LbTcpConnection *tcp) { if (tcp->inbound.IsValid()) lb_tcp_destroy_inbound(tcp); if (tcp->connect.IsDefined()) tcp->connect.Abort(); else if (tcp->outbound.IsValid()) lb_tcp_destroy_outbound(tcp); } <commit_msg>lb_tcp: move functions into the struct<commit_after>/* * Handler for raw TCP connections. * * author: Max Kellermann <mk@cm4all.com> */ #include "lb_tcp.hxx" #include "filtered_socket.hxx" #include "address_list.hxx" #include "client_balancer.hxx" #include "address_sticky.h" #include "async.hxx" #include "direct.hxx" #include "pool.hxx" #include "net/ConnectSocket.hxx" #include "net/SocketDescriptor.hxx" #include "net/SocketAddress.hxx" #include <unistd.h> #include <errno.h> struct LbTcpConnection final : ConnectSocketHandler { struct pool *pool; Stock *pipe_stock; const LbTcpConnectionHandler *handler; void *handler_ctx; FilteredSocket inbound; BufferedSocket outbound; struct async_operation_ref connect; bool got_inbound_data, got_outbound_data; void DestroyInbound(); void DestroyOutbound(); /* virtual methods from class ConnectSocketHandler */ void OnSocketConnectSuccess(SocketDescriptor &&fd) override; void OnSocketConnectTimeout() override; void OnSocketConnectError(GError *error) override; }; static constexpr timeval write_timeout = { 30, 0 }; void LbTcpConnection::DestroyInbound() { if (inbound.IsConnected()) inbound.Close(); inbound.Destroy(); } void LbTcpConnection::DestroyOutbound() { if (outbound.IsConnected()) outbound.Close(); outbound.Destroy(); } /* * inbound BufferedSocketHandler * */ static BufferedResult inbound_buffered_socket_data(const void *buffer, size_t size, void *ctx) { LbTcpConnection *tcp = (LbTcpConnection *)ctx; tcp->got_inbound_data = true; if (tcp->connect.IsDefined()) /* outbound is not yet connected */ return BufferedResult::BLOCKING; if (!tcp->outbound.IsValid()) { lb_tcp_close(tcp); tcp->handler->error("Send error", "Broken socket", tcp->handler_ctx); return BufferedResult::CLOSED; } ssize_t nbytes = tcp->outbound.Write(buffer, size); if (nbytes > 0) { tcp->inbound.Consumed(nbytes); return (size_t)nbytes == size ? BufferedResult::OK : BufferedResult::PARTIAL; } switch ((enum write_result)nbytes) { case WRITE_SOURCE_EOF: assert(false); gcc_unreachable(); case WRITE_ERRNO: lb_tcp_close(tcp); tcp->handler->_errno("Send failed", errno, tcp->handler_ctx); return BufferedResult::CLOSED; case WRITE_BLOCKING: return BufferedResult::BLOCKING; case WRITE_DESTROYED: return BufferedResult::CLOSED; case WRITE_BROKEN: lb_tcp_close(tcp); tcp->handler->eof(tcp->handler_ctx); return BufferedResult::CLOSED; } assert(false); gcc_unreachable(); } static bool inbound_buffered_socket_closed(void *ctx) { LbTcpConnection *tcp = (LbTcpConnection *)ctx; lb_tcp_close(tcp); tcp->handler->eof(tcp->handler_ctx); return false; } static bool inbound_buffered_socket_write(void *ctx) { LbTcpConnection *tcp = (LbTcpConnection *)ctx; tcp->got_outbound_data = false; if (!tcp->outbound.Read(false)) return false; if (!tcp->got_outbound_data) tcp->inbound.UnscheduleWrite(); return true; } static bool inbound_buffered_socket_drained(void *ctx) { LbTcpConnection *tcp = (LbTcpConnection *)ctx; if (!tcp->outbound.IsValid()) { /* now that inbound's output buffers are drained, we can finally close the connection (postponed from outbound_buffered_socket_end()) */ lb_tcp_close(tcp); tcp->handler->eof(tcp->handler_ctx); return false; } return true; } static enum write_result inbound_buffered_socket_broken(void *ctx) { LbTcpConnection *tcp = (LbTcpConnection *)ctx; lb_tcp_close(tcp); tcp->handler->eof(tcp->handler_ctx); return WRITE_DESTROYED; } static void inbound_buffered_socket_error(GError *error, void *ctx) { LbTcpConnection *tcp = (LbTcpConnection *)ctx; lb_tcp_close(tcp); tcp->handler->gerror("Error", error, tcp->handler_ctx); } static constexpr BufferedSocketHandler inbound_buffered_socket_handler = { inbound_buffered_socket_data, nullptr, // TODO: inbound_buffered_socket_direct, inbound_buffered_socket_closed, nullptr, nullptr, inbound_buffered_socket_write, inbound_buffered_socket_drained, nullptr, inbound_buffered_socket_broken, inbound_buffered_socket_error, }; /* * outbound buffered_socket_handler * */ static BufferedResult outbound_buffered_socket_data(const void *buffer, size_t size, void *ctx) { LbTcpConnection *tcp = (LbTcpConnection *)ctx; tcp->got_outbound_data = true; ssize_t nbytes = tcp->inbound.Write(buffer, size); if (nbytes > 0) { tcp->outbound.Consumed(nbytes); return (size_t)nbytes == size ? BufferedResult::OK : BufferedResult::PARTIAL; } switch ((enum write_result)nbytes) { int save_errno; case WRITE_SOURCE_EOF: assert(false); gcc_unreachable(); case WRITE_ERRNO: save_errno = errno; lb_tcp_close(tcp); tcp->handler->_errno("Send failed", save_errno, tcp->handler_ctx); return BufferedResult::CLOSED; case WRITE_BLOCKING: return BufferedResult::BLOCKING; case WRITE_DESTROYED: return BufferedResult::CLOSED; case WRITE_BROKEN: lb_tcp_close(tcp); tcp->handler->eof(tcp->handler_ctx); return BufferedResult::CLOSED; } assert(false); gcc_unreachable(); } static bool outbound_buffered_socket_closed(void *ctx) { LbTcpConnection *tcp = (LbTcpConnection *)ctx; tcp->outbound.Close(); return true; } static void outbound_buffered_socket_end(void *ctx) { LbTcpConnection *tcp = (LbTcpConnection *)ctx; tcp->outbound.Destroy(); tcp->inbound.UnscheduleWrite(); if (tcp->inbound.IsDrained()) { /* all output buffers to "inbound" are drained; close the connection, because there's nothing left to do */ lb_tcp_close(tcp); tcp->handler->eof(tcp->handler_ctx); /* nothing will be done if the buffers are not yet drained; we're waiting for inbound_buffered_socket_drained() to be called */ } } static bool outbound_buffered_socket_write(void *ctx) { LbTcpConnection *tcp = (LbTcpConnection *)ctx; tcp->got_inbound_data = false; if (!tcp->inbound.Read(false)) return false; if (!tcp->got_inbound_data) tcp->outbound.UnscheduleWrite(); return true; } static enum write_result outbound_buffered_socket_broken(void *ctx) { LbTcpConnection *tcp = (LbTcpConnection *)ctx; lb_tcp_close(tcp); tcp->handler->eof(tcp->handler_ctx); return WRITE_DESTROYED; } static void outbound_buffered_socket_error(GError *error, void *ctx) { LbTcpConnection *tcp = (LbTcpConnection *)ctx; lb_tcp_close(tcp); tcp->handler->gerror("Error", error, tcp->handler_ctx); } static constexpr BufferedSocketHandler outbound_buffered_socket_handler = { outbound_buffered_socket_data, nullptr, // TODO: outbound_buffered_socket_direct, outbound_buffered_socket_closed, nullptr, outbound_buffered_socket_end, outbound_buffered_socket_write, nullptr, nullptr, outbound_buffered_socket_broken, outbound_buffered_socket_error, }; /* * ConnectSocketHandler * */ void LbTcpConnection::OnSocketConnectSuccess(SocketDescriptor &&fd) { connect.Clear(); outbound.Init(*pool, fd.Steal(), FdType::FD_TCP, nullptr, &write_timeout, outbound_buffered_socket_handler, this); /* TODO outbound.direct = pipe_stock != nullptr && (ISTREAM_TO_TCP & FdType::FD_PIPE) != 0 && (istream_direct_mask_to(inbound.base.base.fd_type) & FdType::FD_PIPE) != 0; */ if (inbound.Read(false)) outbound.Read(false); } void LbTcpConnection::OnSocketConnectTimeout() { DestroyInbound(); handler->error("Connect error", "Timeout", handler_ctx); } void LbTcpConnection::OnSocketConnectError(GError *error) { DestroyInbound(); handler->gerror("Connect error", error, handler_ctx); } /* * constructor * */ gcc_pure static unsigned lb_tcp_sticky(const AddressList &address_list, const struct sockaddr *remote_address) { switch (address_list.sticky_mode) { case StickyMode::NONE: case StickyMode::FAILOVER: break; case StickyMode::SOURCE_IP: return socket_address_sticky(remote_address); case StickyMode::SESSION_MODULO: case StickyMode::COOKIE: case StickyMode::JVM_ROUTE: /* not implemented here */ break; } return 0; } void lb_tcp_new(struct pool *pool, Stock *pipe_stock, SocketDescriptor &&fd, FdType fd_type, const SocketFilter *filter, void *filter_ctx, SocketAddress remote_address, bool transparent_source, const AddressList &address_list, struct balancer &balancer, const LbTcpConnectionHandler *handler, void *ctx, LbTcpConnection **tcp_r) { auto *tcp = NewFromPool<LbTcpConnection>(*pool); tcp->pool = pool; tcp->pipe_stock = pipe_stock; tcp->handler = handler; tcp->handler_ctx = ctx; tcp->inbound.Init(*pool, fd.Steal(), fd_type, nullptr, &write_timeout, filter, filter_ctx, inbound_buffered_socket_handler, tcp); /* TODO tcp->inbound.base.direct = pipe_stock != nullptr && (ISTREAM_TO_PIPE & fd_type) != 0 && (ISTREAM_TO_TCP & FdType::FD_PIPE) != 0; */ unsigned session_sticky = lb_tcp_sticky(address_list, remote_address.GetAddress()); SocketAddress bind_address = SocketAddress::Null(); if (transparent_source) { bind_address = remote_address; /* reset the port to 0 to allow the kernel to choose one */ if (bind_address.GetFamily() == AF_INET) { struct sockaddr_in *s_in = (struct sockaddr_in *) p_memdup(pool, bind_address.GetAddress(), bind_address.GetSize()); s_in->sin_port = 0; bind_address = SocketAddress((const struct sockaddr *)s_in, bind_address.GetSize()); } else if (bind_address.GetFamily() == AF_INET6) { struct sockaddr_in6 *s_in = (struct sockaddr_in6 *) p_memdup(pool, bind_address.GetAddress(), bind_address.GetSize()); s_in->sin6_port = 0; bind_address = SocketAddress((const struct sockaddr *)s_in, bind_address.GetSize()); } } *tcp_r = tcp; client_balancer_connect(pool, &balancer, transparent_source, bind_address, session_sticky, &address_list, 20, *tcp, &tcp->connect); } void lb_tcp_close(LbTcpConnection *tcp) { if (tcp->inbound.IsValid()) tcp->DestroyInbound(); if (tcp->connect.IsDefined()) tcp->connect.Abort(); else if (tcp->outbound.IsValid()) tcp->DestroyOutbound(); } <|endoftext|>
<commit_before>/* * Handler for raw TCP connections. * * author: Max Kellermann <mk@cm4all.com> */ #include "lb_tcp.hxx" #include "filtered_socket.hxx" #include "address_list.hxx" #include "client_balancer.hxx" #include "address_sticky.hxx" #include "direct.hxx" #include "pool.hxx" #include "async.hxx" #include "net/ConnectSocket.hxx" #include "net/SocketDescriptor.hxx" #include "net/SocketAddress.hxx" #include <unistd.h> #include <errno.h> struct LbTcpConnection final : ConnectSocketHandler { struct pool *pool; Stock *pipe_stock; const LbTcpConnectionHandler *handler; void *handler_ctx; FilteredSocket inbound; BufferedSocket outbound; struct async_operation_ref connect; bool got_inbound_data, got_outbound_data; explicit LbTcpConnection(EventLoop &event_loop) :inbound(event_loop), outbound(event_loop) {} void DestroyInbound(); void DestroyOutbound(); /* virtual methods from class ConnectSocketHandler */ void OnSocketConnectSuccess(SocketDescriptor &&fd) override; void OnSocketConnectTimeout() override; void OnSocketConnectError(GError *error) override; }; static constexpr timeval write_timeout = { 30, 0 }; void LbTcpConnection::DestroyInbound() { if (inbound.IsConnected()) inbound.Close(); inbound.Destroy(); } void LbTcpConnection::DestroyOutbound() { if (outbound.IsConnected()) outbound.Close(); outbound.Destroy(); } /* * inbound BufferedSocketHandler * */ static BufferedResult inbound_buffered_socket_data(const void *buffer, size_t size, void *ctx) { LbTcpConnection *tcp = (LbTcpConnection *)ctx; tcp->got_inbound_data = true; if (tcp->connect.IsDefined()) /* outbound is not yet connected */ return BufferedResult::BLOCKING; if (!tcp->outbound.IsValid()) { lb_tcp_close(tcp); tcp->handler->error("Send error", "Broken socket", tcp->handler_ctx); return BufferedResult::CLOSED; } ssize_t nbytes = tcp->outbound.Write(buffer, size); if (nbytes > 0) { tcp->inbound.Consumed(nbytes); return (size_t)nbytes == size ? BufferedResult::OK : BufferedResult::PARTIAL; } switch ((enum write_result)nbytes) { case WRITE_SOURCE_EOF: assert(false); gcc_unreachable(); case WRITE_ERRNO: lb_tcp_close(tcp); tcp->handler->_errno("Send failed", errno, tcp->handler_ctx); return BufferedResult::CLOSED; case WRITE_BLOCKING: return BufferedResult::BLOCKING; case WRITE_DESTROYED: return BufferedResult::CLOSED; case WRITE_BROKEN: lb_tcp_close(tcp); tcp->handler->eof(tcp->handler_ctx); return BufferedResult::CLOSED; } assert(false); gcc_unreachable(); } static bool inbound_buffered_socket_closed(void *ctx) { LbTcpConnection *tcp = (LbTcpConnection *)ctx; lb_tcp_close(tcp); tcp->handler->eof(tcp->handler_ctx); return false; } static bool inbound_buffered_socket_write(void *ctx) { LbTcpConnection *tcp = (LbTcpConnection *)ctx; tcp->got_outbound_data = false; if (!tcp->outbound.Read(false)) return false; if (!tcp->got_outbound_data) tcp->inbound.UnscheduleWrite(); return true; } static bool inbound_buffered_socket_drained(void *ctx) { LbTcpConnection *tcp = (LbTcpConnection *)ctx; if (!tcp->outbound.IsValid()) { /* now that inbound's output buffers are drained, we can finally close the connection (postponed from outbound_buffered_socket_end()) */ lb_tcp_close(tcp); tcp->handler->eof(tcp->handler_ctx); return false; } return true; } static enum write_result inbound_buffered_socket_broken(void *ctx) { LbTcpConnection *tcp = (LbTcpConnection *)ctx; lb_tcp_close(tcp); tcp->handler->eof(tcp->handler_ctx); return WRITE_DESTROYED; } static void inbound_buffered_socket_error(GError *error, void *ctx) { LbTcpConnection *tcp = (LbTcpConnection *)ctx; lb_tcp_close(tcp); tcp->handler->gerror("Error", error, tcp->handler_ctx); } static constexpr BufferedSocketHandler inbound_buffered_socket_handler = { inbound_buffered_socket_data, nullptr, // TODO: inbound_buffered_socket_direct, inbound_buffered_socket_closed, nullptr, nullptr, inbound_buffered_socket_write, inbound_buffered_socket_drained, nullptr, inbound_buffered_socket_broken, inbound_buffered_socket_error, }; /* * outbound buffered_socket_handler * */ static BufferedResult outbound_buffered_socket_data(const void *buffer, size_t size, void *ctx) { LbTcpConnection *tcp = (LbTcpConnection *)ctx; tcp->got_outbound_data = true; ssize_t nbytes = tcp->inbound.Write(buffer, size); if (nbytes > 0) { tcp->outbound.Consumed(nbytes); return (size_t)nbytes == size ? BufferedResult::OK : BufferedResult::PARTIAL; } switch ((enum write_result)nbytes) { int save_errno; case WRITE_SOURCE_EOF: assert(false); gcc_unreachable(); case WRITE_ERRNO: save_errno = errno; lb_tcp_close(tcp); tcp->handler->_errno("Send failed", save_errno, tcp->handler_ctx); return BufferedResult::CLOSED; case WRITE_BLOCKING: return BufferedResult::BLOCKING; case WRITE_DESTROYED: return BufferedResult::CLOSED; case WRITE_BROKEN: lb_tcp_close(tcp); tcp->handler->eof(tcp->handler_ctx); return BufferedResult::CLOSED; } assert(false); gcc_unreachable(); } static bool outbound_buffered_socket_closed(void *ctx) { LbTcpConnection *tcp = (LbTcpConnection *)ctx; tcp->outbound.Close(); return true; } static void outbound_buffered_socket_end(void *ctx) { LbTcpConnection *tcp = (LbTcpConnection *)ctx; tcp->outbound.Destroy(); tcp->inbound.UnscheduleWrite(); if (tcp->inbound.IsDrained()) { /* all output buffers to "inbound" are drained; close the connection, because there's nothing left to do */ lb_tcp_close(tcp); tcp->handler->eof(tcp->handler_ctx); /* nothing will be done if the buffers are not yet drained; we're waiting for inbound_buffered_socket_drained() to be called */ } } static bool outbound_buffered_socket_write(void *ctx) { LbTcpConnection *tcp = (LbTcpConnection *)ctx; tcp->got_inbound_data = false; if (!tcp->inbound.Read(false)) return false; if (!tcp->got_inbound_data) tcp->outbound.UnscheduleWrite(); return true; } static enum write_result outbound_buffered_socket_broken(void *ctx) { LbTcpConnection *tcp = (LbTcpConnection *)ctx; lb_tcp_close(tcp); tcp->handler->eof(tcp->handler_ctx); return WRITE_DESTROYED; } static void outbound_buffered_socket_error(GError *error, void *ctx) { LbTcpConnection *tcp = (LbTcpConnection *)ctx; lb_tcp_close(tcp); tcp->handler->gerror("Error", error, tcp->handler_ctx); } static constexpr BufferedSocketHandler outbound_buffered_socket_handler = { outbound_buffered_socket_data, nullptr, // TODO: outbound_buffered_socket_direct, outbound_buffered_socket_closed, nullptr, outbound_buffered_socket_end, outbound_buffered_socket_write, nullptr, nullptr, outbound_buffered_socket_broken, outbound_buffered_socket_error, }; /* * ConnectSocketHandler * */ void LbTcpConnection::OnSocketConnectSuccess(SocketDescriptor &&fd) { connect.Clear(); outbound.Init(fd.Steal(), FdType::FD_TCP, nullptr, &write_timeout, outbound_buffered_socket_handler, this); /* TODO outbound.direct = pipe_stock != nullptr && (ISTREAM_TO_TCP & FdType::FD_PIPE) != 0 && (istream_direct_mask_to(inbound.base.base.fd_type) & FdType::FD_PIPE) != 0; */ if (inbound.Read(false)) outbound.Read(false); } void LbTcpConnection::OnSocketConnectTimeout() { DestroyInbound(); handler->error("Connect error", "Timeout", handler_ctx); } void LbTcpConnection::OnSocketConnectError(GError *error) { DestroyInbound(); handler->gerror("Connect error", error, handler_ctx); } /* * constructor * */ gcc_pure static unsigned lb_tcp_sticky(const AddressList &address_list, SocketAddress remote_address) { switch (address_list.sticky_mode) { case StickyMode::NONE: case StickyMode::FAILOVER: break; case StickyMode::SOURCE_IP: return socket_address_sticky(remote_address); case StickyMode::SESSION_MODULO: case StickyMode::COOKIE: case StickyMode::JVM_ROUTE: /* not implemented here */ break; } return 0; } void lb_tcp_new(struct pool *pool, EventLoop &event_loop, Stock *pipe_stock, SocketDescriptor &&fd, FdType fd_type, const SocketFilter *filter, void *filter_ctx, SocketAddress remote_address, bool transparent_source, const AddressList &address_list, Balancer &balancer, const LbTcpConnectionHandler *handler, void *ctx, LbTcpConnection **tcp_r) { auto *tcp = NewFromPool<LbTcpConnection>(*pool, event_loop); tcp->pool = pool; tcp->pipe_stock = pipe_stock; tcp->handler = handler; tcp->handler_ctx = ctx; tcp->inbound.Init(fd.Steal(), fd_type, nullptr, &write_timeout, filter, filter_ctx, inbound_buffered_socket_handler, tcp); /* TODO tcp->inbound.base.direct = pipe_stock != nullptr && (ISTREAM_TO_PIPE & fd_type) != 0 && (ISTREAM_TO_TCP & FdType::FD_PIPE) != 0; */ unsigned session_sticky = lb_tcp_sticky(address_list, remote_address); SocketAddress bind_address = SocketAddress::Null(); if (transparent_source) { bind_address = remote_address; /* reset the port to 0 to allow the kernel to choose one */ if (bind_address.GetFamily() == AF_INET) { struct sockaddr_in *s_in = (struct sockaddr_in *) p_memdup(pool, bind_address.GetAddress(), bind_address.GetSize()); s_in->sin_port = 0; bind_address = SocketAddress((const struct sockaddr *)s_in, bind_address.GetSize()); } else if (bind_address.GetFamily() == AF_INET6) { struct sockaddr_in6 *s_in = (struct sockaddr_in6 *) p_memdup(pool, bind_address.GetAddress(), bind_address.GetSize()); s_in->sin6_port = 0; bind_address = SocketAddress((const struct sockaddr *)s_in, bind_address.GetSize()); } } *tcp_r = tcp; client_balancer_connect(event_loop, *pool, balancer, transparent_source, bind_address, session_sticky, &address_list, 20, *tcp, tcp->connect); } void lb_tcp_close(LbTcpConnection *tcp) { if (tcp->inbound.IsValid()) tcp->DestroyInbound(); if (tcp->connect.IsDefined()) tcp->connect.Abort(); else if (tcp->outbound.IsValid()) tcp->DestroyOutbound(); } <commit_msg>lb_tcp: migrate to CancellablePointer<commit_after>/* * Handler for raw TCP connections. * * author: Max Kellermann <mk@cm4all.com> */ #include "lb_tcp.hxx" #include "filtered_socket.hxx" #include "address_list.hxx" #include "client_balancer.hxx" #include "address_sticky.hxx" #include "direct.hxx" #include "pool.hxx" #include "net/ConnectSocket.hxx" #include "net/SocketDescriptor.hxx" #include "net/SocketAddress.hxx" #include "util/Cancellable.hxx" #include <unistd.h> #include <errno.h> struct LbTcpConnection final : ConnectSocketHandler { struct pool *pool; Stock *pipe_stock; const LbTcpConnectionHandler *handler; void *handler_ctx; FilteredSocket inbound; BufferedSocket outbound; CancellablePointer cancel_connect; bool got_inbound_data, got_outbound_data; explicit LbTcpConnection(EventLoop &event_loop) :inbound(event_loop), outbound(event_loop) {} void DestroyInbound(); void DestroyOutbound(); /* virtual methods from class ConnectSocketHandler */ void OnSocketConnectSuccess(SocketDescriptor &&fd) override; void OnSocketConnectTimeout() override; void OnSocketConnectError(GError *error) override; }; static constexpr timeval write_timeout = { 30, 0 }; void LbTcpConnection::DestroyInbound() { if (inbound.IsConnected()) inbound.Close(); inbound.Destroy(); } void LbTcpConnection::DestroyOutbound() { if (outbound.IsConnected()) outbound.Close(); outbound.Destroy(); } /* * inbound BufferedSocketHandler * */ static BufferedResult inbound_buffered_socket_data(const void *buffer, size_t size, void *ctx) { LbTcpConnection *tcp = (LbTcpConnection *)ctx; tcp->got_inbound_data = true; if (tcp->cancel_connect) /* outbound is not yet connected */ return BufferedResult::BLOCKING; if (!tcp->outbound.IsValid()) { lb_tcp_close(tcp); tcp->handler->error("Send error", "Broken socket", tcp->handler_ctx); return BufferedResult::CLOSED; } ssize_t nbytes = tcp->outbound.Write(buffer, size); if (nbytes > 0) { tcp->inbound.Consumed(nbytes); return (size_t)nbytes == size ? BufferedResult::OK : BufferedResult::PARTIAL; } switch ((enum write_result)nbytes) { case WRITE_SOURCE_EOF: assert(false); gcc_unreachable(); case WRITE_ERRNO: lb_tcp_close(tcp); tcp->handler->_errno("Send failed", errno, tcp->handler_ctx); return BufferedResult::CLOSED; case WRITE_BLOCKING: return BufferedResult::BLOCKING; case WRITE_DESTROYED: return BufferedResult::CLOSED; case WRITE_BROKEN: lb_tcp_close(tcp); tcp->handler->eof(tcp->handler_ctx); return BufferedResult::CLOSED; } assert(false); gcc_unreachable(); } static bool inbound_buffered_socket_closed(void *ctx) { LbTcpConnection *tcp = (LbTcpConnection *)ctx; lb_tcp_close(tcp); tcp->handler->eof(tcp->handler_ctx); return false; } static bool inbound_buffered_socket_write(void *ctx) { LbTcpConnection *tcp = (LbTcpConnection *)ctx; tcp->got_outbound_data = false; if (!tcp->outbound.Read(false)) return false; if (!tcp->got_outbound_data) tcp->inbound.UnscheduleWrite(); return true; } static bool inbound_buffered_socket_drained(void *ctx) { LbTcpConnection *tcp = (LbTcpConnection *)ctx; if (!tcp->outbound.IsValid()) { /* now that inbound's output buffers are drained, we can finally close the connection (postponed from outbound_buffered_socket_end()) */ lb_tcp_close(tcp); tcp->handler->eof(tcp->handler_ctx); return false; } return true; } static enum write_result inbound_buffered_socket_broken(void *ctx) { LbTcpConnection *tcp = (LbTcpConnection *)ctx; lb_tcp_close(tcp); tcp->handler->eof(tcp->handler_ctx); return WRITE_DESTROYED; } static void inbound_buffered_socket_error(GError *error, void *ctx) { LbTcpConnection *tcp = (LbTcpConnection *)ctx; lb_tcp_close(tcp); tcp->handler->gerror("Error", error, tcp->handler_ctx); } static constexpr BufferedSocketHandler inbound_buffered_socket_handler = { inbound_buffered_socket_data, nullptr, // TODO: inbound_buffered_socket_direct, inbound_buffered_socket_closed, nullptr, nullptr, inbound_buffered_socket_write, inbound_buffered_socket_drained, nullptr, inbound_buffered_socket_broken, inbound_buffered_socket_error, }; /* * outbound buffered_socket_handler * */ static BufferedResult outbound_buffered_socket_data(const void *buffer, size_t size, void *ctx) { LbTcpConnection *tcp = (LbTcpConnection *)ctx; tcp->got_outbound_data = true; ssize_t nbytes = tcp->inbound.Write(buffer, size); if (nbytes > 0) { tcp->outbound.Consumed(nbytes); return (size_t)nbytes == size ? BufferedResult::OK : BufferedResult::PARTIAL; } switch ((enum write_result)nbytes) { int save_errno; case WRITE_SOURCE_EOF: assert(false); gcc_unreachable(); case WRITE_ERRNO: save_errno = errno; lb_tcp_close(tcp); tcp->handler->_errno("Send failed", save_errno, tcp->handler_ctx); return BufferedResult::CLOSED; case WRITE_BLOCKING: return BufferedResult::BLOCKING; case WRITE_DESTROYED: return BufferedResult::CLOSED; case WRITE_BROKEN: lb_tcp_close(tcp); tcp->handler->eof(tcp->handler_ctx); return BufferedResult::CLOSED; } assert(false); gcc_unreachable(); } static bool outbound_buffered_socket_closed(void *ctx) { LbTcpConnection *tcp = (LbTcpConnection *)ctx; tcp->outbound.Close(); return true; } static void outbound_buffered_socket_end(void *ctx) { LbTcpConnection *tcp = (LbTcpConnection *)ctx; tcp->outbound.Destroy(); tcp->inbound.UnscheduleWrite(); if (tcp->inbound.IsDrained()) { /* all output buffers to "inbound" are drained; close the connection, because there's nothing left to do */ lb_tcp_close(tcp); tcp->handler->eof(tcp->handler_ctx); /* nothing will be done if the buffers are not yet drained; we're waiting for inbound_buffered_socket_drained() to be called */ } } static bool outbound_buffered_socket_write(void *ctx) { LbTcpConnection *tcp = (LbTcpConnection *)ctx; tcp->got_inbound_data = false; if (!tcp->inbound.Read(false)) return false; if (!tcp->got_inbound_data) tcp->outbound.UnscheduleWrite(); return true; } static enum write_result outbound_buffered_socket_broken(void *ctx) { LbTcpConnection *tcp = (LbTcpConnection *)ctx; lb_tcp_close(tcp); tcp->handler->eof(tcp->handler_ctx); return WRITE_DESTROYED; } static void outbound_buffered_socket_error(GError *error, void *ctx) { LbTcpConnection *tcp = (LbTcpConnection *)ctx; lb_tcp_close(tcp); tcp->handler->gerror("Error", error, tcp->handler_ctx); } static constexpr BufferedSocketHandler outbound_buffered_socket_handler = { outbound_buffered_socket_data, nullptr, // TODO: outbound_buffered_socket_direct, outbound_buffered_socket_closed, nullptr, outbound_buffered_socket_end, outbound_buffered_socket_write, nullptr, nullptr, outbound_buffered_socket_broken, outbound_buffered_socket_error, }; /* * ConnectSocketHandler * */ void LbTcpConnection::OnSocketConnectSuccess(SocketDescriptor &&fd) { cancel_connect = nullptr; outbound.Init(fd.Steal(), FdType::FD_TCP, nullptr, &write_timeout, outbound_buffered_socket_handler, this); /* TODO outbound.direct = pipe_stock != nullptr && (ISTREAM_TO_TCP & FdType::FD_PIPE) != 0 && (istream_direct_mask_to(inbound.base.base.fd_type) & FdType::FD_PIPE) != 0; */ if (inbound.Read(false)) outbound.Read(false); } void LbTcpConnection::OnSocketConnectTimeout() { DestroyInbound(); handler->error("Connect error", "Timeout", handler_ctx); } void LbTcpConnection::OnSocketConnectError(GError *error) { DestroyInbound(); handler->gerror("Connect error", error, handler_ctx); } /* * constructor * */ gcc_pure static unsigned lb_tcp_sticky(const AddressList &address_list, SocketAddress remote_address) { switch (address_list.sticky_mode) { case StickyMode::NONE: case StickyMode::FAILOVER: break; case StickyMode::SOURCE_IP: return socket_address_sticky(remote_address); case StickyMode::SESSION_MODULO: case StickyMode::COOKIE: case StickyMode::JVM_ROUTE: /* not implemented here */ break; } return 0; } void lb_tcp_new(struct pool *pool, EventLoop &event_loop, Stock *pipe_stock, SocketDescriptor &&fd, FdType fd_type, const SocketFilter *filter, void *filter_ctx, SocketAddress remote_address, bool transparent_source, const AddressList &address_list, Balancer &balancer, const LbTcpConnectionHandler *handler, void *ctx, LbTcpConnection **tcp_r) { auto *tcp = NewFromPool<LbTcpConnection>(*pool, event_loop); tcp->pool = pool; tcp->pipe_stock = pipe_stock; tcp->handler = handler; tcp->handler_ctx = ctx; tcp->inbound.Init(fd.Steal(), fd_type, nullptr, &write_timeout, filter, filter_ctx, inbound_buffered_socket_handler, tcp); /* TODO tcp->inbound.base.direct = pipe_stock != nullptr && (ISTREAM_TO_PIPE & fd_type) != 0 && (ISTREAM_TO_TCP & FdType::FD_PIPE) != 0; */ unsigned session_sticky = lb_tcp_sticky(address_list, remote_address); SocketAddress bind_address = SocketAddress::Null(); if (transparent_source) { bind_address = remote_address; /* reset the port to 0 to allow the kernel to choose one */ if (bind_address.GetFamily() == AF_INET) { struct sockaddr_in *s_in = (struct sockaddr_in *) p_memdup(pool, bind_address.GetAddress(), bind_address.GetSize()); s_in->sin_port = 0; bind_address = SocketAddress((const struct sockaddr *)s_in, bind_address.GetSize()); } else if (bind_address.GetFamily() == AF_INET6) { struct sockaddr_in6 *s_in = (struct sockaddr_in6 *) p_memdup(pool, bind_address.GetAddress(), bind_address.GetSize()); s_in->sin6_port = 0; bind_address = SocketAddress((const struct sockaddr *)s_in, bind_address.GetSize()); } } *tcp_r = tcp; client_balancer_connect(event_loop, *pool, balancer, transparent_source, bind_address, session_sticky, &address_list, 20, *tcp, tcp->cancel_connect); } void lb_tcp_close(LbTcpConnection *tcp) { if (tcp->inbound.IsValid()) tcp->DestroyInbound(); if (tcp->cancel_connect) tcp->cancel_connect.Cancel(); else if (tcp->outbound.IsValid()) tcp->DestroyOutbound(); } <|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. // chromeos::MediaDeviceNotifications implementation. #include "chrome/browser/system_monitor/media_device_notifications_chromeos.h" #include "base/file_path.h" #include "base/logging.h" #include "base/metrics/histogram.h" #include "base/stl_util.h" #include "base/string_number_conversions.h" #include "base/utf_string_conversions.h" #include "chrome/browser/system_monitor/media_device_notifications_utils.h" #include "chrome/browser/system_monitor/media_storage_util.h" #include "content/public/browser/browser_thread.h" namespace chromeos { namespace { bool GetDeviceInfo(const std::string& source_path, std::string* unique_id, string16* device_label) { // Get the media device uuid and label if exists. const disks::DiskMountManager::Disk* disk = disks::DiskMountManager::GetInstance()->FindDiskBySourcePath(source_path); if (!disk) return false; *unique_id = disk->fs_uuid(); // TODO(kmadhusu): If device label is empty, extract vendor and model details // and use them as device_label. *device_label = UTF8ToUTF16(disk->device_label().empty() ? FilePath(source_path).BaseName().value() : disk->device_label()); return true; } } // namespace using content::BrowserThread; MediaDeviceNotifications::MediaDeviceNotifications() { DCHECK(disks::DiskMountManager::GetInstance()); disks::DiskMountManager::GetInstance()->AddObserver(this); CheckExistingMountPointsOnUIThread(); } MediaDeviceNotifications::~MediaDeviceNotifications() { disks::DiskMountManager* manager = disks::DiskMountManager::GetInstance(); if (manager) { manager->RemoveObserver(this); } } void MediaDeviceNotifications::CheckExistingMountPointsOnUIThread() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); const disks::DiskMountManager::MountPointMap& mount_point_map = disks::DiskMountManager::GetInstance()->mount_points(); for (disks::DiskMountManager::MountPointMap::const_iterator it = mount_point_map.begin(); it != mount_point_map.end(); ++it) { BrowserThread::PostTask( BrowserThread::FILE, FROM_HERE, base::Bind(&MediaDeviceNotifications::CheckMountedPathOnFileThread, this, it->second)); } } void MediaDeviceNotifications::DiskChanged( disks::DiskMountManagerEventType event, const disks::DiskMountManager::Disk* disk) { } void MediaDeviceNotifications::DeviceChanged( disks::DiskMountManagerEventType event, const std::string& device_path) { } void MediaDeviceNotifications::MountCompleted( disks::DiskMountManager::MountEvent event_type, MountError error_code, const disks::DiskMountManager::MountPointInfo& mount_info) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); // Ignore mount points that are not devices. if (mount_info.mount_type != MOUNT_TYPE_DEVICE) return; // Ignore errors. if (error_code != MOUNT_ERROR_NONE) return; if (mount_info.mount_condition != disks::MOUNT_CONDITION_NONE) return; switch (event_type) { case disks::DiskMountManager::MOUNTING: { if (ContainsKey(mount_map_, mount_info.mount_path)) { NOTREACHED(); return; } BrowserThread::PostTask( BrowserThread::FILE, FROM_HERE, base::Bind(&MediaDeviceNotifications::CheckMountedPathOnFileThread, this, mount_info)); break; } case disks::DiskMountManager::UNMOUNTING: { MountMap::iterator it = mount_map_.find(mount_info.mount_path); if (it == mount_map_.end()) return; base::SystemMonitor::Get()->ProcessRemovableStorageDetached(it->second); mount_map_.erase(it); break; } } } void MediaDeviceNotifications::CheckMountedPathOnFileThread( const disks::DiskMountManager::MountPointInfo& mount_info) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); if (!chrome::IsMediaDevice(mount_info.mount_path)) return; BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&MediaDeviceNotifications::AddMountedPathOnUIThread, this, mount_info)); } void MediaDeviceNotifications::AddMountedPathOnUIThread( const disks::DiskMountManager::MountPointInfo& mount_info) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (ContainsKey(mount_map_, mount_info.mount_path)) { NOTREACHED(); return; } // Get the media device uuid and label if exists. std::string unique_id; string16 device_label; if (!GetDeviceInfo(mount_info.source_path, &unique_id, &device_label)) return; // Keep track of device uuid, to see how often we receive empty uuid values. UMA_HISTOGRAM_BOOLEAN("MediaDeviceNotification.device_uuid_available", !unique_id.empty()); if (unique_id.empty()) return; std::string device_id = chrome::MediaStorageUtil::MakeDeviceId( chrome::MediaStorageUtil::REMOVABLE_MASS_STORAGE_WITH_DCIM, unique_id); mount_map_.insert(std::make_pair(mount_info.mount_path, device_id)); base::SystemMonitor::Get()->ProcessRemovableStorageAttached( device_id, device_label, mount_info.mount_path); } } // namespace chrome <commit_msg>Fix MediaDeviceNotification histogram name.<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. // chromeos::MediaDeviceNotifications implementation. #include "chrome/browser/system_monitor/media_device_notifications_chromeos.h" #include "base/file_path.h" #include "base/logging.h" #include "base/metrics/histogram.h" #include "base/stl_util.h" #include "base/string_number_conversions.h" #include "base/utf_string_conversions.h" #include "chrome/browser/system_monitor/media_device_notifications_utils.h" #include "chrome/browser/system_monitor/media_storage_util.h" #include "content/public/browser/browser_thread.h" namespace chromeos { namespace { bool GetDeviceInfo(const std::string& source_path, std::string* unique_id, string16* device_label) { // Get the media device uuid and label if exists. const disks::DiskMountManager::Disk* disk = disks::DiskMountManager::GetInstance()->FindDiskBySourcePath(source_path); if (!disk) return false; *unique_id = disk->fs_uuid(); // TODO(kmadhusu): If device label is empty, extract vendor and model details // and use them as device_label. *device_label = UTF8ToUTF16(disk->device_label().empty() ? FilePath(source_path).BaseName().value() : disk->device_label()); return true; } } // namespace using content::BrowserThread; MediaDeviceNotifications::MediaDeviceNotifications() { DCHECK(disks::DiskMountManager::GetInstance()); disks::DiskMountManager::GetInstance()->AddObserver(this); CheckExistingMountPointsOnUIThread(); } MediaDeviceNotifications::~MediaDeviceNotifications() { disks::DiskMountManager* manager = disks::DiskMountManager::GetInstance(); if (manager) { manager->RemoveObserver(this); } } void MediaDeviceNotifications::CheckExistingMountPointsOnUIThread() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); const disks::DiskMountManager::MountPointMap& mount_point_map = disks::DiskMountManager::GetInstance()->mount_points(); for (disks::DiskMountManager::MountPointMap::const_iterator it = mount_point_map.begin(); it != mount_point_map.end(); ++it) { BrowserThread::PostTask( BrowserThread::FILE, FROM_HERE, base::Bind(&MediaDeviceNotifications::CheckMountedPathOnFileThread, this, it->second)); } } void MediaDeviceNotifications::DiskChanged( disks::DiskMountManagerEventType event, const disks::DiskMountManager::Disk* disk) { } void MediaDeviceNotifications::DeviceChanged( disks::DiskMountManagerEventType event, const std::string& device_path) { } void MediaDeviceNotifications::MountCompleted( disks::DiskMountManager::MountEvent event_type, MountError error_code, const disks::DiskMountManager::MountPointInfo& mount_info) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); // Ignore mount points that are not devices. if (mount_info.mount_type != MOUNT_TYPE_DEVICE) return; // Ignore errors. if (error_code != MOUNT_ERROR_NONE) return; if (mount_info.mount_condition != disks::MOUNT_CONDITION_NONE) return; switch (event_type) { case disks::DiskMountManager::MOUNTING: { if (ContainsKey(mount_map_, mount_info.mount_path)) { NOTREACHED(); return; } BrowserThread::PostTask( BrowserThread::FILE, FROM_HERE, base::Bind(&MediaDeviceNotifications::CheckMountedPathOnFileThread, this, mount_info)); break; } case disks::DiskMountManager::UNMOUNTING: { MountMap::iterator it = mount_map_.find(mount_info.mount_path); if (it == mount_map_.end()) return; base::SystemMonitor::Get()->ProcessRemovableStorageDetached(it->second); mount_map_.erase(it); break; } } } void MediaDeviceNotifications::CheckMountedPathOnFileThread( const disks::DiskMountManager::MountPointInfo& mount_info) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); if (!chrome::IsMediaDevice(mount_info.mount_path)) return; BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&MediaDeviceNotifications::AddMountedPathOnUIThread, this, mount_info)); } void MediaDeviceNotifications::AddMountedPathOnUIThread( const disks::DiskMountManager::MountPointInfo& mount_info) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (ContainsKey(mount_map_, mount_info.mount_path)) { NOTREACHED(); return; } // Get the media device uuid and label if exists. std::string unique_id; string16 device_label; if (!GetDeviceInfo(mount_info.source_path, &unique_id, &device_label)) return; // Keep track of device uuid, to see how often we receive empty uuid values. UMA_HISTOGRAM_BOOLEAN("MediaDeviceNotification.DeviceUUIDAvailable", !unique_id.empty()); if (unique_id.empty()) return; std::string device_id = chrome::MediaStorageUtil::MakeDeviceId( chrome::MediaStorageUtil::REMOVABLE_MASS_STORAGE_WITH_DCIM, unique_id); mount_map_.insert(std::make_pair(mount_info.mount_path, device_id)); base::SystemMonitor::Get()->ProcessRemovableStorageAttached( device_id, device_label, mount_info.mount_path); } } // namespace chrome <|endoftext|>
<commit_before>/* * Copyright (C) 2008-2013 The Communi Project * * 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. */ #include "messagestackview.h" #include "settingsmodel.h" #include "application.h" #include "zncmanager.h" #include "completer.h" #include "session.h" #include <ircbuffer.h> #include <irccommand.h> #include <ircbuffermodel.h> class BufferModel : public IrcBufferModel { public: BufferModel(QObject* parent = 0) : IrcBufferModel(parent) { } protected: void destroyBuffer(IrcBuffer* buffer) { Q_UNUSED(buffer); } }; MessageStackView::MessageStackView(IrcSession* session, QWidget* parent) : QStackedWidget(parent) { d.session = session; d.bufferModel = new BufferModel(session); connect(d.bufferModel, SIGNAL(bufferAdded(IrcBuffer*)), this, SLOT(setBuffer(IrcBuffer*))); connect(d.bufferModel, SIGNAL(messageIgnored(IrcMessage*)), &d.handler, SLOT(handleMessage(IrcMessage*))); connect(d.bufferModel, SIGNAL(channelsChanged(QStringList)), &d.parser, SLOT(setChannels(QStringList))); session->installMessageFilter(&d.handler); session->installMessageFilter(qobject_cast<Session*>(session)); // TODO d.handler.znc()->setModel(d.bufferModel); connect(this, SIGNAL(currentChanged(int)), this, SLOT(activateView(int))); connect(&d.handler, SIGNAL(viewToBeAdded(QString)), this, SLOT(addView(QString))); connect(&d.handler, SIGNAL(viewToBeRemoved(QString)), this, SLOT(removeView(QString))); connect(&d.handler, SIGNAL(viewToBeRenamed(QString, QString)), this, SLOT(renameView(QString, QString))); MessageView* view = addView(session->host()); d.handler.setDefaultView(view); d.handler.setCurrentView(view); setCurrentWidget(view); applySettings(); connect(Application::settings(), SIGNAL(changed()), this, SLOT(applySettings())); } IrcSession* MessageStackView::session() const { return d.session; } CommandParser* MessageStackView::parser() const { return &const_cast<MessageStackView*>(this)->d.parser; } QStringListModel* MessageStackView::commandModel() const { return &const_cast<MessageStackView*>(this)->d.commandModel; } MessageView* MessageStackView::currentView() const { return qobject_cast<MessageView*>(currentWidget()); } MessageView* MessageStackView::viewAt(int index) const { return qobject_cast<MessageView*>(widget(index)); } MessageView* MessageStackView::addView(const QString& receiver) { MessageView* view = d.views.value(receiver.toLower()); bool channel = !receiver.isEmpty() && IrcSessionInfo(d.session).channelTypes().contains(receiver.at(0)); if (!view) { ViewInfo::Type type = ViewInfo::Server; if (!d.views.isEmpty()) type = channel ? ViewInfo::Channel : ViewInfo::Query; view = createView(type, receiver); } if (channel && !view->isActive()) openView(receiver); return view; } void MessageStackView::restoreView(const ViewInfo& view) { createView(static_cast<ViewInfo::Type>(view.type), view.name); } MessageView* MessageStackView::createView(ViewInfo::Type type, const QString& receiver) { MessageView* view = new MessageView(type, static_cast<Session*>(d.session), this); // TODO // TODO: if (IrcSessionInfo(session()).isValid()) view->completer()->setChannelPrefixes(IrcSessionInfo(session()).channelTypes().join("")); view->completer()->setChannelModel(&d.viewModel); view->setReceiver(receiver); connect(view, SIGNAL(queried(QString)), this, SLOT(addView(QString))); connect(view, SIGNAL(queried(QString)), this, SLOT(openView(QString))); connect(view, SIGNAL(messaged(QString,QString)), this, SLOT(sendMessage(QString,QString))); d.handler.addView(receiver, view); d.views.insert(receiver.toLower(), view); addWidget(view); d.viewModel.setStringList(d.viewModel.stringList() << receiver); emit viewAdded(view); return view; } void MessageStackView::openView(const QString& receiver) { MessageView* view = d.views.value(receiver.toLower()); if (view) setCurrentWidget(view); } void MessageStackView::removeView(const QString& receiver) { MessageView* view = d.views.take(receiver.toLower()); if (view) { view->deleteLater(); QStringList views = d.viewModel.stringList(); if (views.removeOne(receiver)) d.viewModel.setStringList(views); emit viewRemoved(view); d.handler.removeView(view->receiver()); } } void MessageStackView::closeView(int index) { MessageView* view = viewAt(index); if (view) { if (view->isActive()) { if (indexOf(view) == 0) static_cast<Session*>(session())->quit(); // TODO else if (view->viewType() == ViewInfo::Channel) d.session->sendCommand(IrcCommand::createPart(view->receiver())); } d.handler.removeView(view->receiver()); } } void MessageStackView::renameView(const QString& from, const QString& to) { if (!d.views.contains(to.toLower())) { MessageView* view = d.views.take(from.toLower()); if (view) { view->setReceiver(to); d.views.insert(to.toLower(), view); emit viewRenamed(view); } } else if (currentView() == d.views.value(from.toLower())) { setCurrentWidget(d.views.value(to.toLower())); } } void MessageStackView::sendMessage(const QString& receiver, const QString& message) { MessageView* view = addView(receiver); if (view) { setCurrentWidget(view); view->sendMessage(message); } } void MessageStackView::applySettings() { SettingsModel* settings = Application::settings(); d.handler.znc()->setTimeStampFormat(settings->value("formatting.timeStamp").toString()); QMap<QString,QString> aliases; QVariantMap values = settings->values("aliases.*"); QMapIterator<QString,QVariant> it(values); while (it.hasNext()) { it.next(); aliases[it.key().mid(8).toUpper()] = it.value().toString(); } d.parser.setAliases(aliases); QStringList commands; foreach (const QString& command, d.parser.availableCommands()) commands += d.parser.prefix() + command; d.commandModel.setStringList(commands); } void MessageStackView::activateView(int index) { MessageView* view = viewAt(index); if (view && isVisible()) { d.handler.setCurrentView(view); d.parser.setCurrentTarget(view->receiver()); view->setFocus(); emit viewActivated(view); } } void MessageStackView::setBuffer(IrcBuffer* buffer) { MessageView* view = addView(buffer->title().toLower()); if (view) view->setBuffer(buffer); } <commit_msg>Fix MessageStackView::setBuffer() not to force lower case title<commit_after>/* * Copyright (C) 2008-2013 The Communi Project * * 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. */ #include "messagestackview.h" #include "settingsmodel.h" #include "application.h" #include "zncmanager.h" #include "completer.h" #include "session.h" #include <ircbuffer.h> #include <irccommand.h> #include <ircbuffermodel.h> class BufferModel : public IrcBufferModel { public: BufferModel(QObject* parent = 0) : IrcBufferModel(parent) { } protected: void destroyBuffer(IrcBuffer* buffer) { Q_UNUSED(buffer); } }; MessageStackView::MessageStackView(IrcSession* session, QWidget* parent) : QStackedWidget(parent) { d.session = session; d.bufferModel = new BufferModel(session); connect(d.bufferModel, SIGNAL(bufferAdded(IrcBuffer*)), this, SLOT(setBuffer(IrcBuffer*))); connect(d.bufferModel, SIGNAL(messageIgnored(IrcMessage*)), &d.handler, SLOT(handleMessage(IrcMessage*))); connect(d.bufferModel, SIGNAL(channelsChanged(QStringList)), &d.parser, SLOT(setChannels(QStringList))); session->installMessageFilter(&d.handler); session->installMessageFilter(qobject_cast<Session*>(session)); // TODO d.handler.znc()->setModel(d.bufferModel); connect(this, SIGNAL(currentChanged(int)), this, SLOT(activateView(int))); connect(&d.handler, SIGNAL(viewToBeAdded(QString)), this, SLOT(addView(QString))); connect(&d.handler, SIGNAL(viewToBeRemoved(QString)), this, SLOT(removeView(QString))); connect(&d.handler, SIGNAL(viewToBeRenamed(QString, QString)), this, SLOT(renameView(QString, QString))); MessageView* view = addView(session->host()); d.handler.setDefaultView(view); d.handler.setCurrentView(view); setCurrentWidget(view); applySettings(); connect(Application::settings(), SIGNAL(changed()), this, SLOT(applySettings())); } IrcSession* MessageStackView::session() const { return d.session; } CommandParser* MessageStackView::parser() const { return &const_cast<MessageStackView*>(this)->d.parser; } QStringListModel* MessageStackView::commandModel() const { return &const_cast<MessageStackView*>(this)->d.commandModel; } MessageView* MessageStackView::currentView() const { return qobject_cast<MessageView*>(currentWidget()); } MessageView* MessageStackView::viewAt(int index) const { return qobject_cast<MessageView*>(widget(index)); } MessageView* MessageStackView::addView(const QString& receiver) { MessageView* view = d.views.value(receiver.toLower()); bool channel = !receiver.isEmpty() && IrcSessionInfo(d.session).channelTypes().contains(receiver.at(0)); if (!view) { ViewInfo::Type type = ViewInfo::Server; if (!d.views.isEmpty()) type = channel ? ViewInfo::Channel : ViewInfo::Query; view = createView(type, receiver); } if (channel && !view->isActive()) openView(receiver); return view; } void MessageStackView::restoreView(const ViewInfo& view) { createView(static_cast<ViewInfo::Type>(view.type), view.name); } MessageView* MessageStackView::createView(ViewInfo::Type type, const QString& receiver) { MessageView* view = new MessageView(type, static_cast<Session*>(d.session), this); // TODO // TODO: if (IrcSessionInfo(session()).isValid()) view->completer()->setChannelPrefixes(IrcSessionInfo(session()).channelTypes().join("")); view->completer()->setChannelModel(&d.viewModel); view->setReceiver(receiver); connect(view, SIGNAL(queried(QString)), this, SLOT(addView(QString))); connect(view, SIGNAL(queried(QString)), this, SLOT(openView(QString))); connect(view, SIGNAL(messaged(QString,QString)), this, SLOT(sendMessage(QString,QString))); d.handler.addView(receiver, view); d.views.insert(receiver.toLower(), view); addWidget(view); d.viewModel.setStringList(d.viewModel.stringList() << receiver); emit viewAdded(view); return view; } void MessageStackView::openView(const QString& receiver) { MessageView* view = d.views.value(receiver.toLower()); if (view) setCurrentWidget(view); } void MessageStackView::removeView(const QString& receiver) { MessageView* view = d.views.take(receiver.toLower()); if (view) { view->deleteLater(); QStringList views = d.viewModel.stringList(); if (views.removeOne(receiver)) d.viewModel.setStringList(views); emit viewRemoved(view); d.handler.removeView(view->receiver()); } } void MessageStackView::closeView(int index) { MessageView* view = viewAt(index); if (view) { if (view->isActive()) { if (indexOf(view) == 0) static_cast<Session*>(session())->quit(); // TODO else if (view->viewType() == ViewInfo::Channel) d.session->sendCommand(IrcCommand::createPart(view->receiver())); } d.handler.removeView(view->receiver()); } } void MessageStackView::renameView(const QString& from, const QString& to) { if (!d.views.contains(to.toLower())) { MessageView* view = d.views.take(from.toLower()); if (view) { view->setReceiver(to); d.views.insert(to.toLower(), view); emit viewRenamed(view); } } else if (currentView() == d.views.value(from.toLower())) { setCurrentWidget(d.views.value(to.toLower())); } } void MessageStackView::sendMessage(const QString& receiver, const QString& message) { MessageView* view = addView(receiver); if (view) { setCurrentWidget(view); view->sendMessage(message); } } void MessageStackView::applySettings() { SettingsModel* settings = Application::settings(); d.handler.znc()->setTimeStampFormat(settings->value("formatting.timeStamp").toString()); QMap<QString,QString> aliases; QVariantMap values = settings->values("aliases.*"); QMapIterator<QString,QVariant> it(values); while (it.hasNext()) { it.next(); aliases[it.key().mid(8).toUpper()] = it.value().toString(); } d.parser.setAliases(aliases); QStringList commands; foreach (const QString& command, d.parser.availableCommands()) commands += d.parser.prefix() + command; d.commandModel.setStringList(commands); } void MessageStackView::activateView(int index) { MessageView* view = viewAt(index); if (view && isVisible()) { d.handler.setCurrentView(view); d.parser.setCurrentTarget(view->receiver()); view->setFocus(); emit viewActivated(view); } } void MessageStackView::setBuffer(IrcBuffer* buffer) { MessageView* view = addView(buffer->title()); if (view) view->setBuffer(buffer); } <|endoftext|>
<commit_before>#include <QMainWindow> #include <QFileDialog> #include <QString> #include <QBoxLayout> #include <QLabel> #include <QMessageBox> #include "mainwindow.h" #include "parser/htmlreader.h" #include "painter/paintarea.h" #define WINDOW_HEIGHT 480 MainWindow::MainWindow() { reader = new HTMLReader; webpage = new Document; //Draw main window for WebWhirr. setMinimumHeight(WINDOW_HEIGHT); setMaximumHeight(WINDOW_HEIGHT); positionSet = false; QLabel *addressBarLabel = new QLabel(tr("Current Document:")); addressBar = new QLineEdit; addressBar->setReadOnly(true); QHBoxLayout *addressBarLayout = new QHBoxLayout; addressBarLayout->addWidget(addressBarLabel); addressBarLayout->addWidget(addressBar); paintArea = new PaintArea; scrollArea = new QScrollArea(this); documentDisplay = new QLabel(scrollArea); documentDisplay->setAlignment(Qt::AlignTop | Qt::AlignLeft); scrollArea->setWidget(documentDisplay); scrollArea->setWidgetResizable(true); QVBoxLayout *layout = new QVBoxLayout; layout->addLayout(addressBarLayout); layout->addWidget(scrollArea); centralLayout = new QWidget; centralLayout->setLayout(layout); setCentralWidget(centralLayout); createActions(); createMenus(); setWindowTitle("WebWhirr 0.1.0 Beta"); } void MainWindow::createActions() { openAct = new QAction(tr("&Open"), this); openAct->setShortcut(QKeySequence::Open); connect(openAct, SIGNAL(triggered()), this, SLOT(setFilepath())); } void MainWindow::createMenus() { fileMenu = menuBar()->addMenu(tr("&File")); fileMenu->addAction(openAct); } bool MainWindow::setFilepath(std::string filepath) { if (!checkFilepath(filepath)) { return false; } else { //Construct a Document (contains node tree) from parsing document //passed from command line. webpage = reader->prepareDocument(filepath); addressBar->setText(QString::fromStdString(filepath)); paintArea->setDocument(webpage); } return true; } bool MainWindow::setFilepath() { //QString::toStdString() doesn't convert the filepath properly std::string filepath = QFileDialog::getOpenFileName(this, tr("Open HTML Document")).toUtf8().constData(); if (filepath.empty()) { return false; } if (!checkFilepath(filepath)) { QMessageBox invalidTypeErrorBox; invalidTypeErrorBox.setText("Error: Document type is invalid or not supported."); invalidTypeErrorBox.exec(); return false; } else { //Delete any old nodes to avoid memory leaks. if (webpage->getFirstNode() != NULL) { webpage->clearTree(); } addressBar->setText(QString::fromStdString(filepath)); //Construct a Document (contains node tree) from parsing document //selected in "Open HTML Document" dialog. webpage = reader->prepareDocument(filepath); paintArea->setDocument(webpage); return repaintDocument(); } } //This entire function is a mess. I will return and work //on it more after the 0.1.0 release. bool MainWindow::repaintDocument() { //Paint the current document in paintArea by creating a QPixmap //and assigning this to the QLabel documentDisplay. Dimensions //are also set to avoid annoying issues with the scrollbars. QPixmap paintedDocument; //grab() has to be called twice. Otherwise, the pixmap is the wrong //size when the document is first displayed and the document has to //be opened twice in order to scroll through it properly. paintedDocument = paintArea->grab(); paintedDocument.scaled(paintArea->size(), Qt::IgnoreAspectRatio); paintedDocument = paintArea->grab(); documentDisplay->setMinimumWidth(paintedDocument.width()); documentDisplay->setMaximumWidth(paintedDocument.width()); documentDisplay->setMaximumHeight(paintArea->height()); documentDisplay->setPixmap(paintedDocument); scrollArea->setMinimumWidth(documentDisplay->width() + 20); this->setMinimumWidth(scrollArea->width() + 20); this->setMaximumWidth(scrollArea->width() + 20); return true; } bool MainWindow::checkFilepath(std::string filepath) { //This is a fix for the crash on opening a non-HTML document. //It will have to do until I write a check into the encoding, //because for some reason a similar check in the document text //itself always returns true. if (filepath.find(".html") != std::string::npos || filepath.find(".htm") != std::string::npos) { return true; } return false; } Document* MainWindow::getWebpage() { return webpage; } <commit_msg>Update name in title bar to WebWhirr 0.1.0 instead of WebWhirr 0.1.0 Beta.<commit_after>#include <QMainWindow> #include <QFileDialog> #include <QString> #include <QBoxLayout> #include <QLabel> #include <QMessageBox> #include "mainwindow.h" #include "parser/htmlreader.h" #include "painter/paintarea.h" #define WINDOW_HEIGHT 480 MainWindow::MainWindow() { reader = new HTMLReader; webpage = new Document; //Draw main window for WebWhirr. setMinimumHeight(WINDOW_HEIGHT); setMaximumHeight(WINDOW_HEIGHT); positionSet = false; QLabel *addressBarLabel = new QLabel(tr("Current Document:")); addressBar = new QLineEdit; addressBar->setReadOnly(true); QHBoxLayout *addressBarLayout = new QHBoxLayout; addressBarLayout->addWidget(addressBarLabel); addressBarLayout->addWidget(addressBar); paintArea = new PaintArea; scrollArea = new QScrollArea(this); documentDisplay = new QLabel(scrollArea); documentDisplay->setAlignment(Qt::AlignTop | Qt::AlignLeft); scrollArea->setWidget(documentDisplay); scrollArea->setWidgetResizable(true); QVBoxLayout *layout = new QVBoxLayout; layout->addLayout(addressBarLayout); layout->addWidget(scrollArea); centralLayout = new QWidget; centralLayout->setLayout(layout); setCentralWidget(centralLayout); createActions(); createMenus(); setWindowTitle("WebWhirr 0.1.0"); } void MainWindow::createActions() { openAct = new QAction(tr("&Open"), this); openAct->setShortcut(QKeySequence::Open); connect(openAct, SIGNAL(triggered()), this, SLOT(setFilepath())); } void MainWindow::createMenus() { fileMenu = menuBar()->addMenu(tr("&File")); fileMenu->addAction(openAct); } bool MainWindow::setFilepath(std::string filepath) { if (!checkFilepath(filepath)) { return false; } else { //Construct a Document (contains node tree) from parsing document //passed from command line. webpage = reader->prepareDocument(filepath); addressBar->setText(QString::fromStdString(filepath)); paintArea->setDocument(webpage); } return true; } bool MainWindow::setFilepath() { //QString::toStdString() doesn't convert the filepath properly std::string filepath = QFileDialog::getOpenFileName(this, tr("Open HTML Document")).toUtf8().constData(); if (filepath.empty()) { return false; } if (!checkFilepath(filepath)) { QMessageBox invalidTypeErrorBox; invalidTypeErrorBox.setText("Error: Document type is invalid or not supported."); invalidTypeErrorBox.exec(); return false; } else { //Delete any old nodes to avoid memory leaks. if (webpage->getFirstNode() != NULL) { webpage->clearTree(); } addressBar->setText(QString::fromStdString(filepath)); //Construct a Document (contains node tree) from parsing document //selected in "Open HTML Document" dialog. webpage = reader->prepareDocument(filepath); paintArea->setDocument(webpage); return repaintDocument(); } } //This entire function is a mess. I will return and work //on it more after the 0.1.0 release. bool MainWindow::repaintDocument() { //Paint the current document in paintArea by creating a QPixmap //and assigning this to the QLabel documentDisplay. Dimensions //are also set to avoid annoying issues with the scrollbars. QPixmap paintedDocument; //grab() has to be called twice. Otherwise, the pixmap is the wrong //size when the document is first displayed and the document has to //be opened twice in order to scroll through it properly. paintedDocument = paintArea->grab(); paintedDocument.scaled(paintArea->size(), Qt::IgnoreAspectRatio); paintedDocument = paintArea->grab(); documentDisplay->setMinimumWidth(paintedDocument.width()); documentDisplay->setMaximumWidth(paintedDocument.width()); documentDisplay->setMaximumHeight(paintArea->height()); documentDisplay->setPixmap(paintedDocument); scrollArea->setMinimumWidth(documentDisplay->width() + 20); this->setMinimumWidth(scrollArea->width() + 20); this->setMaximumWidth(scrollArea->width() + 20); return true; } bool MainWindow::checkFilepath(std::string filepath) { //This is a fix for the crash on opening a non-HTML document. //It will have to do until I write a check into the encoding, //because for some reason a similar check in the document text //itself always returns true. if (filepath.find(".html") != std::string::npos || filepath.find(".htm") != std::string::npos) { return true; } return false; } Document* MainWindow::getWebpage() { return webpage; } <|endoftext|>
<commit_before>#include <io/network/tcpSocket.h> #include <logging.h> #ifdef _WIN32 #include <winsock2.h> #include <ws2tcpip.h> static constexpr int flags = 0; static inline int send(SOCKET s, const void* msg, size_t len, int flags) { return send(s, static_cast<const char*>(msg), static_cast<int>(len), flags); } static inline int recv(SOCKET s, void* buf, size_t len, int flags) { return recv(s, static_cast<char*>(buf), static_cast<int>(len), flags); } #else #include <sys/types.h> #include <sys/socket.h> #include <unistd.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <arpa/inet.h> #include <string.h> static constexpr int flags = MSG_NOSIGNAL; static constexpr intptr_t INVALID_SOCKET = -1; #endif extern "C" { struct X509; struct X509_STORE; struct SSL_CTX; struct SSL_METHOD; struct SSL; static X509_STORE* (*X509_STORE_new)(); static X509* (*d2i_X509)(X509**, const unsigned char **, long); static int (*X509_STORE_add_cert)(X509_STORE*, X509*); static void (*X509_free)(X509*); static SSL_CTX* (*SSL_CTX_new)(const SSL_METHOD*); static const SSL_METHOD* (*TLSv1_2_client_method)(); static long (*SSL_CTX_set_options)(SSL_CTX*, long); static int (*SSL_CTX_set_default_verify_paths)(SSL_CTX*); static void (*SSL_CTX_set_cert_store)(SSL_CTX*, X509_STORE*); static SSL* (*SSL_new)(SSL_CTX*); static int (*SSL_set_fd)(SSL *ssl, int fd); static int (*SSL_connect)(SSL *ssl); static long (*SSL_get_verify_result)(const SSL *ssl); static int (*SSL_read)(SSL *ssl, void *buf, int num); static int (*SSL_write)(SSL *ssl, const void *buf, int num); static void (*SSL_free)(SSL *ssl); static SSL_CTX* ssl_context; } # define SSL_OP_NO_SSLv2 0x01000000L # define SSL_OP_NO_SSLv3 0x02000000L # define SSL_OP_NO_TLSv1 0x04000000L # define SSL_OP_NO_TLSv1_2 0x08000000L # define SSL_OP_NO_TLSv1_1 0x10000000L #ifndef __ANDROID__ #include "dynamicLibrary.h" static std::unique_ptr<DynamicLibrary> libcrypto; static std::unique_ptr<DynamicLibrary> libssl; #endif static void initializeLibSSL() { static bool initialized = false; if (initialized) return; initialized = true; #ifndef __ANDROID__ #ifdef _WIN32 libcrypto = DynamicLibrary::open("libcrypto-1_1.dll"); libssl = DynamicLibrary::open("libssl-1_1.dll"); #else libcrypto = DynamicLibrary::open("libcrypto.so.1.1"); libssl = DynamicLibrary::open("libssl.so.1.1"); #endif if (!libcrypto || !libssl) return; X509_STORE_new = libcrypto->getFunction<X509_STORE*(*)()>("X509_STORE_new"); d2i_X509 = libcrypto->getFunction<X509* (*)(X509**, const unsigned char **, long)>("d2i_X509"); X509_STORE_add_cert = libcrypto->getFunction<int (*)(X509_STORE*, X509*)>("X509_STORE_add_cert"); X509_free = libcrypto->getFunction<void (*)(X509*)>("X509_free"); SSL_CTX_new = libssl->getFunction<SSL_CTX*(*)(const SSL_METHOD*)>("SSL_CTX_new"); TLSv1_2_client_method = libssl->getFunction<const SSL_METHOD* (*)()>("TLSv1_2_client_method"); SSL_CTX_set_options = libssl->getFunction<long (*)(SSL_CTX*, long)>("SSL_CTX_set_options"); SSL_CTX_set_default_verify_paths = libssl->getFunction<int (*)(SSL_CTX*)>("SSL_CTX_set_default_verify_paths"); SSL_CTX_set_cert_store = libssl->getFunction<void (*)(SSL_CTX*, X509_STORE*)>("SSL_CTX_set_cert_store"); SSL_new = libssl->getFunction<SSL* (*)(SSL_CTX*)>("SSL_new"); SSL_set_fd = libssl->getFunction<int (*)(SSL *ssl, int fd)>("SSL_set_fd"); SSL_connect = libssl->getFunction<int (*)(SSL *ssl)>("SSL_connect"); SSL_get_verify_result = libssl->getFunction<long (*)(const SSL *ssl)>("SSL_get_verify_result"); SSL_read = libssl->getFunction<int (*)(SSL *ssl, void *buf, int num)>("SSL_read"); SSL_write = libssl->getFunction<int (*)(SSL *ssl, const void *buf, int num)>("SSL_write"); SSL_free = libssl->getFunction<void (*)(SSL *ssl)>("SSL_free"); #ifdef _WIN32 HCERTSTORE hStore; PCCERT_CONTEXT pContext = NULL; X509 *x509; X509_STORE *store = X509_STORE_new(); hStore = CertOpenSystemStore(0, "ROOT"); while((pContext = CertEnumCertificatesInStore(hStore, pContext)) != nullptr) { const unsigned char* c = pContext->pbCertEncoded; x509 = d2i_X509(nullptr, &c, pContext->cbCertEncoded); if (x509) { X509_STORE_add_cert(store, x509); X509_free(x509); } } CertFreeCertificateContext(pContext); CertCloseStore(hStore, 0); #endif ssl_context = SSL_CTX_new(TLSv1_2_client_method()); SSL_CTX_set_options(ssl_context, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1); #ifdef _WIN32 SSL_CTX_set_cert_store(ssl_context, store); #else SSL_CTX_set_default_verify_paths(ssl_context); #endif #endif } namespace sp { namespace io { namespace network { TcpSocket::TcpSocket() : ssl_handle(nullptr) { } TcpSocket::~TcpSocket() { close(); } bool TcpSocket::connect(const Address& host, int port) { if (handle != INVALID_SOCKET) close(); for(const auto& addr_info : host.addr_info) { handle = ::socket(addr_info.family, SOCK_STREAM, 0); if (handle == INVALID_SOCKET) return false; setBlocking(blocking); if (addr_info.family == AF_INET && sizeof(struct sockaddr_in) == addr_info.addr.size()) { struct sockaddr_in server_addr; memset(&server_addr, 0, sizeof(server_addr)); memcpy(&server_addr, addr_info.addr.data(), addr_info.addr.size()); server_addr.sin_port = htons(port); if (::connect(handle, reinterpret_cast<const sockaddr*>(&server_addr), sizeof(server_addr)) == 0) return true; if (isLastErrorNonBlocking()) { connecting = true; return true; } } if (addr_info.family == AF_INET6 && sizeof(struct sockaddr_in6) == addr_info.addr.size()) { struct sockaddr_in6 server_addr; memset(&server_addr, 0, sizeof(server_addr)); memcpy(&server_addr, addr_info.addr.data(), addr_info.addr.size()); server_addr.sin6_port = htons(port); if (::connect(handle, reinterpret_cast<const sockaddr*>(&server_addr), sizeof(server_addr)) == 0) return true; if (isLastErrorNonBlocking()) { connecting = true; return true; } } close(); } return false; } bool TcpSocket::connectSSL(const Address& host, int port) { if (!connect(host, port)) return false; initializeLibSSL(); if (!SSL_new) { LOG(Warning, "Failed to connect SSL socket due to missing libssl/libcrypto v1.1"); close(); return false; } ssl_handle = SSL_new(ssl_context); SSL_set_fd(static_cast<SSL*>(ssl_handle), static_cast<int>(handle)); if (!SSL_connect(static_cast<SSL*>(ssl_handle))) { LOG(Warning, "Failed to connect SSL socket due to SSL negotiation failure."); close(); return false; } if (SSL_get_verify_result(static_cast<SSL*>(ssl_handle)) != 0) { LOG(Warning, "Failed to connect SSL socket due to certificate verfication failure."); close(); return false; } return true; } void TcpSocket::setDelay(bool delay) { if (handle == INVALID_SOCKET) { LOG(Warning, "Failed to setDelay due to being called on an incomplete socket"); return; } int mode = delay ? 0 : 1; if (setsockopt(handle, IPPROTO_TCP, TCP_NODELAY, (char*)&mode, sizeof(mode)) == -1) { LOG(Warning, "Failed to setDelay on a socket"); } } void TcpSocket::close() { if (handle != INVALID_SOCKET) { #ifdef _WIN32 closesocket(handle); #else ::close(handle); #endif handle = INVALID_SOCKET; connecting = false; clearQueue(); if (ssl_handle) SSL_free(static_cast<SSL*>(ssl_handle)); ssl_handle = nullptr; } } StreamSocket::State TcpSocket::getState() { if (handle == INVALID_SOCKET) return StreamSocket::State::Closed; if (connecting) { struct pollfd fds; fds.fd = handle; fds.events = POLLOUT; fds.revents = 0; if (WSAPoll(&fds, 1, 0)) { struct sockaddr_in6 server_addr; int server_addr_len = sizeof(server_addr); if (getpeername(handle, reinterpret_cast<sockaddr*>(&server_addr), &server_addr_len)) { close(); return StreamSocket::State::Closed; } connecting = false; return StreamSocket::State::Connected; } return StreamSocket::State::Connecting; } return StreamSocket::State::Connected; } size_t TcpSocket::_send(const void* data, size_t size) { int result; if (ssl_handle) result = SSL_write(static_cast<SSL*>(ssl_handle), static_cast<const char*>(data), static_cast<int>(size)); else result = ::send(handle, reinterpret_cast<const void *>(static_cast<const char*>(data)), size, flags); if (result < 0) { if (!isLastErrorNonBlocking()) close(); return 0; } return result; } size_t TcpSocket::_receive(void* data, size_t size) { int result; if (ssl_handle) result = SSL_read(static_cast<SSL*>(ssl_handle), static_cast<char*>(data), static_cast<int>(size)); else result = ::recv(handle, data, size, flags); if (result < 0) { result = 0; if (!isLastErrorNonBlocking()) close(); } return result; } }//namespace network }//namespace io }//namespace sp <commit_msg>linux build fix?<commit_after>#include <io/network/tcpSocket.h> #include <logging.h> #ifdef _WIN32 #include <winsock2.h> #include <ws2tcpip.h> static constexpr int flags = 0; static inline int send(SOCKET s, const void* msg, size_t len, int flags) { return send(s, static_cast<const char*>(msg), static_cast<int>(len), flags); } static inline int recv(SOCKET s, void* buf, size_t len, int flags) { return recv(s, static_cast<char*>(buf), static_cast<int>(len), flags); } #else #include <sys/types.h> #include <sys/socket.h> #include <unistd.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <arpa/inet.h> #include <string.h> #include <poll.h> static constexpr int flags = MSG_NOSIGNAL; static constexpr intptr_t INVALID_SOCKET = -1; #endif extern "C" { struct X509; struct X509_STORE; struct SSL_CTX; struct SSL_METHOD; struct SSL; static X509_STORE* (*X509_STORE_new)(); static X509* (*d2i_X509)(X509**, const unsigned char **, long); static int (*X509_STORE_add_cert)(X509_STORE*, X509*); static void (*X509_free)(X509*); static SSL_CTX* (*SSL_CTX_new)(const SSL_METHOD*); static const SSL_METHOD* (*TLSv1_2_client_method)(); static long (*SSL_CTX_set_options)(SSL_CTX*, long); static int (*SSL_CTX_set_default_verify_paths)(SSL_CTX*); static void (*SSL_CTX_set_cert_store)(SSL_CTX*, X509_STORE*); static SSL* (*SSL_new)(SSL_CTX*); static int (*SSL_set_fd)(SSL *ssl, int fd); static int (*SSL_connect)(SSL *ssl); static long (*SSL_get_verify_result)(const SSL *ssl); static int (*SSL_read)(SSL *ssl, void *buf, int num); static int (*SSL_write)(SSL *ssl, const void *buf, int num); static void (*SSL_free)(SSL *ssl); static SSL_CTX* ssl_context; } # define SSL_OP_NO_SSLv2 0x01000000L # define SSL_OP_NO_SSLv3 0x02000000L # define SSL_OP_NO_TLSv1 0x04000000L # define SSL_OP_NO_TLSv1_2 0x08000000L # define SSL_OP_NO_TLSv1_1 0x10000000L #ifndef __ANDROID__ #include "dynamicLibrary.h" static std::unique_ptr<DynamicLibrary> libcrypto; static std::unique_ptr<DynamicLibrary> libssl; #endif static void initializeLibSSL() { static bool initialized = false; if (initialized) return; initialized = true; #ifndef __ANDROID__ #ifdef _WIN32 libcrypto = DynamicLibrary::open("libcrypto-1_1.dll"); libssl = DynamicLibrary::open("libssl-1_1.dll"); #else libcrypto = DynamicLibrary::open("libcrypto.so.1.1"); libssl = DynamicLibrary::open("libssl.so.1.1"); #endif if (!libcrypto || !libssl) return; X509_STORE_new = libcrypto->getFunction<X509_STORE*(*)()>("X509_STORE_new"); d2i_X509 = libcrypto->getFunction<X509* (*)(X509**, const unsigned char **, long)>("d2i_X509"); X509_STORE_add_cert = libcrypto->getFunction<int (*)(X509_STORE*, X509*)>("X509_STORE_add_cert"); X509_free = libcrypto->getFunction<void (*)(X509*)>("X509_free"); SSL_CTX_new = libssl->getFunction<SSL_CTX*(*)(const SSL_METHOD*)>("SSL_CTX_new"); TLSv1_2_client_method = libssl->getFunction<const SSL_METHOD* (*)()>("TLSv1_2_client_method"); SSL_CTX_set_options = libssl->getFunction<long (*)(SSL_CTX*, long)>("SSL_CTX_set_options"); SSL_CTX_set_default_verify_paths = libssl->getFunction<int (*)(SSL_CTX*)>("SSL_CTX_set_default_verify_paths"); SSL_CTX_set_cert_store = libssl->getFunction<void (*)(SSL_CTX*, X509_STORE*)>("SSL_CTX_set_cert_store"); SSL_new = libssl->getFunction<SSL* (*)(SSL_CTX*)>("SSL_new"); SSL_set_fd = libssl->getFunction<int (*)(SSL *ssl, int fd)>("SSL_set_fd"); SSL_connect = libssl->getFunction<int (*)(SSL *ssl)>("SSL_connect"); SSL_get_verify_result = libssl->getFunction<long (*)(const SSL *ssl)>("SSL_get_verify_result"); SSL_read = libssl->getFunction<int (*)(SSL *ssl, void *buf, int num)>("SSL_read"); SSL_write = libssl->getFunction<int (*)(SSL *ssl, const void *buf, int num)>("SSL_write"); SSL_free = libssl->getFunction<void (*)(SSL *ssl)>("SSL_free"); #ifdef _WIN32 HCERTSTORE hStore; PCCERT_CONTEXT pContext = NULL; X509 *x509; X509_STORE *store = X509_STORE_new(); hStore = CertOpenSystemStore(0, "ROOT"); while((pContext = CertEnumCertificatesInStore(hStore, pContext)) != nullptr) { const unsigned char* c = pContext->pbCertEncoded; x509 = d2i_X509(nullptr, &c, pContext->cbCertEncoded); if (x509) { X509_STORE_add_cert(store, x509); X509_free(x509); } } CertFreeCertificateContext(pContext); CertCloseStore(hStore, 0); #endif ssl_context = SSL_CTX_new(TLSv1_2_client_method()); SSL_CTX_set_options(ssl_context, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1); #ifdef _WIN32 SSL_CTX_set_cert_store(ssl_context, store); #else SSL_CTX_set_default_verify_paths(ssl_context); #endif #endif } namespace sp { namespace io { namespace network { TcpSocket::TcpSocket() : ssl_handle(nullptr) { } TcpSocket::~TcpSocket() { close(); } bool TcpSocket::connect(const Address& host, int port) { if (handle != INVALID_SOCKET) close(); for(const auto& addr_info : host.addr_info) { handle = ::socket(addr_info.family, SOCK_STREAM, 0); if (handle == INVALID_SOCKET) return false; setBlocking(blocking); if (addr_info.family == AF_INET && sizeof(struct sockaddr_in) == addr_info.addr.size()) { struct sockaddr_in server_addr; memset(&server_addr, 0, sizeof(server_addr)); memcpy(&server_addr, addr_info.addr.data(), addr_info.addr.size()); server_addr.sin_port = htons(port); if (::connect(handle, reinterpret_cast<const sockaddr*>(&server_addr), sizeof(server_addr)) == 0) return true; if (isLastErrorNonBlocking()) { connecting = true; return true; } } if (addr_info.family == AF_INET6 && sizeof(struct sockaddr_in6) == addr_info.addr.size()) { struct sockaddr_in6 server_addr; memset(&server_addr, 0, sizeof(server_addr)); memcpy(&server_addr, addr_info.addr.data(), addr_info.addr.size()); server_addr.sin6_port = htons(port); if (::connect(handle, reinterpret_cast<const sockaddr*>(&server_addr), sizeof(server_addr)) == 0) return true; if (isLastErrorNonBlocking()) { connecting = true; return true; } } close(); } return false; } bool TcpSocket::connectSSL(const Address& host, int port) { if (!connect(host, port)) return false; initializeLibSSL(); if (!SSL_new) { LOG(Warning, "Failed to connect SSL socket due to missing libssl/libcrypto v1.1"); close(); return false; } ssl_handle = SSL_new(ssl_context); SSL_set_fd(static_cast<SSL*>(ssl_handle), static_cast<int>(handle)); if (!SSL_connect(static_cast<SSL*>(ssl_handle))) { LOG(Warning, "Failed to connect SSL socket due to SSL negotiation failure."); close(); return false; } if (SSL_get_verify_result(static_cast<SSL*>(ssl_handle)) != 0) { LOG(Warning, "Failed to connect SSL socket due to certificate verfication failure."); close(); return false; } return true; } void TcpSocket::setDelay(bool delay) { if (handle == INVALID_SOCKET) { LOG(Warning, "Failed to setDelay due to being called on an incomplete socket"); return; } int mode = delay ? 0 : 1; if (setsockopt(handle, IPPROTO_TCP, TCP_NODELAY, (char*)&mode, sizeof(mode)) == -1) { LOG(Warning, "Failed to setDelay on a socket"); } } void TcpSocket::close() { if (handle != INVALID_SOCKET) { #ifdef _WIN32 closesocket(handle); #else ::close(handle); #endif handle = INVALID_SOCKET; connecting = false; clearQueue(); if (ssl_handle) SSL_free(static_cast<SSL*>(ssl_handle)); ssl_handle = nullptr; } } StreamSocket::State TcpSocket::getState() { if (handle == INVALID_SOCKET) return StreamSocket::State::Closed; if (connecting) { struct pollfd fds; fds.fd = handle; fds.events = POLLOUT; fds.revents = 0; #ifdef WIN32 if (WSAPoll(&fds, 1, 0)) #else if (poll(&fds, 1, 0)) #endif { struct sockaddr_in6 server_addr; int server_addr_len = sizeof(server_addr); if (getpeername(handle, reinterpret_cast<sockaddr*>(&server_addr), &server_addr_len)) { close(); return StreamSocket::State::Closed; } connecting = false; return StreamSocket::State::Connected; } return StreamSocket::State::Connecting; } return StreamSocket::State::Connected; } size_t TcpSocket::_send(const void* data, size_t size) { int result; if (ssl_handle) result = SSL_write(static_cast<SSL*>(ssl_handle), static_cast<const char*>(data), static_cast<int>(size)); else result = ::send(handle, reinterpret_cast<const void *>(static_cast<const char*>(data)), size, flags); if (result < 0) { if (!isLastErrorNonBlocking()) close(); return 0; } return result; } size_t TcpSocket::_receive(void* data, size_t size) { int result; if (ssl_handle) result = SSL_read(static_cast<SSL*>(ssl_handle), static_cast<char*>(data), static_cast<int>(size)); else result = ::recv(handle, data, size, flags); if (result < 0) { result = 0; if (!isLastErrorNonBlocking()) close(); } return result; } }//namespace network }//namespace io }//namespace sp <|endoftext|>
<commit_before>/* * Asynchronous local file access. * * author: Max Kellermann <mk@cm4all.com> */ #include "istream_file.hxx" #include "istream.hxx" #include "io/Buffered.hxx" #include "io/UniqueFileDescriptor.hxx" #include "gerrno.h" #include "pool.hxx" #include "fb_pool.hxx" #include "SliceFifoBuffer.hxx" #include "event/TimerEvent.hxx" #include <assert.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <limits.h> /** * If EAGAIN occurs (on NFS), we try again after 100ms. We can't * check EV_READ, because the kernel always indicates VFS files as * "readable without blocking". */ static const struct timeval file_retry_timeout = { .tv_sec = 0, .tv_usec = 100000, }; struct FileIstream final : public Istream { int fd; FdType fd_type; /** * A timer to retry reading after EAGAIN. */ TimerEvent event; off_t rest; SliceFifoBuffer buffer; const char *path; FileIstream(struct pool &p, EventLoop &event_loop, int _fd, FdType _fd_type, off_t _length, const char *_path) :Istream(p), fd(_fd), fd_type(_fd_type), event(event_loop, BIND_THIS_METHOD(EventCallback)), rest(_length), path(_path) {} ~FileIstream() { event.Cancel(); } void CloseHandle() { if (fd < 0) return; event.Cancel(); close(fd); fd = -1; buffer.FreeIfDefined(fb_pool_get()); } void Abort(GError *error) { CloseHandle(); DestroyError(error); } /** * @return the number of bytes still in the buffer */ size_t SubmitBuffer() { return ConsumeFromBuffer(buffer); } void EofDetected() { assert(fd >= 0); CloseHandle(); DestroyEof(); } gcc_pure size_t GetMaxRead() const { if (rest != (off_t)-1 && rest < (off_t)INT_MAX) return (size_t)rest; else return INT_MAX; } void TryData(); void TryDirect(); void TryRead() { if (CheckDirect(fd_type)) TryDirect(); else TryData(); } void EventCallback() { TryRead(); } /* virtual methods from class Istream */ off_t _GetAvailable(bool partial) override; off_t _Skip(gcc_unused off_t length) override; void _Read() override { event.Cancel(); TryRead(); } int _AsFd() override; void _Close() override { CloseHandle(); Destroy(); } }; inline void FileIstream::TryData() { size_t buffer_rest = 0; if (buffer.IsNull()) { if (rest != 0) buffer.Allocate(fb_pool_get()); } else { const size_t available = buffer.GetAvailable(); if (available > 0) { buffer_rest = SubmitBuffer(); if (buffer_rest == available) /* not a single byte was consumed: we may have been closed, and we must bail out now */ return; } } if (rest == 0) { if (buffer_rest == 0) EofDetected(); return; } ssize_t nbytes = read_to_buffer(fd, buffer, GetMaxRead()); if (nbytes == 0) { if (rest == (off_t)-1) { rest = 0; if (buffer_rest == 0) EofDetected(); } else { GError *error = g_error_new(g_file_error_quark(), 0, "premature end of file in '%s'", path); Abort(error); } return; } else if (nbytes == -1) { GError *error = g_error_new(errno_quark(), errno, "failed to read from '%s': %s", path, strerror(errno)); Abort(error); return; } else if (nbytes > 0 && rest != (off_t)-1) { rest -= (off_t)nbytes; assert(rest >= 0); } assert(!buffer.IsEmpty()); buffer_rest = SubmitBuffer(); if (buffer_rest == 0 && rest == 0) EofDetected(); } inline void FileIstream::TryDirect() { /* first consume the rest of the buffer */ if (SubmitBuffer() > 0) return; if (rest == 0) { EofDetected(); return; } ssize_t nbytes = InvokeDirect(fd_type, fd, GetMaxRead()); if (nbytes == ISTREAM_RESULT_CLOSED) /* this stream was closed during the direct() callback */ return; if (nbytes > 0 || nbytes == ISTREAM_RESULT_BLOCKING) { /* -2 means the callback wasn't able to consume any data right now */ if (nbytes > 0 && rest != (off_t)-1) { rest -= (off_t)nbytes; assert(rest >= 0); if (rest == 0) EofDetected(); } } else if (nbytes == ISTREAM_RESULT_EOF) { if (rest == (off_t)-1) { EofDetected(); } else { GError *error = g_error_new(g_file_error_quark(), 0, "premature end of file in '%s'", path); Abort(error); } } else if (errno == EAGAIN) { /* this should only happen for splice(SPLICE_F_NONBLOCK) from NFS files - unfortunately we cannot use EV_READ here, so we just install a timer which retries after 100ms */ event.Add(file_retry_timeout); } else { /* XXX */ GError *error = g_error_new(errno_quark(), errno, "failed to read from '%s': %s", path, strerror(errno)); Abort(error); } } /* * istream implementation * */ off_t FileIstream::_GetAvailable(bool partial) { off_t available; if (rest != (off_t)-1) available = rest; else if (!partial) return (off_t)-1; else available = 0; available += buffer.GetAvailable(); return available; } off_t FileIstream::_Skip(off_t length) { event.Cancel(); if (rest == (off_t)-1) return (off_t)-1; if (length == 0) return 0; const size_t buffer_available = buffer.GetAvailable(); if (length < off_t(buffer_available)) { buffer.Consume(length); Consumed(length); return length; } length -= buffer_available; buffer.Clear(); if (length >= rest) { /* skip beyond EOF */ length = rest; rest = 0; } else { /* seek the file descriptor */ off_t ret = lseek(fd, length, SEEK_CUR); if (ret < 0) return -1; rest -= length; } off_t result = buffer_available + length; Consumed(result); return result; } int FileIstream::_AsFd() { int result_fd = fd; Destroy(); return result_fd; } /* * constructor and public methods * */ Istream * istream_file_fd_new(EventLoop &event_loop, struct pool &pool, const char *path, int fd, FdType fd_type, off_t length) { assert(fd >= 0); assert(length >= -1); return NewIstream<FileIstream>(pool, event_loop, fd, fd_type, length, path); } Istream * istream_file_stat_new(EventLoop &event_loop, struct pool &pool, const char *path, struct stat &st, GError **error_r) { assert(path != nullptr); UniqueFileDescriptor fd; if (!fd.OpenReadOnly(path)) { set_error_errno(error_r); g_prefix_error(error_r, "Failed to open %s: ", path); return nullptr; } if (fstat(fd.Get(), &st) < 0) { set_error_errno(error_r); g_prefix_error(error_r, "Failed to stat %s: ", path); return nullptr; } FdType fd_type = FdType::FD_FILE; off_t size = st.st_size; if (S_ISCHR(st.st_mode)) { fd_type = FdType::FD_CHARDEV; size = -1; } return istream_file_fd_new(event_loop, pool, path, fd.Steal(), fd_type, size); } Istream * istream_file_new(EventLoop &event_loop, struct pool &pool, const char *path, off_t length, GError **error_r) { assert(length >= -1); UniqueFileDescriptor fd; if (!fd.OpenReadOnly(path)) { set_error_errno(error_r); g_prefix_error(error_r, "Failed to open %s: ", path); return nullptr; } return istream_file_fd_new(event_loop, pool, path, fd.Steal(), FdType::FD_FILE, length); } int istream_file_fd(Istream &istream) { auto &file = (FileIstream &)istream; assert(file.fd >= 0); return file.fd; } bool istream_file_set_range(Istream &istream, off_t start, off_t end) { assert(start >= 0); assert(end >= start); auto &file = (FileIstream &)istream; assert(file.fd >= 0); assert(file.rest >= 0); assert(file.buffer.IsNull()); assert(end <= file.rest); if (start > 0 && lseek(file.fd, start, SEEK_CUR) < 0) return false; file.rest = end - start; return true; } <commit_msg>istream/file: rename "event" to "retry_event"<commit_after>/* * Asynchronous local file access. * * author: Max Kellermann <mk@cm4all.com> */ #include "istream_file.hxx" #include "istream.hxx" #include "io/Buffered.hxx" #include "io/UniqueFileDescriptor.hxx" #include "gerrno.h" #include "pool.hxx" #include "fb_pool.hxx" #include "SliceFifoBuffer.hxx" #include "event/TimerEvent.hxx" #include <assert.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <limits.h> /** * If EAGAIN occurs (on NFS), we try again after 100ms. We can't * check EV_READ, because the kernel always indicates VFS files as * "readable without blocking". */ static const struct timeval file_retry_timeout = { .tv_sec = 0, .tv_usec = 100000, }; struct FileIstream final : public Istream { int fd; FdType fd_type; /** * A timer to retry reading after EAGAIN. */ TimerEvent retry_event; off_t rest; SliceFifoBuffer buffer; const char *path; FileIstream(struct pool &p, EventLoop &event_loop, int _fd, FdType _fd_type, off_t _length, const char *_path) :Istream(p), fd(_fd), fd_type(_fd_type), retry_event(event_loop, BIND_THIS_METHOD(EventCallback)), rest(_length), path(_path) {} ~FileIstream() { retry_event.Cancel(); } void CloseHandle() { if (fd < 0) return; retry_event.Cancel(); close(fd); fd = -1; buffer.FreeIfDefined(fb_pool_get()); } void Abort(GError *error) { CloseHandle(); DestroyError(error); } /** * @return the number of bytes still in the buffer */ size_t SubmitBuffer() { return ConsumeFromBuffer(buffer); } void EofDetected() { assert(fd >= 0); CloseHandle(); DestroyEof(); } gcc_pure size_t GetMaxRead() const { if (rest != (off_t)-1 && rest < (off_t)INT_MAX) return (size_t)rest; else return INT_MAX; } void TryData(); void TryDirect(); void TryRead() { if (CheckDirect(fd_type)) TryDirect(); else TryData(); } void EventCallback() { TryRead(); } /* virtual methods from class Istream */ off_t _GetAvailable(bool partial) override; off_t _Skip(gcc_unused off_t length) override; void _Read() override { retry_event.Cancel(); TryRead(); } int _AsFd() override; void _Close() override { CloseHandle(); Destroy(); } }; inline void FileIstream::TryData() { size_t buffer_rest = 0; if (buffer.IsNull()) { if (rest != 0) buffer.Allocate(fb_pool_get()); } else { const size_t available = buffer.GetAvailable(); if (available > 0) { buffer_rest = SubmitBuffer(); if (buffer_rest == available) /* not a single byte was consumed: we may have been closed, and we must bail out now */ return; } } if (rest == 0) { if (buffer_rest == 0) EofDetected(); return; } ssize_t nbytes = read_to_buffer(fd, buffer, GetMaxRead()); if (nbytes == 0) { if (rest == (off_t)-1) { rest = 0; if (buffer_rest == 0) EofDetected(); } else { GError *error = g_error_new(g_file_error_quark(), 0, "premature end of file in '%s'", path); Abort(error); } return; } else if (nbytes == -1) { GError *error = g_error_new(errno_quark(), errno, "failed to read from '%s': %s", path, strerror(errno)); Abort(error); return; } else if (nbytes > 0 && rest != (off_t)-1) { rest -= (off_t)nbytes; assert(rest >= 0); } assert(!buffer.IsEmpty()); buffer_rest = SubmitBuffer(); if (buffer_rest == 0 && rest == 0) EofDetected(); } inline void FileIstream::TryDirect() { /* first consume the rest of the buffer */ if (SubmitBuffer() > 0) return; if (rest == 0) { EofDetected(); return; } ssize_t nbytes = InvokeDirect(fd_type, fd, GetMaxRead()); if (nbytes == ISTREAM_RESULT_CLOSED) /* this stream was closed during the direct() callback */ return; if (nbytes > 0 || nbytes == ISTREAM_RESULT_BLOCKING) { /* -2 means the callback wasn't able to consume any data right now */ if (nbytes > 0 && rest != (off_t)-1) { rest -= (off_t)nbytes; assert(rest >= 0); if (rest == 0) EofDetected(); } } else if (nbytes == ISTREAM_RESULT_EOF) { if (rest == (off_t)-1) { EofDetected(); } else { GError *error = g_error_new(g_file_error_quark(), 0, "premature end of file in '%s'", path); Abort(error); } } else if (errno == EAGAIN) { /* this should only happen for splice(SPLICE_F_NONBLOCK) from NFS files - unfortunately we cannot use EV_READ here, so we just install a timer which retries after 100ms */ retry_event.Add(file_retry_timeout); } else { /* XXX */ GError *error = g_error_new(errno_quark(), errno, "failed to read from '%s': %s", path, strerror(errno)); Abort(error); } } /* * istream implementation * */ off_t FileIstream::_GetAvailable(bool partial) { off_t available; if (rest != (off_t)-1) available = rest; else if (!partial) return (off_t)-1; else available = 0; available += buffer.GetAvailable(); return available; } off_t FileIstream::_Skip(off_t length) { retry_event.Cancel(); if (rest == (off_t)-1) return (off_t)-1; if (length == 0) return 0; const size_t buffer_available = buffer.GetAvailable(); if (length < off_t(buffer_available)) { buffer.Consume(length); Consumed(length); return length; } length -= buffer_available; buffer.Clear(); if (length >= rest) { /* skip beyond EOF */ length = rest; rest = 0; } else { /* seek the file descriptor */ off_t ret = lseek(fd, length, SEEK_CUR); if (ret < 0) return -1; rest -= length; } off_t result = buffer_available + length; Consumed(result); return result; } int FileIstream::_AsFd() { int result_fd = fd; Destroy(); return result_fd; } /* * constructor and public methods * */ Istream * istream_file_fd_new(EventLoop &event_loop, struct pool &pool, const char *path, int fd, FdType fd_type, off_t length) { assert(fd >= 0); assert(length >= -1); return NewIstream<FileIstream>(pool, event_loop, fd, fd_type, length, path); } Istream * istream_file_stat_new(EventLoop &event_loop, struct pool &pool, const char *path, struct stat &st, GError **error_r) { assert(path != nullptr); UniqueFileDescriptor fd; if (!fd.OpenReadOnly(path)) { set_error_errno(error_r); g_prefix_error(error_r, "Failed to open %s: ", path); return nullptr; } if (fstat(fd.Get(), &st) < 0) { set_error_errno(error_r); g_prefix_error(error_r, "Failed to stat %s: ", path); return nullptr; } FdType fd_type = FdType::FD_FILE; off_t size = st.st_size; if (S_ISCHR(st.st_mode)) { fd_type = FdType::FD_CHARDEV; size = -1; } return istream_file_fd_new(event_loop, pool, path, fd.Steal(), fd_type, size); } Istream * istream_file_new(EventLoop &event_loop, struct pool &pool, const char *path, off_t length, GError **error_r) { assert(length >= -1); UniqueFileDescriptor fd; if (!fd.OpenReadOnly(path)) { set_error_errno(error_r); g_prefix_error(error_r, "Failed to open %s: ", path); return nullptr; } return istream_file_fd_new(event_loop, pool, path, fd.Steal(), FdType::FD_FILE, length); } int istream_file_fd(Istream &istream) { auto &file = (FileIstream &)istream; assert(file.fd >= 0); return file.fd; } bool istream_file_set_range(Istream &istream, off_t start, off_t end) { assert(start >= 0); assert(end >= start); auto &file = (FileIstream &)istream; assert(file.fd >= 0); assert(file.rest >= 0); assert(file.buffer.IsNull()); assert(end <= file.rest); if (start > 0 && lseek(file.fd, start, SEEK_CUR) < 0) return false; file.rest = end - start; return true; } <|endoftext|>
<commit_before>#include "Manager.hpp" #include <string> #include <vector> #include <stdexcept> #include <algorithm> #include <boost/program_options.hpp> #include <boost/filesystem.hpp> int smain(int argc, char *argv[]) { namespace po = boost::program_options; namespace fs = boost::filesystem; po::options_description desc("Allowed options"); desc.add_options() ("help,h", "help message") ("config-path,c", po::value< std::vector<std::string> >(), "configuration path") ; po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); if(vm.count("help")) { std::cerr << desc << "\n"; return 1; } std::vector<std::string> files; if(vm.count("config-path")) { auto conf_path = vm["config-path"].as< std::vector<std::string> >(); for(std::string &dir : conf_path) { fs::path p(dir); if(fs::is_regular_file(p) && 0 == p.extension().compare(".lua") && file_size(p) > 0) { files.push_back(p.native()); } else if (fs::is_directory(p)) { std::for_each(fs::directory_iterator(p), fs::directory_iterator(), [&](fs::directory_entry &de) { fs::path p2 = de.path(); if(fs::is_regular_file(p2) && 0 == p2.extension().compare(".lua") && file_size(p2) > 0) { files.push_back(p2.native()); } } ); } } } else { std::cerr << desc << "\n"; return 1; } // run it... lutop::Manager m; m.loadFiles(files); return 0; } int main(int argc, char *argv[]) { try { return smain(argc, argv); } catch(std::exception const &e) { std::cerr << "Exception: " << e.what() << std::endl; return 1; } catch(...) { std::cerr << "Unknown exception" << std::endl; return 1; } } <commit_msg>boost::filesystem api in not stable...<commit_after>#include "Manager.hpp" #include <string> #include <vector> #include <stdexcept> #include <algorithm> #include <boost/program_options.hpp> #include <boost/filesystem.hpp> int smain(int argc, char *argv[]) { namespace po = boost::program_options; namespace fs = boost::filesystem; po::options_description desc("Allowed options"); desc.add_options() ("help,h", "help message") ("config-path,c", po::value< std::vector<std::string> >(), "configuration path") ; po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); if(vm.count("help")) { std::cerr << desc << "\n"; return 1; } std::vector<std::string> files; if(vm.count("config-path")) { auto conf_path = vm["config-path"].as< std::vector<std::string> >(); for(std::string &dir : conf_path) { fs::path p(dir); if(fs::is_regular_file(p) && (p.extension() == ".lua") && file_size(p) > 0) { files.push_back(p.native()); } else if (fs::is_directory(p)) { std::for_each(fs::directory_iterator(p), fs::directory_iterator(), [&](fs::directory_entry &de) { fs::path p2 = de.path(); if(fs::is_regular_file(p2) && (p2.extension() == ".lua") && file_size(p2) > 0) { files.push_back(p2.native()); } } ); } } } else { std::cerr << desc << "\n"; return 1; } // run it... lutop::Manager m; m.loadFiles(files); return 0; } int main(int argc, char *argv[]) { try { return smain(argc, argv); } catch(std::exception const &e) { std::cerr << "Exception: " << e.what() << std::endl; return 1; } catch(...) { std::cerr << "Unknown exception" << std::endl; return 1; } } <|endoftext|>
<commit_before>/******************************************************************************* * E.S.O. - ACS project * * "@(#) $Id: acsdaemonStopContainer.cpp,v 1.9 2008/06/27 11:41:07 msekoran Exp $" * * who when what * -------- ---------- ---------------------------------------------- */ /** @file acsdaemonStopContainer.cpp * acsdaemonStopContainer is used to remotely stop container via ACS Deamon. * @htmlonly * <br><hr> * @endhtmlonly */ #include <acsutilPorts.h> #include <logging.h> #include <acsdaemonC.h> #include <ACSErrTypeCommon.h> #include <acsdaemonErrType.h> #include <getopt.h> static struct option long_options[] = { {"help", no_argument, 0, 'h'}, {"container", required_argument, 0, 'c'}, {"instance", required_argument, 0, 'i'}, {"host", required_argument, 0, 'H'}, {"daemon", required_argument, 0, 'd'}, {"additional", required_argument, 0, 'a'}, {0, 0, 0, '\0'}}; void usage(const char *argv) { ACE_OS::printf ("\n\tusage: %s {-h} -i INSTANCE -t TYPE -c CONTAINER [-d DAEMONREF] [-H HOST] [-a more options]", argv); ACE_OS::printf ("\t -h, --help show this help message\n"); ACE_OS::printf ("\t -c, --container container name\n"); ACE_OS::printf ("\t -i, --instance ACS instance to use\n"); ACE_OS::printf ("\t -H, --host Host where to stop the container\n"); ACE_OS::printf ("\t -d, --daemon Daemon reference\n"); ACE_OS::printf ("\t -a, --additional passthrough options for stopContaner. Put options between \"\"\n"); } int main (int argc, char *argv[]) { int c, instance = -1; ACE_CString daemonRef; ACE_CString hostName; ACE_CString containerName; ACE_CString additional; for(;;) { int option_index = 0; c = getopt_long (argc, argv, "hc:i:d:H:a:", long_options, &option_index); if (c==-1) break; switch(c) { case 'h': usage(argv[0]); return 0; case 'i': instance = ACE_OS::atoi(optarg); break; case 'd': daemonRef = optarg; break; case 'H': hostName = optarg; break; case 'c': containerName = optarg; break; case 'a': additional = optarg; break; } } if (instance == -1) { ACE_OS::printf("Error: instance is a mandatory option try %s -h\n", argv[0]); return -1; } if (containerName.length() == 0) { ACE_OS::printf("Error: container name is a mandatory option try %s -h\n", argv[0]); return -1; } LoggingProxy * logger = new LoggingProxy(0, 0, 31); if (logger) { LoggingProxy::init(logger); LoggingProxy::ProcessName(argv[0]); LoggingProxy::ThreadName("main"); } else ACS_SHORT_LOG((LM_INFO, "Failed to initialize logging.")); try { // Initialize the ORB. CORBA::ORB_var orb = CORBA::ORB_init (argc,argv,"TAO"); // construct default one if (daemonRef.length() == 0) { if(hostName.length() == 0) { hostName = ACSPorts::getIP(); } daemonRef = "corbaloc::"; daemonRef = daemonRef + hostName + ":" + ACSPorts::getContainerDaemonPort().c_str() + "/" + ::acsdaemon::containerDaemonServiceName; ACS_SHORT_LOG((LM_INFO, "Using local Container Daemon reference: '%s'", daemonRef.c_str())); } else { ACS_SHORT_LOG((LM_INFO, "Container Daemon reference obtained via command line: '%s'", daemonRef.c_str())); } CORBA::Object_var obj = orb->string_to_object(daemonRef.c_str()); if (CORBA::is_nil(obj.in())) { ACS_SHORT_LOG((LM_INFO, "Failed to resolve reference '%s'.", daemonRef.c_str())); return -1; } acsdaemon::ContainerDaemon_var daemon = acsdaemon::ContainerDaemon::_narrow(obj.in()); if (CORBA::is_nil(daemon.in())) { ACS_SHORT_LOG((LM_INFO, "Failed to narrow reference '%s'.", daemonRef.c_str())); return -1; } ACS_SHORT_LOG((LM_INFO, "Calling stop_container(%s, %d, %s).", containerName.c_str(), instance, additional.c_str())); daemon->stop_container(containerName.c_str(), instance, additional.c_str()); ACS_SHORT_LOG((LM_INFO, "Container stop message issued.")); } catch (ACSErrTypeCommon::BadParameterEx &ex) { ACSErrTypeCommon::BadParameterExImpl exImpl(ex); exImpl.log(); return -1; } catch (acsdaemonErrType::FailedToStopContainerEx &ex) { acsdaemonErrType::FailedToStopContainerExImpl exImpl(ex); exImpl.log(); return -1; } catch( CORBA::Exception &ex ) { ACS_SHORT_LOG((LM_INFO, "Failed.")); ACE_PRINT_EXCEPTION (ex, ACE_TEXT ("Caught unexpected exception:")); return -1; } return 0; } <commit_msg>Added --synchronous (-s) option to invoke stop_container_sync() method instead of stop_container()<commit_after>/******************************************************************************* * E.S.O. - ACS project * * "@(#) $Id: acsdaemonStopContainer.cpp,v 1.9 2008/06/27 11:41:07 msekoran Exp $" * * who when what * -------- ---------- ---------------------------------------------- */ /** @file acsdaemonStopContainer.cpp * acsdaemonStopContainer is used to remotely stop container via ACS Deamon. * @htmlonly * <br><hr> * @endhtmlonly */ #include <acsutilPorts.h> #include <logging.h> #include <acsdaemonC.h> #include <ACSErrTypeCommon.h> #include <acsdaemonErrType.h> #include <getopt.h> static struct option long_options[] = { {"help", no_argument, 0, 'h'}, {"container", required_argument, 0, 'c'}, {"instance", required_argument, 0, 'i'}, {"host", required_argument, 0, 'H'}, {"daemon", required_argument, 0, 'd'}, {"additional", required_argument, 0, 'a'}, {"synchronous", no_argument, 0, 's'}, {0, 0, 0, '\0'}}; void usage(const char *argv) { ACE_OS::printf ("\n\tusage: %s {-h} -i INSTANCE -t TYPE -c CONTAINER [-d DAEMONREF] [-H HOST] [-a more options]", argv); ACE_OS::printf ("\t -h, --help show this help message\n"); ACE_OS::printf ("\t -c, --container container name\n"); ACE_OS::printf ("\t -i, --instance ACS instance to use\n"); ACE_OS::printf ("\t -H, --host Host where to stop the container\n"); ACE_OS::printf ("\t -d, --daemon Daemon reference\n"); ACE_OS::printf ("\t -a, --additional passthrough options for stopContaner. Put options between \"\"\n"); ACE_OS::printf ("\t -s, --synchronous Send the command to stop the container synchronously\n"); ACE_OS::printf ("\t The script will exit only when the container will have been fully stopped or if an error occurred\n"); } int main (int argc, char *argv[]) { int c, instance = -1; ACE_CString daemonRef; ACE_CString hostName; ACE_CString containerName; ACE_CString additional; int sync_flag = 0; for(;;) { int option_index = 0; c = getopt_long (argc, argv, "hc:i:d:H:a:s", long_options, &option_index); if (c==-1) break; switch(c) { case 'h': usage(argv[0]); return 0; case 'i': instance = ACE_OS::atoi(optarg); break; case 'd': daemonRef = optarg; break; case 'H': hostName = optarg; break; case 'c': containerName = optarg; break; case 'a': additional = optarg; break; case 's': sync_flag = 1; break; } } if (instance == -1) { ACE_OS::printf("Error: instance is a mandatory option try %s -h\n", argv[0]); return -1; } if (containerName.length() == 0) { ACE_OS::printf("Error: container name is a mandatory option try %s -h\n", argv[0]); return -1; } LoggingProxy * logger = new LoggingProxy(0, 0, 31); if (logger) { LoggingProxy::init(logger); LoggingProxy::ProcessName(argv[0]); LoggingProxy::ThreadName("main"); } else ACS_SHORT_LOG((LM_INFO, "Failed to initialize logging.")); try { // Initialize the ORB. CORBA::ORB_var orb = CORBA::ORB_init (argc,argv,"TAO"); // construct default one if (daemonRef.length() == 0) { if(hostName.length() == 0) { hostName = ACSPorts::getIP(); } daemonRef = "corbaloc::"; daemonRef = daemonRef + hostName + ":" + ACSPorts::getContainerDaemonPort().c_str() + "/" + ::acsdaemon::containerDaemonServiceName; ACS_SHORT_LOG((LM_INFO, "Using local Container Daemon reference: '%s'", daemonRef.c_str())); } else { ACS_SHORT_LOG((LM_INFO, "Container Daemon reference obtained via command line: '%s'", daemonRef.c_str())); } CORBA::Object_var obj = orb->string_to_object(daemonRef.c_str()); if (CORBA::is_nil(obj.in())) { ACS_SHORT_LOG((LM_INFO, "Failed to resolve reference '%s'.", daemonRef.c_str())); return -1; } acsdaemon::ContainerDaemon_var daemon = acsdaemon::ContainerDaemon::_narrow(obj.in()); if (CORBA::is_nil(daemon.in())) { ACS_SHORT_LOG((LM_INFO, "Failed to narrow reference '%s'.", daemonRef.c_str())); return -1; } ACS_SHORT_LOG((LM_INFO, "Calling stop_container(%s, %d, %s).", containerName.c_str(), instance, additional.c_str())); if (sync_flag) { daemon->stop_container_sync(containerName.c_str(), instance, additional.c_str()); } else { daemon->stop_container(containerName.c_str(), instance, additional.c_str()); } ACS_SHORT_LOG((LM_INFO, "Container stop message issued.")); } catch (ACSErrTypeCommon::BadParameterEx &ex) { ACSErrTypeCommon::BadParameterExImpl exImpl(ex); exImpl.log(); return -1; } catch (acsdaemonErrType::FailedToStopContainerEx &ex) { acsdaemonErrType::FailedToStopContainerExImpl exImpl(ex); exImpl.log(); return -1; } catch( CORBA::Exception &ex ) { ACS_SHORT_LOG((LM_INFO, "Failed.")); ACE_PRINT_EXCEPTION (ex, ACE_TEXT ("Caught unexpected exception:")); return -1; } return 0; } <|endoftext|>
<commit_before>/******************************************************************************* * ALMA - Atacama Large Millimiter Array * (c) European Southern Observatory, 2011 * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * "@(#) $Id: bulkDataNTWriterListener.cpp,v 1.3 2011/10/14 17:30:28 bjeram Exp $" * * who when what * -------- -------- ---------------------------------------------- * almadev 2011-10-14 created */ #include "bulkDataNTWriterListener.h" #include <ACS_DDS_Errors.h> #include <iostream> using namespace std; BulkDataNTWriterListener::BulkDataNTWriterListener(const char *name) : topicName_m(name) { ACS_TRACE(__PRETTY_FUNCTION__); sum_unacknowledged_sample = 0; max_unacknowledged_sample =0; iter=0; } // Implementation skeleton destructor BulkDataNTWriterListener::~BulkDataNTWriterListener () { ACS_TRACE(__PRETTY_FUNCTION__); } void BulkDataNTWriterListener::on_offered_deadline_missed ( ::DDS::DataWriter* writer, const ::DDS::OfferedDeadlineMissedStatus & status) { cerr << topicName_m << " BulkDataNTWriterListener::on_offered_deadline_missed" << endl; } void BulkDataNTWriterListener::on_offered_incompatible_qos ( ::DDS::DataWriter* writer, const ::DDS::OfferedIncompatibleQosStatus & status) { cerr << topicName_m << " BulkDataNTWriterListener::on_offered_incompatible_qos" << endl; } void BulkDataNTWriterListener::on_liveliness_lost ( ::DDS::DataWriter* writer, const ::DDS::LivelinessLostStatus & status) { cerr << topicName_m << " BulkDataNTWriterListener::on_liveliness_lost" << endl; } void BulkDataNTWriterListener::on_publication_matched ( ::DDS::DataWriter* writer, const ::DDS::PublicationMatchedStatus & status) { cerr << topicName_m << " BulkDataNTWriterListener::on_publication_match" << endl; } void BulkDataNTWriterListener::on_reliable_writer_cache_changed(DDSDataWriter* writer, const DDS_ReliableWriterCacheChangedStatus& status) { sum_unacknowledged_sample += status.unacknowledged_sample_count; if( status.unacknowledged_sample_count > max_unacknowledged_sample) max_unacknowledged_sample = status.unacknowledged_sample_count; iter++; /* cerr << "==========> BDDDSWriterListenerImpl::on_reliable_writer_cache_changed" << endl; cerr << "==========> unacknowledged_sample_count: " << status.unacknowledged_sample_count; cerr << " unacknowledged_sample_count_peak: " << status.unacknowledged_sample_count_peak << endl; */ } void BulkDataNTWriterListener::on_reliable_reader_activity_changed(DDSDataWriter* writer, const DDS::ReliableReaderActivityChangedStatus& status) { cerr << topicName_m << " ==========> BulkDataNTWriterListener::on_reliable_reader_activity_changed:" << endl; cerr << topicName_m << " ==========> status.active_count:" << status.active_count << endl; cerr << topicName_m << " ==========> status.active_count_change:" << status.active_count_change << endl; cerr << topicName_m << " ==========> status.inactive_count:" << status.inactive_count << endl; cerr << topicName_m << " ==========> status.inactive_count_change:" << status.inactive_count_change << endl; } void BulkDataNTWriterListener::on_destination_unreachable(DDSDataWriter* writer, const DDS_InstanceHandle_t& handle, const DDS_Locator_t& destination) { cerr << topicName_m << " BulkDataNTWriterListener::on_destination_unreachable" << endl; } /*___oOo___*/ <commit_msg>implementd on_publication_matched<commit_after>/******************************************************************************* * ALMA - Atacama Large Millimiter Array * (c) European Southern Observatory, 2011 * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * "@(#) $Id: bulkDataNTWriterListener.cpp,v 1.4 2012/01/12 11:41:38 bjeram Exp $" * * who when what * -------- -------- ---------------------------------------------- * almadev 2011-10-14 created */ #include "bulkDataNTWriterListener.h" #include <ACS_DDS_Errors.h> #include <iostream> using namespace std; BulkDataNTWriterListener::BulkDataNTWriterListener(const char *name) : topicName_m(name) { ACS_TRACE(__PRETTY_FUNCTION__); sum_unacknowledged_sample = 0; max_unacknowledged_sample =0; iter=0; } // Implementation skeleton destructor BulkDataNTWriterListener::~BulkDataNTWriterListener () { ACS_TRACE(__PRETTY_FUNCTION__); } void BulkDataNTWriterListener::on_offered_deadline_missed ( ::DDS::DataWriter* writer, const ::DDS::OfferedDeadlineMissedStatus & status) { cerr << topicName_m << " BulkDataNTWriterListener::on_offered_deadline_missed" << endl; } void BulkDataNTWriterListener::on_offered_incompatible_qos ( ::DDS::DataWriter* writer, const ::DDS::OfferedIncompatibleQosStatus & status) { cerr << topicName_m << " BulkDataNTWriterListener::on_offered_incompatible_qos" << endl; } void BulkDataNTWriterListener::on_liveliness_lost ( ::DDS::DataWriter* writer, const ::DDS::LivelinessLostStatus & status) { cerr << topicName_m << " BulkDataNTWriterListener::on_liveliness_lost" << endl; } void BulkDataNTWriterListener::on_publication_matched (DDS::DataWriter* writer, const DDS::PublicationMatchedStatus & status) { ACS_TRACE(__FUNCTION__); }//on_publication_matched void BulkDataNTWriterListener::on_reliable_writer_cache_changed(DDSDataWriter* writer, const DDS_ReliableWriterCacheChangedStatus& status) { sum_unacknowledged_sample += status.unacknowledged_sample_count; if( status.unacknowledged_sample_count > max_unacknowledged_sample) max_unacknowledged_sample = status.unacknowledged_sample_count; iter++; /* cerr << "==========> BDDDSWriterListenerImpl::on_reliable_writer_cache_changed" << endl; cerr << "==========> unacknowledged_sample_count: " << status.unacknowledged_sample_count; cerr << " unacknowledged_sample_count_peak: " << status.unacknowledged_sample_count_peak << endl; */ } void BulkDataNTWriterListener::on_reliable_reader_activity_changed(DDSDataWriter* writer, const DDS::ReliableReaderActivityChangedStatus& status) { cerr << topicName_m << " ==========> BulkDataNTWriterListener::on_reliable_reader_activity_changed:" << endl; cerr << topicName_m << " ==========> status.active_count:" << status.active_count << endl; cerr << topicName_m << " ==========> status.active_count_change:" << status.active_count_change << endl; cerr << topicName_m << " ==========> status.inactive_count:" << status.inactive_count << endl; cerr << topicName_m << " ==========> status.inactive_count_change:" << status.inactive_count_change << endl; } void BulkDataNTWriterListener::on_destination_unreachable(DDSDataWriter* writer, const DDS_InstanceHandle_t& handle, const DDS_Locator_t& destination) { cerr << topicName_m << " BulkDataNTWriterListener::on_destination_unreachable" << endl; } /*___oOo___*/ <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2016. All rights reserved */ #include "../StroikaPreComp.h" #include "../Characters/Format.h" #include "../Execution/Logger.h" #include "../IO/FileSystem/FileInputStream.h" #include "../IO/FileSystem/FileOutputStream.h" #include "../IO/FileSystem/PathName.h" #include "../IO/FileSystem/ThroughTmpFileWriter.h" #include "../IO/FileSystem/WellKnownLocations.h" #include "../Streams/MemoryStream.h" #include "JSON/Reader.h" #include "JSON/Writer.h" #include "XML/Reader.h" #include "XML/Writer.h" #include "VariantValue.h" #include "OptionsFile.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::Characters; using namespace Stroika::Foundation::DataExchange; using namespace Stroika::Foundation::Streams; using Memory::BLOB; // Comment this in to turn on aggressive noisy DbgTrace in this module //#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1 /* ******************************************************************************** ***************** DataExchange::OptionsFile::LoggerMessage ********************* ******************************************************************************** */ OptionsFile::LoggerMessage::LoggerMessage (Msg msg, String fn) : fMsg (msg) , fFileName (fn) { } String OptionsFile::LoggerMessage::FormatMessage () const { switch (fMsg) { case Msg::eFailedToWriteFile: return Characters::Format (L"Failed to write file: %s", fFileName.Value ().c_str ()); case Msg::eFailedToReadFile: return Characters::Format (L"Failed to read file: %s", fFileName.Value ().c_str ()); case Msg::eFailedToParseReadFile: return Characters::Format (L"Error analyzing configuration file '%s' - using defaults.", fFileName.Value ().c_str ()); case Msg::eFailedToParseReadFileBadFormat: return Characters::Format (L"Error analyzing configuration file (because bad format) '%s' - using defaults.", fFileName.Value ().c_str ()); case Msg::eFailedToCompareReadFile: return Characters::Format (L"Failed to compare configuration file: %s", fFileName.Value ().c_str ()); case Msg::eWritingConfigFile_SoDefaultsEditable: return Characters::Format (L"Writing configuration file '%s' because not found (and so defaults are more easily seen and editable).", fFileName.Value ().c_str ()); case Msg::eWritingConfigFile_BecauseUpgraded: return Characters::Format (L"Writing configuration file '%s' in a new location because the software has been upgraded.", fFileName.Value ().c_str ()); case Msg::eWritingConfigFile_BecauseSomethingChanged: return Characters::Format (L"Writing configuration file '%s' because something changed (e.g. a default, or field added/removed).", fFileName.Value ().c_str ()); case Msg::eFailedToWriteInUseValues: return Characters::Format (L"Failed to write default (in use) values to file: %s", fFileName.Value ().c_str ()); default: RequireNotReached (); return String (); } } /* ******************************************************************************** ************************** DataExchange::OptionsFile *************************** ******************************************************************************** */ const OptionsFile::ModuleDataUpgraderType OptionsFile::kDefaultUpgrader = [] (const Memory::Optional<Configuration::Version>& version, const VariantValue& rawVariantValue) -> VariantValue { return rawVariantValue; }; const OptionsFile::LoggerType OptionsFile::kDefaultLogger = [] (const LoggerMessage& message) { using Execution::Logger; Logger::Priority priority = Logger::Priority::eError; using Msg = OptionsFile::LoggerMessage::Msg; switch (message.fMsg) { case Msg::eFailedToReadFile: priority = Logger::Priority::eWarning; // could be just because new system, no file break; case Msg::eWritingConfigFile_SoDefaultsEditable: case Msg::eWritingConfigFile_BecauseUpgraded: case Msg::eWritingConfigFile_BecauseSomethingChanged: priority = Logger::Priority::eInfo; break; case Msg::eFailedToParseReadFile: case Msg::eFailedToParseReadFileBadFormat: // Most likely very bad - as critical configuration data will be lost, and overwritten with 'defaults' priority = Logger::Priority::eCriticalError; break; } Logger::Get ().Log (priority, L"%s", message.FormatMessage ().c_str ()); }; const OptionsFile::ModuleNameToFileNameMapperType OptionsFile::mkFilenameMapper (const String& appName) { String useAppName = appName; return [useAppName] (const String & moduleName, const String & fileSuffix) -> String { return IO::FileSystem::WellKnownLocations::GetApplicationData() + useAppName + String (IO::FileSystem::kPathComponentSeperator) + moduleName + fileSuffix; } ; } const OptionsFile::ModuleNameToFileVersionMapperType OptionsFile::kDefaultModuleNameToFileVersionMapper = [] (const String& moduleName) -> Optional<Configuration::Version> { return Optional<Configuration::Version> (); // default to dont know }; // Consider using XML by default when more mature const VariantReader OptionsFile::kDefaultReader = JSON::Reader (); const VariantWriter OptionsFile::kDefaultWriter = JSON::Writer (); OptionsFile::OptionsFile ( const String& modName, const ObjectVariantMapper& mapper, ModuleDataUpgraderType moduleUpgrader, ModuleNameToFileNameMapperType moduleNameToFileNameMapper, ModuleNameToFileVersionMapperType moduleNameToReadFileVersion, LoggerType logger, VariantReader reader, VariantWriter writer ) : OptionsFile (modName, mapper, moduleUpgrader, moduleNameToFileNameMapper, moduleNameToFileNameMapper, moduleNameToReadFileVersion, logger, reader, writer, reader.GetDefaultFileSuffix ()) { } OptionsFile::OptionsFile ( const String& modName, const ObjectVariantMapper& mapper, ModuleDataUpgraderType moduleUpgrader, ModuleNameToFileNameMapperType moduleNameToReadFileNameMapper, ModuleNameToFileNameMapperType moduleNameToWriteFileNameMapper, ModuleNameToFileVersionMapperType moduleNameToReadFileVersion, LoggerType logger, VariantReader reader, VariantWriter writer ) : OptionsFile (modName, mapper, moduleUpgrader, moduleNameToReadFileNameMapper, moduleNameToWriteFileNameMapper, moduleNameToReadFileVersion, logger, reader, writer, reader.GetDefaultFileSuffix ()) { } OptionsFile::OptionsFile ( const String& modName, const ObjectVariantMapper& mapper, ModuleDataUpgraderType moduleUpgrader, ModuleNameToFileNameMapperType moduleNameToReadFileNameMapper, ModuleNameToFileNameMapperType moduleNameToWriteFileNameMapper, ModuleNameToFileVersionMapperType moduleNameToReadFileVersion, LoggerType logger, VariantReader reader, VariantWriter writer, const String& fileSuffix ) : fModuleName_ (modName) , fMapper_ (mapper) , fModuleDataUpgrader_ (moduleUpgrader) , fModuleNameToReadFileNameMapper_ (moduleNameToReadFileNameMapper) , fModuleNameToWriteFileNameMapper_ (moduleNameToWriteFileNameMapper) , fModuleNameToFileVersionMapper_ (moduleNameToReadFileVersion) , fLogger_ (logger) , fReader_ (reader) , fWriter_ (writer) , fFileSuffix_ (fileSuffix) { } BLOB OptionsFile::ReadRaw () const { Debug::TraceContextBumper ctx ("OptionsFile::ReadRaw"); #if USE_NOISY_TRACE_IN_THIS_MODULE_ DbgTrace (L"(readfilename=%s)", GetReadFilePath_ ().c_str ()); #endif return IO::FileSystem::FileInputStream::mk (GetReadFilePath_ ()).ReadAll (); } void OptionsFile::WriteRaw (const BLOB& blob) { Debug::TraceContextBumper ctx ("OptionsFile::WriteRaw"); #if USE_NOISY_TRACE_IN_THIS_MODULE_ DbgTrace (L"(writefilename=%s)", GetWriteFilePath_ ().c_str ()); #endif if (GetReadFilePath_ () == GetWriteFilePath_ ()) { try { if (ReadRaw () == blob) { return; } } catch (...) { // No matter why we fail, nevermind. Just fall through and write. } } try { IO::FileSystem::ThroughTmpFileWriter tmpFile (GetWriteFilePath_ ()); IO::FileSystem::FileOutputStream outStream (tmpFile.GetFilePath ()); outStream.Write (blob); outStream.Flush (); outStream.clear (); // so any errors can be displayed as exceptions, and so closed before commit/rename tmpFile.Commit (); } catch (...) { fLogger_ (LoggerMessage (LoggerMessage::Msg::eFailedToWriteFile, GetWriteFilePath_ ())); } } template <> Optional<VariantValue> OptionsFile::Read () { Debug::TraceContextBumper ctx ("OptionsFile::Read"); try { Optional<VariantValue> r = fReader_.Read (MemoryStream<Byte> (ReadRaw ())); if (r.IsPresent ()) { r = fModuleDataUpgrader_ (fModuleNameToFileVersionMapper_ (fModuleName_), *r); } return r; } catch (...) { // @todo - check different exception cases and for some - like file not found - just no warning... fLogger_ (LoggerMessage (LoggerMessage::Msg::eFailedToReadFile, GetReadFilePath_ ())); return Optional<VariantValue> (); } } template <> void OptionsFile::Write (const VariantValue& optionsObject) { Debug::TraceContextBumper ctx ("OptionsFile::Write"); MemoryStream<Byte> tmp; fWriter_.Write (optionsObject, tmp); WriteRaw (tmp.As<BLOB> ()); } String OptionsFile::GetReadFilePath_ () const { return fModuleNameToReadFileNameMapper_(fModuleName_, fFileSuffix_); } String OptionsFile::GetWriteFilePath_ () const { return fModuleNameToWriteFileNameMapper_(fModuleName_, fFileSuffix_); } <commit_msg>cosmetic<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2016. All rights reserved */ #include "../StroikaPreComp.h" #include "../Characters/Format.h" #include "../Execution/Logger.h" #include "../IO/FileSystem/FileInputStream.h" #include "../IO/FileSystem/FileOutputStream.h" #include "../IO/FileSystem/PathName.h" #include "../IO/FileSystem/ThroughTmpFileWriter.h" #include "../IO/FileSystem/WellKnownLocations.h" #include "../Streams/MemoryStream.h" #include "JSON/Reader.h" #include "JSON/Writer.h" #include "XML/Reader.h" #include "XML/Writer.h" #include "VariantValue.h" #include "OptionsFile.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::Characters; using namespace Stroika::Foundation::DataExchange; using namespace Stroika::Foundation::Streams; using Memory::BLOB; // Comment this in to turn on aggressive noisy DbgTrace in this module //#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1 /* ******************************************************************************** ***************** DataExchange::OptionsFile::LoggerMessage ********************* ******************************************************************************** */ OptionsFile::LoggerMessage::LoggerMessage (Msg msg, String fn) : fMsg (msg) , fFileName (fn) { } String OptionsFile::LoggerMessage::FormatMessage () const { switch (fMsg) { case Msg::eFailedToWriteFile: return Characters::Format (L"Failed to write file: %s", fFileName.Value ().c_str ()); case Msg::eFailedToReadFile: return Characters::Format (L"Failed to read file: %s", fFileName.Value ().c_str ()); case Msg::eFailedToParseReadFile: return Characters::Format (L"Error analyzing configuration file '%s' - using defaults.", fFileName.Value ().c_str ()); case Msg::eFailedToParseReadFileBadFormat: return Characters::Format (L"Error analyzing configuration file (because bad format) '%s' - using defaults.", fFileName.Value ().c_str ()); case Msg::eFailedToCompareReadFile: return Characters::Format (L"Failed to compare configuration file: %s", fFileName.Value ().c_str ()); case Msg::eWritingConfigFile_SoDefaultsEditable: return Characters::Format (L"Writing configuration file '%s' because not found (and so defaults are more easily seen and editable).", fFileName.Value ().c_str ()); case Msg::eWritingConfigFile_BecauseUpgraded: return Characters::Format (L"Writing configuration file '%s' in a new location because the software has been upgraded.", fFileName.Value ().c_str ()); case Msg::eWritingConfigFile_BecauseSomethingChanged: return Characters::Format (L"Writing configuration file '%s' because something changed (e.g. a default, or field added/removed).", fFileName.Value ().c_str ()); case Msg::eFailedToWriteInUseValues: return Characters::Format (L"Failed to write default (in use) values to file: %s", fFileName.Value ().c_str ()); default: RequireNotReached (); return String (); } } /* ******************************************************************************** ************************** DataExchange::OptionsFile *************************** ******************************************************************************** */ const OptionsFile::ModuleDataUpgraderType OptionsFile::kDefaultUpgrader = [] (const Memory::Optional<Configuration::Version>& version, const VariantValue& rawVariantValue) -> VariantValue { return rawVariantValue; }; const OptionsFile::LoggerType OptionsFile::kDefaultLogger = [] (const LoggerMessage& message) { using Execution::Logger; Logger::Priority priority = Logger::Priority::eError; using Msg = OptionsFile::LoggerMessage::Msg; switch (message.fMsg) { case Msg::eFailedToReadFile: priority = Logger::Priority::eWarning; // could be just because new system, no file break; case Msg::eWritingConfigFile_SoDefaultsEditable: case Msg::eWritingConfigFile_BecauseUpgraded: case Msg::eWritingConfigFile_BecauseSomethingChanged: priority = Logger::Priority::eInfo; break; case Msg::eFailedToParseReadFile: case Msg::eFailedToParseReadFileBadFormat: // Most likely very bad - as critical configuration data will be lost, and overwritten with 'defaults' priority = Logger::Priority::eCriticalError; break; } Logger::Get ().Log (priority, L"%s", message.FormatMessage ().c_str ()); }; const OptionsFile::ModuleNameToFileNameMapperType OptionsFile::mkFilenameMapper (const String& appName) { String useAppName = appName; return [useAppName] (const String & moduleName, const String & fileSuffix) -> String { return IO::FileSystem::WellKnownLocations::GetApplicationData() + useAppName + String (IO::FileSystem::kPathComponentSeperator) + moduleName + fileSuffix; } ; } const OptionsFile::ModuleNameToFileVersionMapperType OptionsFile::kDefaultModuleNameToFileVersionMapper = [] (const String& moduleName) -> Optional<Configuration::Version> { return Optional<Configuration::Version> (); // default to dont know }; // Consider using XML by default when more mature const VariantReader OptionsFile::kDefaultReader = JSON::Reader (); const VariantWriter OptionsFile::kDefaultWriter = JSON::Writer (); OptionsFile::OptionsFile ( const String& modName, const ObjectVariantMapper& mapper, ModuleDataUpgraderType moduleUpgrader, ModuleNameToFileNameMapperType moduleNameToFileNameMapper, ModuleNameToFileVersionMapperType moduleNameToReadFileVersion, LoggerType logger, VariantReader reader, VariantWriter writer ) : OptionsFile (modName, mapper, moduleUpgrader, moduleNameToFileNameMapper, moduleNameToFileNameMapper, moduleNameToReadFileVersion, logger, reader, writer, reader.GetDefaultFileSuffix ()) { } OptionsFile::OptionsFile ( const String& modName, const ObjectVariantMapper& mapper, ModuleDataUpgraderType moduleUpgrader, ModuleNameToFileNameMapperType moduleNameToReadFileNameMapper, ModuleNameToFileNameMapperType moduleNameToWriteFileNameMapper, ModuleNameToFileVersionMapperType moduleNameToReadFileVersion, LoggerType logger, VariantReader reader, VariantWriter writer ) : OptionsFile (modName, mapper, moduleUpgrader, moduleNameToReadFileNameMapper, moduleNameToWriteFileNameMapper, moduleNameToReadFileVersion, logger, reader, writer, reader.GetDefaultFileSuffix ()) { } OptionsFile::OptionsFile ( const String& modName, const ObjectVariantMapper& mapper, ModuleDataUpgraderType moduleUpgrader, ModuleNameToFileNameMapperType moduleNameToReadFileNameMapper, ModuleNameToFileNameMapperType moduleNameToWriteFileNameMapper, ModuleNameToFileVersionMapperType moduleNameToReadFileVersion, LoggerType logger, VariantReader reader, VariantWriter writer, const String& fileSuffix ) : fModuleName_ (modName) , fMapper_ (mapper) , fModuleDataUpgrader_ (moduleUpgrader) , fModuleNameToReadFileNameMapper_ (moduleNameToReadFileNameMapper) , fModuleNameToWriteFileNameMapper_ (moduleNameToWriteFileNameMapper) , fModuleNameToFileVersionMapper_ (moduleNameToReadFileVersion) , fLogger_ (logger) , fReader_ (reader) , fWriter_ (writer) , fFileSuffix_ (fileSuffix) { } BLOB OptionsFile::ReadRaw () const { Debug::TraceContextBumper ctx ("OptionsFile::ReadRaw"); #if USE_NOISY_TRACE_IN_THIS_MODULE_ DbgTrace (L"(readfilename=%s)", GetReadFilePath_ ().c_str ()); #endif return IO::FileSystem::FileInputStream::mk (GetReadFilePath_ ()).ReadAll (); } void OptionsFile::WriteRaw (const BLOB& blob) { Debug::TraceContextBumper ctx ("OptionsFile::WriteRaw"); #if USE_NOISY_TRACE_IN_THIS_MODULE_ DbgTrace (L"(writefilename=%s)", GetWriteFilePath_ ().c_str ()); #endif if (GetReadFilePath_ () == GetWriteFilePath_ ()) { try { if (ReadRaw () == blob) { return; } } catch (...) { // No matter why we fail, nevermind. Just fall through and write. } } try { IO::FileSystem::ThroughTmpFileWriter tmpFile (GetWriteFilePath_ ()); IO::FileSystem::FileOutputStream outStream (tmpFile.GetFilePath ()); outStream.Write (blob); outStream.Flush (); outStream.clear (); // so any errors can be displayed as exceptions, and so closed before commit/rename tmpFile.Commit (); } catch (...) { fLogger_ (LoggerMessage (LoggerMessage::Msg::eFailedToWriteFile, GetWriteFilePath_ ())); } } template <> Optional<VariantValue> OptionsFile::Read () { Debug::TraceContextBumper ctx ("OptionsFile::Read"); try { Optional<VariantValue> r = fReader_.Read (MemoryStream<Byte> (ReadRaw ())); if (r.IsPresent ()) { r = fModuleDataUpgrader_ (fModuleNameToFileVersionMapper_ (fModuleName_), *r); } return r; } catch (...) { // @todo - check different exception cases and for some - like file not found - just no warning... fLogger_ (LoggerMessage (LoggerMessage::Msg::eFailedToReadFile, GetReadFilePath_ ())); return Optional<VariantValue> (); } } template <> void OptionsFile::Write (const VariantValue& optionsObject) { Debug::TraceContextBumper ctx ("OptionsFile::Write"); MemoryStream<Byte> tmp; fWriter_.Write (optionsObject, tmp); WriteRaw (tmp.As<BLOB> ()); } String OptionsFile::GetReadFilePath_ () const { return fModuleNameToReadFileNameMapper_ (fModuleName_, fFileSuffix_); } String OptionsFile::GetWriteFilePath_ () const { return fModuleNameToWriteFileNameMapper_ (fModuleName_, fFileSuffix_); } <|endoftext|>
<commit_before>#include "TM0Cylindrical.h" template<> InputParameters validParams<TM0Cylindrical>() { InputParameters params = validParams<Kernel>(); // params.addRequiredParam<Real>("position_units", "Units of position."); params.addRequiredParam<Real>("f", "The drive frequency."); params.addParam<Real>("eps_r", 1., "The relative permittivity of the medium."); return params; } TM0Cylindrical::TM0Cylindrical(const InputParameters & parameters) : Kernel(parameters), // _r_units(1. / getParam<Real>("position_units")), _omega(2. * libMesh::pi * getParam<Real>("f")), _eps_r(getParam<Real>("eps_r")), _mu0(4. * libMesh::pi * 1e-7), _eps0(8.85e-12) { } TM0Cylindrical::~TM0Cylindrical() { } Real TM0Cylindrical::computeQpResidual() { return -_grad_test[_i][_qp] * _grad_u[_qp] - _test[_i][_qp] * _u[_qp] / std::pow(_q_point[_qp](0), 2) + _test[_i][_qp] * std::pow(_omega, 2) * _mu0 * _eps_r * _eps0 * _u[_qp]; } Real TM0Cylindrical::computeQpJacobian() { return -_grad_test[_i][_qp] * _grad_phi[_j][_qp] - _test[_i][_qp] * _phi[_j][_qp] / std::pow(_q_point[_qp](0), 2) + _test[_i][_qp] * std::pow(_omega, 2) * _mu0 * _eps_r * _eps0 * _phi[_j][_qp]; } <commit_msg>Possible error in dielectric formulation.<commit_after>#include "TM0Cylindrical.h" template<> InputParameters validParams<TM0Cylindrical>() { InputParameters params = validParams<Kernel>(); // params.addRequiredParam<Real>("position_units", "Units of position."); params.addRequiredParam<Real>("f", "The drive frequency."); params.addParam<Real>("eps_r", 1., "The relative permittivity of the medium."); return params; } TM0Cylindrical::TM0Cylindrical(const InputParameters & parameters) : Kernel(parameters), // _r_units(1. / getParam<Real>("position_units")), _omega(2. * libMesh::pi * getParam<Real>("f")), _eps_r(getParam<Real>("eps_r")), _mu0(4. * libMesh::pi * 1e-7), _eps0(8.85e-12) { } TM0Cylindrical::~TM0Cylindrical() { } Real TM0Cylindrical::computeQpResidual() { return -_grad_test[_i][_qp] * _grad_u[_qp] / _eps_r - _test[_i][_qp] * _u[_qp] / std::pow(_q_point[_qp](0), 2) / _eps_r + _test[_i][_qp] * std::pow(_omega, 2) * _mu0 * _eps_r * _eps0 * _u[_qp]; } Real TM0Cylindrical::computeQpJacobian() { return -_grad_test[_i][_qp] * _grad_phi[_j][_qp] / _eps_r - _test[_i][_qp] * _phi[_j][_qp] / std::pow(_q_point[_qp](0), 2) / _eps_r + _test[_i][_qp] * std::pow(_omega, 2) * _mu0 * _eps_r * _eps0 * _phi[_j][_qp]; } <|endoftext|>
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include <mitkImageToUnstructuredGridFilter.h> #include <vtkSmartPointer.h> #include <vtkPoints.h> #include <vtkUnstructuredGrid.h> #include <vtkPolyVertex.h> #include <itkImageRegionIterator.h> #include <mitkImageAccessByItk.h> mitk::ImageToUnstructuredGridFilter::ImageToUnstructuredGridFilter(): m_NumberOfExtractedPoints(0), m_Threshold(-0.1) { this->m_UnstructGrid = mitk::UnstructuredGrid::New(); } mitk::ImageToUnstructuredGridFilter::~ImageToUnstructuredGridFilter(){} void mitk::ImageToUnstructuredGridFilter::GenerateData() { mitk::UnstructuredGrid::Pointer unstructGrid = this->GetOutput(); const mitk::Image* image = this->GetInput(); if(image == nullptr || !image->IsInitialized()) { MITK_ERROR << "Wrong input image set" << std::endl; return; } m_Geometry = image->GetGeometry(); m_NumberOfExtractedPoints = 0; AccessByItk(image, ExtractPoints) } void mitk::ImageToUnstructuredGridFilter::SetInput(const mitk::Image* image) { this->ProcessObject::SetNthInput(0, const_cast< mitk::Image* >( image ) ); } const mitk::Image* mitk::ImageToUnstructuredGridFilter::GetInput(void) const { return this->GetInput(); } mitk::Image* mitk::ImageToUnstructuredGridFilter::GetInput(void) { if (this->GetNumberOfInputs() < 1) { MITK_ERROR << "No input set" << std::endl; return nullptr; } return static_cast< mitk::Image* >( this->ProcessObject::GetInput(0) ); } template<typename TPixel, unsigned int VImageDimension> void mitk::ImageToUnstructuredGridFilter:: ExtractPoints(const itk::Image<TPixel, VImageDimension>* image) { typedef itk::Image<TPixel, VImageDimension> InputImageType; typename itk::ImageRegionConstIterator<InputImageType> it(image, image->GetRequestedRegion()); vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New(); it.GoToBegin(); while( !it.IsAtEnd() ) { if(it.Get() >= m_Threshold) { mitk::Point3D imagePoint; mitk::Point3D worldPoint; imagePoint[0] = it.GetIndex()[0]; imagePoint[1] = it.GetIndex()[1]; imagePoint[2] = it.GetIndex()[2]; m_Geometry->IndexToWorld(imagePoint, worldPoint); points->InsertNextPoint(worldPoint[0],worldPoint[1],worldPoint[2]); m_NumberOfExtractedPoints++; } ++it; } vtkSmartPointer<vtkPolyVertex> verts = vtkSmartPointer<vtkPolyVertex>::New(); verts->GetPointIds()->SetNumberOfIds(m_NumberOfExtractedPoints); for(int i=0; i<m_NumberOfExtractedPoints; i++) { verts->GetPointIds()->SetId(i,i); } vtkSmartPointer<vtkUnstructuredGrid> uGrid = vtkSmartPointer<vtkUnstructuredGrid>::New(); uGrid->Allocate(1); uGrid->InsertNextCell(verts->GetCellType(), verts->GetPointIds()); uGrid->SetPoints(points); m_UnstructGrid->SetVtkUnstructuredGrid(uGrid); } void mitk::ImageToUnstructuredGridFilter::SetThreshold(double threshold) { this->m_Threshold = threshold; } double mitk::ImageToUnstructuredGridFilter::GetThreshold() { return this->m_Threshold; } void mitk::ImageToUnstructuredGridFilter::GenerateOutputInformation() { mitk::Image::ConstPointer inputImage = this->GetInput(); m_UnstructGrid = this->GetOutput(); itkDebugMacro(<<"GenerateOutputInformation()"); if(inputImage.IsNull()) return; } <commit_msg>Fixed build error on windows<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include <mitkImageToUnstructuredGridFilter.h> #include <vtkSmartPointer.h> #include <vtkPoints.h> #include <vtkUnstructuredGrid.h> #include <vtkPolyVertex.h> #include <itkImageRegionIterator.h> #include <mitkImageAccessByItk.h> mitk::ImageToUnstructuredGridFilter::ImageToUnstructuredGridFilter(): m_NumberOfExtractedPoints(0), m_Threshold(-0.1) { this->m_UnstructGrid = mitk::UnstructuredGrid::New(); } mitk::ImageToUnstructuredGridFilter::~ImageToUnstructuredGridFilter(){} void mitk::ImageToUnstructuredGridFilter::GenerateData() { mitk::UnstructuredGrid::Pointer unstructGrid = this->GetOutput(); const mitk::Image* image = this->GetInput(); if(image == nullptr || !image->IsInitialized()) { MITK_ERROR << "Wrong input image set" << std::endl; return; } m_Geometry = image->GetGeometry(); m_NumberOfExtractedPoints = 0; AccessByItk(image, ExtractPoints) } void mitk::ImageToUnstructuredGridFilter::SetInput(const mitk::Image* image) { this->ProcessObject::SetNthInput(0, const_cast< mitk::Image* >( image ) ); } const mitk::Image* mitk::ImageToUnstructuredGridFilter::GetInput(void) const { if (this->GetNumberOfInputs() < 1) { MITK_ERROR << "No input set" << std::endl; return nullptr; } return static_cast<const mitk::Image* >(this->ProcessObject::GetInput(0)); } mitk::Image* mitk::ImageToUnstructuredGridFilter::GetInput(void) { if (this->GetNumberOfInputs() < 1) { MITK_ERROR << "No input set" << std::endl; return nullptr; } return static_cast< mitk::Image* >( this->ProcessObject::GetInput(0) ); } template<typename TPixel, unsigned int VImageDimension> void mitk::ImageToUnstructuredGridFilter:: ExtractPoints(const itk::Image<TPixel, VImageDimension>* image) { typedef itk::Image<TPixel, VImageDimension> InputImageType; typename itk::ImageRegionConstIterator<InputImageType> it(image, image->GetRequestedRegion()); vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New(); it.GoToBegin(); while( !it.IsAtEnd() ) { if(it.Get() >= m_Threshold) { mitk::Point3D imagePoint; mitk::Point3D worldPoint; imagePoint[0] = it.GetIndex()[0]; imagePoint[1] = it.GetIndex()[1]; imagePoint[2] = it.GetIndex()[2]; m_Geometry->IndexToWorld(imagePoint, worldPoint); points->InsertNextPoint(worldPoint[0],worldPoint[1],worldPoint[2]); m_NumberOfExtractedPoints++; } ++it; } vtkSmartPointer<vtkPolyVertex> verts = vtkSmartPointer<vtkPolyVertex>::New(); verts->GetPointIds()->SetNumberOfIds(m_NumberOfExtractedPoints); for(int i=0; i<m_NumberOfExtractedPoints; i++) { verts->GetPointIds()->SetId(i,i); } vtkSmartPointer<vtkUnstructuredGrid> uGrid = vtkSmartPointer<vtkUnstructuredGrid>::New(); uGrid->Allocate(1); uGrid->InsertNextCell(verts->GetCellType(), verts->GetPointIds()); uGrid->SetPoints(points); m_UnstructGrid->SetVtkUnstructuredGrid(uGrid); } void mitk::ImageToUnstructuredGridFilter::SetThreshold(double threshold) { this->m_Threshold = threshold; } double mitk::ImageToUnstructuredGridFilter::GetThreshold() { return this->m_Threshold; } void mitk::ImageToUnstructuredGridFilter::GenerateOutputInformation() { mitk::Image::ConstPointer inputImage = this->GetInput(); m_UnstructGrid = this->GetOutput(); itkDebugMacro(<<"GenerateOutputInformation()"); if(inputImage.IsNull()) return; } <|endoftext|>
<commit_before>/* -------------------------------------------------------------------------- * * OpenSim: ConstantDistanceConstraint.cpp * * -------------------------------------------------------------------------- * * The OpenSim API is a toolkit for musculoskeletal modeling and simulation. * * See http://opensim.stanford.edu and the NOTICE file for more information. * * OpenSim is developed at Stanford University and supported by the US * * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA * * through the Warrior Web program. * * * * Copyright (c) 2005-2012 Stanford University and the Authors * * Author(s): Matt S. DeMers * * * * 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. * * -------------------------------------------------------------------------- */ //============================================================================= // INCLUDES //============================================================================= #include <iostream> #include <math.h> #include <OpenSim/Common/Function.h> #include <OpenSim/Common/Constant.h> #include <OpenSim/Simulation/Model/BodySet.h> #include <OpenSim/Simulation/Model/Model.h> #include "ConstantDistanceConstraint.h" #include "SimbodyEngine.h" //============================================================================= // STATICS //============================================================================= using namespace std; using namespace SimTK; using namespace OpenSim; //============================================================================= // CONSTRUCTOR(S) AND DESTRUCTOR //============================================================================= //_____________________________________________________________________________ /** * Destructor. */ ConstantDistanceConstraint::~ConstantDistanceConstraint() { } //============================================================================= // CONSTRUCTION //============================================================================= /* Default constructor. */ ConstantDistanceConstraint::ConstantDistanceConstraint() : Constraint() { setNull(); constructInfrastructure(); } /* * Convenience Constructor. */ ConstantDistanceConstraint::ConstantDistanceConstraint( const PhysicalFrame& body1, const SimTK::Vec3& locationBody1, const PhysicalFrame& body2, const SimTK::Vec3& locationBody2, const double& distance) : Constraint() { setNull(); constructInfrastructure(); setBody1ByName(body1.getName()); setBody2ByName(body2.getName()); set_location_body_1(locationBody1); set_location_body_2(locationBody2); set_constant_distance(distance); } /* Set the data members of this ConstantDistanceConstraint to their null values. */ void ConstantDistanceConstraint::setNull() { setAuthors("Matt S. DeMers"); } //_____________________________________________________________________________ /** * Connect properties to local pointers. */ void ConstantDistanceConstraint::constructProperties() { //Default location and orientation (rotation sequence) SimTK::Vec3 origin(0.0, 0.0, 0.0); constructProperty_location_body_1(origin); constructProperty_location_body_2(origin); // Constant distance between points constructProperty_constant_distance(SimTK::NaN); } void ConstantDistanceConstraint::constructConnectors() { constructConnector<PhysicalFrame>("body_1"); constructConnector<PhysicalFrame>("body_2"); } void ConstantDistanceConstraint::extendAddToSystem(SimTK::MultibodySystem& system) const { Super::extendAddToSystem(system); // Get underlying mobilized bodies const PhysicalFrame& f1 = getConnectee<PhysicalFrame>("body_1"); const PhysicalFrame& f2 = getConnectee<PhysicalFrame>("body_2"); SimTK::MobilizedBody b1 = f1.getMobilizedBody(); SimTK::MobilizedBody b2 = f2.getMobilizedBody(); // Now create a Simbody Constraint::Rod SimTK::Constraint::Rod simtkRod(b1, get_location_body_1(), b2, get_location_body_2(), get_constant_distance() ); // Beyond the const Component get the index so we can access the SimTK::Constraint later assignConstraintIndex(simtkRod.getConstraintIndex()); } //============================================================================= // GET/SET //============================================================================= const PhysicalFrame& ConstantDistanceConstraint::getBody1() const { return getConnectee<Body>("body_1"); } const PhysicalFrame& ConstantDistanceConstraint::getBody2() const { return getConnectee<PhysicalFrame>("body_2"); } /* * Following methods set attributes of the constraint */ void ConstantDistanceConstraint::setBody1ByName(const std::string& aBodyName) { updConnector<PhysicalFrame>("body_1").set_connectee_name(aBodyName); } void ConstantDistanceConstraint::setBody2ByName(const std::string& aBodyName) { updConnector<PhysicalFrame>("body_2").set_connectee_name(aBodyName); } /** Set the location for point on body 1*/ void ConstantDistanceConstraint::setBody1PointLocation(Vec3 location) { set_location_body_1(location); } /** Set the location for point on body 2*/ void ConstantDistanceConstraint::setBody2PointLocation(Vec3 location) { set_location_body_2(location); } /** Set the constant distance between the two points*/ void ConstantDistanceConstraint::setConstantDistance(double distance) { set_constant_distance(distance); } void ConstantDistanceConstraint::updateFromXMLNode(SimTK::Xml::Element& aNode, int versionNumber) { int documentVersion = versionNumber; if (documentVersion < XMLDocument::getLatestVersion()){ if (documentVersion<30500){ // replace old properties with latest use of Connectors SimTK::Xml::element_iterator body1Element = aNode.element_begin("body_1"); SimTK::Xml::element_iterator body2Element = aNode.element_begin("body_2"); std::string body1_name(""), body2_name(""); // If default constructed then elements not serialized since they are default // values. Check that we have associated elements, then extract their values. if (body1Element != aNode.element_end()) body1Element->getValueAs<std::string>(body1_name); if (body2Element != aNode.element_end()) body2Element->getValueAs<std::string>(body2_name); XMLDocument::addConnector(aNode, "Connector_PhysicalFrame_", "body_1", body1_name); XMLDocument::addConnector(aNode, "Connector_PhysicalFrame_", "body_2", body2_name); } } Super::updateFromXMLNode(aNode, versionNumber); }// Visual support ConstantDistanceConstraint drawing in SimTK visualizer. void ConstantDistanceConstraint::generateDecorations( bool fixed, const ModelDisplayHints& hints, const SimTK::State& state, SimTK::Array_<SimTK::DecorativeGeometry>& appendToThis) const { Super::generateDecorations(fixed, hints, state, appendToThis); if (fixed) return; const Vec3 pink(1, .6, .8); const OpenSim::PhysicalFrame& frame1 = getBody1(); const Vec3& p_B1 = frame1.getGroundTransform(state)*get_location_body_1(); const OpenSim::PhysicalFrame& frame2 = getBody2(); const Vec3& p_B2 = frame2.getGroundTransform(state)*get_location_body_2(); appendToThis.push_back( SimTK::DecorativeLine(p_B1, p_B2).setBodyId(0) .setColor(pink).setOpacity(1.0).setLineThickness(.05)); } <commit_msg>Fixed incorrect template argument for ConstantDistanceConstraint getConnectee<>- should be PhysicalFrame instead of Body. Was only causing build failure in debug.<commit_after>/* -------------------------------------------------------------------------- * * OpenSim: ConstantDistanceConstraint.cpp * * -------------------------------------------------------------------------- * * The OpenSim API is a toolkit for musculoskeletal modeling and simulation. * * See http://opensim.stanford.edu and the NOTICE file for more information. * * OpenSim is developed at Stanford University and supported by the US * * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA * * through the Warrior Web program. * * * * Copyright (c) 2005-2012 Stanford University and the Authors * * Author(s): Matt S. DeMers * * * * 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. * * -------------------------------------------------------------------------- */ //============================================================================= // INCLUDES //============================================================================= #include <iostream> #include <math.h> #include <OpenSim/Common/Function.h> #include <OpenSim/Common/Constant.h> #include <OpenSim/Simulation/Model/BodySet.h> #include <OpenSim/Simulation/Model/Model.h> #include "ConstantDistanceConstraint.h" #include "SimbodyEngine.h" //============================================================================= // STATICS //============================================================================= using namespace std; using namespace SimTK; using namespace OpenSim; //============================================================================= // CONSTRUCTOR(S) AND DESTRUCTOR //============================================================================= //_____________________________________________________________________________ /** * Destructor. */ ConstantDistanceConstraint::~ConstantDistanceConstraint() { } //============================================================================= // CONSTRUCTION //============================================================================= /* Default constructor. */ ConstantDistanceConstraint::ConstantDistanceConstraint() : Constraint() { setNull(); constructInfrastructure(); } /* * Convenience Constructor. */ ConstantDistanceConstraint::ConstantDistanceConstraint( const PhysicalFrame& body1, const SimTK::Vec3& locationBody1, const PhysicalFrame& body2, const SimTK::Vec3& locationBody2, const double& distance) : Constraint() { setNull(); constructInfrastructure(); setBody1ByName(body1.getName()); setBody2ByName(body2.getName()); set_location_body_1(locationBody1); set_location_body_2(locationBody2); set_constant_distance(distance); } /* Set the data members of this ConstantDistanceConstraint to their null values. */ void ConstantDistanceConstraint::setNull() { setAuthors("Matt S. DeMers"); } //_____________________________________________________________________________ /** * Connect properties to local pointers. */ void ConstantDistanceConstraint::constructProperties() { //Default location and orientation (rotation sequence) SimTK::Vec3 origin(0.0, 0.0, 0.0); constructProperty_location_body_1(origin); constructProperty_location_body_2(origin); // Constant distance between points constructProperty_constant_distance(SimTK::NaN); } void ConstantDistanceConstraint::constructConnectors() { constructConnector<PhysicalFrame>("body_1"); constructConnector<PhysicalFrame>("body_2"); } void ConstantDistanceConstraint::extendAddToSystem(SimTK::MultibodySystem& system) const { Super::extendAddToSystem(system); // Get underlying mobilized bodies const PhysicalFrame& f1 = getConnectee<PhysicalFrame>("body_1"); const PhysicalFrame& f2 = getConnectee<PhysicalFrame>("body_2"); SimTK::MobilizedBody b1 = f1.getMobilizedBody(); SimTK::MobilizedBody b2 = f2.getMobilizedBody(); // Now create a Simbody Constraint::Rod SimTK::Constraint::Rod simtkRod(b1, get_location_body_1(), b2, get_location_body_2(), get_constant_distance() ); // Beyond the const Component get the index so we can access the SimTK::Constraint later assignConstraintIndex(simtkRod.getConstraintIndex()); } //============================================================================= // GET/SET //============================================================================= const PhysicalFrame& ConstantDistanceConstraint::getBody1() const { return getConnectee<PhysicalFrame>("body_1"); } const PhysicalFrame& ConstantDistanceConstraint::getBody2() const { return getConnectee<PhysicalFrame>("body_2"); } /* * Following methods set attributes of the constraint */ void ConstantDistanceConstraint::setBody1ByName(const std::string& aBodyName) { updConnector<PhysicalFrame>("body_1").set_connectee_name(aBodyName); } void ConstantDistanceConstraint::setBody2ByName(const std::string& aBodyName) { updConnector<PhysicalFrame>("body_2").set_connectee_name(aBodyName); } /** Set the location for point on body 1*/ void ConstantDistanceConstraint::setBody1PointLocation(Vec3 location) { set_location_body_1(location); } /** Set the location for point on body 2*/ void ConstantDistanceConstraint::setBody2PointLocation(Vec3 location) { set_location_body_2(location); } /** Set the constant distance between the two points*/ void ConstantDistanceConstraint::setConstantDistance(double distance) { set_constant_distance(distance); } void ConstantDistanceConstraint::updateFromXMLNode(SimTK::Xml::Element& aNode, int versionNumber) { int documentVersion = versionNumber; if (documentVersion < XMLDocument::getLatestVersion()){ if (documentVersion<30500){ // replace old properties with latest use of Connectors SimTK::Xml::element_iterator body1Element = aNode.element_begin("body_1"); SimTK::Xml::element_iterator body2Element = aNode.element_begin("body_2"); std::string body1_name(""), body2_name(""); // If default constructed then elements not serialized since they are default // values. Check that we have associated elements, then extract their values. if (body1Element != aNode.element_end()) body1Element->getValueAs<std::string>(body1_name); if (body2Element != aNode.element_end()) body2Element->getValueAs<std::string>(body2_name); XMLDocument::addConnector(aNode, "Connector_PhysicalFrame_", "body_1", body1_name); XMLDocument::addConnector(aNode, "Connector_PhysicalFrame_", "body_2", body2_name); } } Super::updateFromXMLNode(aNode, versionNumber); }// Visual support ConstantDistanceConstraint drawing in SimTK visualizer. void ConstantDistanceConstraint::generateDecorations( bool fixed, const ModelDisplayHints& hints, const SimTK::State& state, SimTK::Array_<SimTK::DecorativeGeometry>& appendToThis) const { Super::generateDecorations(fixed, hints, state, appendToThis); if (fixed) return; const Vec3 pink(1, .6, .8); const OpenSim::PhysicalFrame& frame1 = getBody1(); const Vec3& p_B1 = frame1.getGroundTransform(state)*get_location_body_1(); const OpenSim::PhysicalFrame& frame2 = getBody2(); const Vec3& p_B2 = frame2.getGroundTransform(state)*get_location_body_2(); appendToThis.push_back( SimTK::DecorativeLine(p_B1, p_B2).setBodyId(0) .setColor(pink).setOpacity(1.0).setLineThickness(.05)); } <|endoftext|>
<commit_before>/* * Copyright (c) 2016 dresden elektronik ingenieurtechnik gmbh. * All rights reserved. * * The software in this package is published under the terms of the BSD * style license a copy of which has been included with this distribution in * the LICENSE.txt file. * */ #include "de_web_plugin.h" #include "de_web_plugin_private.h" /*! Inits permit join manager. The manager will observe and ensure the global permit join state. */ void DeRestPluginPrivate::initPermitJoin() { permitJoinFlag = false; permitJoinTimer = new QTimer(this); permitJoinTimer->setSingleShot(false); connect(permitJoinTimer, SIGNAL(timeout()), this, SLOT(permitJoinTimerFired())); permitJoinTimer->start(1000); permitJoinLastSendTime = QTime::currentTime(); resendPermitJoinTimer = new QTimer(this); resendPermitJoinTimer->setSingleShot(true); connect(resendPermitJoinTimer, SIGNAL(timeout()), this, SLOT(resendPermitJoinTimerFired())); } /*! Sets the permit join interval \param duration specifies the interval in which joining is enabled - 0 disabled - 1..254 duration in seconds until joining will be disabled - 255 always permit * \return */ bool DeRestPluginPrivate::setPermitJoinDuration(uint8_t duration) { if (gwPermitJoinDuration != duration) { gwPermitJoinDuration = duration; } // force resend permitJoinLastSendTime = QTime(); return true; } /*! Handle broadcasting of permit join interval. This is done every PERMIT_JOIN_SEND_INTERVAL to ensure any node in the network has the same settings. */ void DeRestPluginPrivate::permitJoinTimerFired() { Q_Q(DeRestPlugin); if (!q->pluginActive()) { return; } if ((gwPermitJoinDuration > 0) && (gwPermitJoinDuration < 255)) { permitJoinFlag = true; gwPermitJoinDuration--; updateEtag(gwConfigEtag); // update Etag so that webApp can count down permitJoin duration //periodically check if there are deleted lights and undelete them if (gwPermitJoinDuration % 10 == 0) { std::vector<LightNode>::iterator i = nodes.begin(); std::vector<LightNode>::iterator end = nodes.end(); for (; i != end; ++i) { if (i->state() == LightNode::StateDeleted) { if (i->isAvailable()) { i->setState(LightNode::StateNormal); i->setNeedSaveDatabase(true); queSaveDb(DB_LIGHTS, DB_SHORT_SAVE_DELAY); } } } } } if (gwPermitJoinDuration == 0 && permitJoinFlag) { permitJoinFlag = false; } if (!isInNetwork()) { return; } if (gwPermitJoinDuration == 0 && otauLastBusyTimeDelta() < (60 * 5)) { // don't pollute channel while OTA is running return; } QTime now = QTime::currentTime(); int diff = permitJoinLastSendTime.msecsTo(now); if (!permitJoinLastSendTime.isValid() || (diff > PERMIT_JOIN_SEND_INTERVAL)) { deCONZ::ApsDataRequest apsReq; quint8 tcSignificance = 0x01; apsReq.setDstAddressMode(deCONZ::ApsNwkAddress); apsReq.dstAddress().setNwk(deCONZ::BroadcastRouters); apsReq.setProfileId(ZDP_PROFILE_ID); apsReq.setClusterId(ZDP_MGMT_PERMIT_JOINING_REQ_CLID); apsReq.setDstEndpoint(ZDO_ENDPOINT); apsReq.setSrcEndpoint(ZDO_ENDPOINT); apsReq.setTxOptions(0); apsReq.setRadius(0); QDataStream stream(&apsReq.asdu(), QIODevice::WriteOnly); stream.setByteOrder(QDataStream::LittleEndian); stream << (uint8_t)now.second(); // seqno stream << gwPermitJoinDuration; stream << tcSignificance; DBG_Assert(apsCtrl != 0); if (!apsCtrl) { return; } // set for own node apsCtrl->setPermitJoin(gwPermitJoinDuration); // broadcast if (apsCtrl->apsdeDataRequest(apsReq) == deCONZ::Success) { DBG_Printf(DBG_INFO, "send permit join, duration: %d\n", gwPermitJoinDuration); permitJoinLastSendTime = now; } else { DBG_Printf(DBG_INFO, "send permit join failed\n"); } } } /*! Check if permitJoin is > 60 seconds then resend permitjoin with 60 seconds */ void DeRestPluginPrivate::resendPermitJoinTimerFired() { resendPermitJoinTimer->stop(); if (gwPermitJoinDuration <= 1) { if (gwPermitJoinResend > 0) { if (gwPermitJoinResend >= 60) { setPermitJoinDuration(60); } else { setPermitJoinDuration(gwPermitJoinResend); } gwPermitJoinResend -= 60; updateEtag(gwConfigEtag); if (gwPermitJoinResend <= 0) { gwPermitJoinResend = 0; return; } } else if (gwPermitJoinResend == 0) { setPermitJoinDuration(0); return; } } else if (gwPermitJoinResend == 0) { setPermitJoinDuration(0); return; } resendPermitJoinTimer->start(1000); } <commit_msg>Check apsCtrl in permitJoinTimerFired()<commit_after>/* * Copyright (c) 2016 dresden elektronik ingenieurtechnik gmbh. * All rights reserved. * * The software in this package is published under the terms of the BSD * style license a copy of which has been included with this distribution in * the LICENSE.txt file. * */ #include "de_web_plugin.h" #include "de_web_plugin_private.h" /*! Inits permit join manager. The manager will observe and ensure the global permit join state. */ void DeRestPluginPrivate::initPermitJoin() { permitJoinFlag = false; permitJoinTimer = new QTimer(this); permitJoinTimer->setSingleShot(false); connect(permitJoinTimer, SIGNAL(timeout()), this, SLOT(permitJoinTimerFired())); permitJoinTimer->start(1000); permitJoinLastSendTime = QTime::currentTime(); resendPermitJoinTimer = new QTimer(this); resendPermitJoinTimer->setSingleShot(true); connect(resendPermitJoinTimer, SIGNAL(timeout()), this, SLOT(resendPermitJoinTimerFired())); } /*! Sets the permit join interval \param duration specifies the interval in which joining is enabled - 0 disabled - 1..254 duration in seconds until joining will be disabled - 255 always permit * \return */ bool DeRestPluginPrivate::setPermitJoinDuration(uint8_t duration) { if (gwPermitJoinDuration != duration) { gwPermitJoinDuration = duration; } // force resend permitJoinLastSendTime = QTime(); return true; } /*! Handle broadcasting of permit join interval. This is done every PERMIT_JOIN_SEND_INTERVAL to ensure any node in the network has the same settings. */ void DeRestPluginPrivate::permitJoinTimerFired() { Q_Q(DeRestPlugin); if (!q->pluginActive() || !apsCtrl) { return; } if ((gwPermitJoinDuration > 0) && (gwPermitJoinDuration < 255)) { permitJoinFlag = true; gwPermitJoinDuration--; updateEtag(gwConfigEtag); // update Etag so that webApp can count down permitJoin duration //periodically check if there are deleted lights and undelete them if (gwPermitJoinDuration % 10 == 0) { std::vector<LightNode>::iterator i = nodes.begin(); std::vector<LightNode>::iterator end = nodes.end(); for (; i != end; ++i) { if (i->state() == LightNode::StateDeleted) { if (i->isAvailable()) { i->setState(LightNode::StateNormal); i->setNeedSaveDatabase(true); queSaveDb(DB_LIGHTS, DB_SHORT_SAVE_DELAY); } } } } } if (gwPermitJoinDuration == 0 && permitJoinFlag) { permitJoinFlag = false; } if (!isInNetwork()) { return; } if (gwPermitJoinDuration == 0 && otauLastBusyTimeDelta() < (60 * 5)) { // don't pollute channel while OTA is running return; } QTime now = QTime::currentTime(); int diff = permitJoinLastSendTime.msecsTo(now); if (!permitJoinLastSendTime.isValid() || (diff > PERMIT_JOIN_SEND_INTERVAL)) { deCONZ::ApsDataRequest apsReq; quint8 tcSignificance = 0x01; apsReq.setDstAddressMode(deCONZ::ApsNwkAddress); apsReq.dstAddress().setNwk(deCONZ::BroadcastRouters); apsReq.setProfileId(ZDP_PROFILE_ID); apsReq.setClusterId(ZDP_MGMT_PERMIT_JOINING_REQ_CLID); apsReq.setDstEndpoint(ZDO_ENDPOINT); apsReq.setSrcEndpoint(ZDO_ENDPOINT); apsReq.setTxOptions(0); apsReq.setRadius(0); QDataStream stream(&apsReq.asdu(), QIODevice::WriteOnly); stream.setByteOrder(QDataStream::LittleEndian); stream << (uint8_t)now.second(); // seqno stream << gwPermitJoinDuration; stream << tcSignificance; DBG_Assert(apsCtrl != 0); if (!apsCtrl) { return; } // set for own node apsCtrl->setPermitJoin(gwPermitJoinDuration); // broadcast if (apsCtrl->apsdeDataRequest(apsReq) == deCONZ::Success) { DBG_Printf(DBG_INFO, "send permit join, duration: %d\n", gwPermitJoinDuration); permitJoinLastSendTime = now; } else { DBG_Printf(DBG_INFO, "send permit join failed\n"); } } } /*! Check if permitJoin is > 60 seconds then resend permitjoin with 60 seconds */ void DeRestPluginPrivate::resendPermitJoinTimerFired() { resendPermitJoinTimer->stop(); if (gwPermitJoinDuration <= 1) { if (gwPermitJoinResend > 0) { if (gwPermitJoinResend >= 60) { setPermitJoinDuration(60); } else { setPermitJoinDuration(gwPermitJoinResend); } gwPermitJoinResend -= 60; updateEtag(gwConfigEtag); if (gwPermitJoinResend <= 0) { gwPermitJoinResend = 0; return; } } else if (gwPermitJoinResend == 0) { setPermitJoinDuration(0); return; } } else if (gwPermitJoinResend == 0) { setPermitJoinDuration(0); return; } resendPermitJoinTimer->start(1000); } <|endoftext|>
<commit_before>/* Copyright (c) 2007, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author 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 <libtorrent/natpmp.hpp> #include <libtorrent/io.hpp> #include <boost/bind.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <asio/ip/host_name.hpp> using boost::bind; using namespace libtorrent; using boost::posix_time::microsec_clock; natpmp::natpmp(io_service& ios, portmap_callback_t const& cb) : m_callback(cb) , m_currently_mapping(-1) , m_retry_count(0) , m_socket(ios) , m_send_timer(ios) , m_refresh_timer(ios) , m_disabled(false) { m_mappings[0].protocol = 2; // tcp m_mappings[1].protocol = 1; // udp #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log.open("natpmp.log", std::ios::in | std::ios::out | std::ios::trunc); #endif udp::resolver r(ios); udp::resolver::iterator i = r.resolve(udp::resolver::query(asio::ip::host_name(), "0")); for (;i != udp::resolver_iterator(); ++i) { if (i->endpoint().address().is_v4()) break; } if (i == udp::resolver_iterator()) { #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << "local host name did not resolve to an IPv4 address. " "disabling NAT-PMP" << std::endl; #endif m_disabled = true; return; } address_v4 local = i->endpoint().address().to_v4(); #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << to_simple_string(microsec_clock::universal_time()) << " local ip: " << local.to_string() << std::endl; #endif if ((local.to_ulong() & 0xff000000) != 0x0a000000 && (local.to_ulong() & 0xfff00000) != 0xac100000 && (local.to_ulong() & 0xffff0000) != 0xaca80000) { // the local address seems to be an external // internet address. Assume it is not behind a NAT #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << "not on a NAT. disabling NAT-PMP" << std::endl; #endif m_disabled = true; return; } // assume the router is located on the local // network as x.x.x.1 // TODO: find a better way to figure out the router IP m_nat_endpoint = udp::endpoint( address_v4((local.to_ulong() & 0xffffff00) | 1), 5351); #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << "assuming router is at: " << m_nat_endpoint.address().to_string() << std::endl; #endif m_socket.open(udp::v4()); m_socket.bind(udp::endpoint()); } void natpmp::set_mappings(int tcp, int udp) { if (m_disabled) return; update_mapping(0, tcp); update_mapping(1, udp); } void natpmp::update_mapping(int i, int port) { natpmp::mapping& m = m_mappings[i]; if (port <= 0) return; if (m.local_port != port) m.need_update = true; m.local_port = port; // prefer the same external port as the local port if (m.external_port == 0) m.external_port = port; if (m_currently_mapping == -1) { // the socket is not currently in use // send out a mapping request m_retry_count = 0; send_map_request(i); m_socket.async_receive_from(asio::buffer(&m_response_buffer, 16) , m_remote, bind(&natpmp::on_reply, this, _1, _2)); } } void natpmp::send_map_request(int i) try { using namespace libtorrent::detail; using boost::posix_time::milliseconds; assert(m_currently_mapping == -1 || m_currently_mapping == i); m_currently_mapping = i; mapping& m = m_mappings[i]; char buf[12]; char* out = buf; write_uint8(0, out); // NAT-PMP version write_uint8(m.protocol, out); // map "protocol" write_uint16(0, out); // reserved write_uint16(m.local_port, out); // private port write_uint16(m.external_port, out); // requested public port int ttl = m.external_port == 0 ? 0 : 3600; write_uint32(ttl, out); // port mapping lifetime #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << to_simple_string(microsec_clock::universal_time()) << " ==> port map request: " << (m.protocol == 1 ? "udp" : "tcp") << " local: " << m.local_port << " external: " << m.external_port << " ttl: " << ttl << std::endl; #endif m_socket.send_to(asio::buffer(buf, 12), m_nat_endpoint); // linear back-off instead of exponential ++m_retry_count; m_send_timer.expires_from_now(milliseconds(250 * m_retry_count)); m_send_timer.async_wait(bind(&natpmp::resend_request, this, i, _1)); } catch (std::exception& e) { std::string err = e.what(); } void natpmp::resend_request(int i, asio::error_code const& e) { using boost::posix_time::hours; if (e) return; if (m_retry_count >= 9) { m_mappings[i].need_update = false; // try again in two hours m_mappings[i].expires = boost::posix_time::second_clock::universal_time() + hours(2); return; } send_map_request(i); } void natpmp::on_reply(asio::error_code const& e , std::size_t bytes_transferred) { using namespace libtorrent::detail; using boost::posix_time::seconds; if (e) return; try { if (m_remote != m_nat_endpoint) { m_socket.async_receive_from(asio::buffer(&m_response_buffer, 16) , m_remote, bind(&natpmp::on_reply, this, _1, _2)); return; } m_send_timer.cancel(); assert(m_currently_mapping >= 0); int i = m_currently_mapping; mapping& m = m_mappings[i]; char* in = m_response_buffer; int version = read_uint8(in); int cmd = read_uint8(in); int result = read_uint16(in); int time = read_uint32(in); int private_port = read_uint16(in); int public_port = read_uint16(in); int lifetime = read_uint32(in); #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << to_simple_string(microsec_clock::universal_time()) << " <== port map response: " << (cmd - 128 == 1 ? "udp" : "tcp") << " local: " << private_port << " external: " << public_port << " ttl: " << lifetime << std::endl; #endif #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) if (version != 0) { m_log << "*** unexpected version: " << version << std::endl; } #endif #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) if (private_port != m.local_port) { m_log << "*** unexpected local port: " << private_port << std::endl; } #endif #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) if (cmd != 128 + m.protocol) { m_log << "*** unexpected protocol: " << (cmd - 128) << std::endl; } #endif if (public_port == 0 || lifetime == 0) { // this means the mapping was // successfully closed m.local_port = 0; } else { m.expires = boost::posix_time::second_clock::universal_time() + seconds(int(lifetime * 0.7f)); m.external_port = public_port; } if (result != 0) { #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << "*** ERROR: " << result << std::endl; #endif std::stringstream errmsg; errmsg << "NAT router reports error (" << result << ") "; switch (result) { case 1: errmsg << "Unsupported protocol version"; break; case 2: errmsg << "Not authorized to create port map (enable NAT-PMP on your router)"; break; case 3: errmsg << "Network failure"; break; case 4: errmsg << "Out of resources"; break; case 5: errmsg << "Unsupported opcpde"; break; } throw std::runtime_error(errmsg.str()); } int tcp_port = 0; int udp_port = 0; if (m.protocol == 1) udp_port = m.external_port; else tcp_port = public_port; m_callback(tcp_port, udp_port, ""); } catch (std::exception& e) { using boost::posix_time::hours; // try again in two hours m_mappings[m_currently_mapping].expires = boost::posix_time::second_clock::universal_time() + hours(2); m_callback(0, 0, e.what()); } int i = m_currently_mapping; m_currently_mapping = -1; m_mappings[i].need_update = false; update_expiration_timer(); try_next_mapping(i); } void natpmp::update_expiration_timer() { using boost::posix_time::seconds; boost::posix_time::ptime now = boost::posix_time::second_clock::universal_time(); boost::posix_time::ptime min_expire = now + seconds(3600); int min_index = -1; for (int i = 0; i < 2; ++i) if (m_mappings[i].expires < min_expire && m_mappings[i].local_port != 0) { min_expire = m_mappings[i].expires; min_index = i; } if (min_index >= 0) { m_refresh_timer.expires_from_now(min_expire - now); m_refresh_timer.async_wait(bind(&natpmp::mapping_expired, this, _1, min_index)); } } void natpmp::mapping_expired(asio::error_code const& e, int i) { if (e) return; #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << "*** mapping " << i << " expired, updating" << std::endl; #endif refresh_mapping(i); } void natpmp::refresh_mapping(int i) { m_mappings[i].need_update = true; if (m_currently_mapping == -1) { // the socket is not currently in use // send out a mapping request m_retry_count = 0; send_map_request(i); m_socket.async_receive_from(asio::buffer(&m_response_buffer, 16) , m_remote, bind(&natpmp::on_reply, this, _1, _2)); } } void natpmp::try_next_mapping(int i) { ++i; if (i >= 2) i = 0; if (m_mappings[i].need_update) refresh_mapping(i); } void natpmp::close() { if (m_disabled) return; for (int i = 0; i < 2; ++i) { if (m_mappings[i].local_port == 0) continue; m_mappings[i].external_port = 0; refresh_mapping(i); } } <commit_msg>fixes incorrect local IP address check<commit_after>/* Copyright (c) 2007, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author 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 <libtorrent/natpmp.hpp> #include <libtorrent/io.hpp> #include <boost/bind.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <asio/ip/host_name.hpp> using boost::bind; using namespace libtorrent; using boost::posix_time::microsec_clock; natpmp::natpmp(io_service& ios, portmap_callback_t const& cb) : m_callback(cb) , m_currently_mapping(-1) , m_retry_count(0) , m_socket(ios) , m_send_timer(ios) , m_refresh_timer(ios) , m_disabled(false) { m_mappings[0].protocol = 2; // tcp m_mappings[1].protocol = 1; // udp #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log.open("natpmp.log", std::ios::in | std::ios::out | std::ios::trunc); #endif udp::resolver r(ios); udp::resolver::iterator i = r.resolve(udp::resolver::query(asio::ip::host_name(), "0")); for (;i != udp::resolver_iterator(); ++i) { if (i->endpoint().address().is_v4()) break; } if (i == udp::resolver_iterator()) { #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << "local host name did not resolve to an IPv4 address. " "disabling NAT-PMP" << std::endl; #endif m_disabled = true; return; } address_v4 local = i->endpoint().address().to_v4(); #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << to_simple_string(microsec_clock::universal_time()) << " local ip: " << local.to_string() << std::endl; #endif if ((local.to_ulong() & 0xff000000) != 0x0a000000 && (local.to_ulong() & 0xfff00000) != 0xac100000 && (local.to_ulong() & 0xffff0000) != 0xc0a80000) { // the local address seems to be an external // internet address. Assume it is not behind a NAT #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << "not on a NAT. disabling NAT-PMP" << std::endl; #endif m_disabled = true; return; } // assume the router is located on the local // network as x.x.x.1 // TODO: find a better way to figure out the router IP m_nat_endpoint = udp::endpoint( address_v4((local.to_ulong() & 0xffffff00) | 1), 5351); #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << "assuming router is at: " << m_nat_endpoint.address().to_string() << std::endl; #endif m_socket.open(udp::v4()); m_socket.bind(udp::endpoint()); } void natpmp::set_mappings(int tcp, int udp) { if (m_disabled) return; update_mapping(0, tcp); update_mapping(1, udp); } void natpmp::update_mapping(int i, int port) { natpmp::mapping& m = m_mappings[i]; if (port <= 0) return; if (m.local_port != port) m.need_update = true; m.local_port = port; // prefer the same external port as the local port if (m.external_port == 0) m.external_port = port; if (m_currently_mapping == -1) { // the socket is not currently in use // send out a mapping request m_retry_count = 0; send_map_request(i); m_socket.async_receive_from(asio::buffer(&m_response_buffer, 16) , m_remote, bind(&natpmp::on_reply, this, _1, _2)); } } void natpmp::send_map_request(int i) try { using namespace libtorrent::detail; using boost::posix_time::milliseconds; assert(m_currently_mapping == -1 || m_currently_mapping == i); m_currently_mapping = i; mapping& m = m_mappings[i]; char buf[12]; char* out = buf; write_uint8(0, out); // NAT-PMP version write_uint8(m.protocol, out); // map "protocol" write_uint16(0, out); // reserved write_uint16(m.local_port, out); // private port write_uint16(m.external_port, out); // requested public port int ttl = m.external_port == 0 ? 0 : 3600; write_uint32(ttl, out); // port mapping lifetime #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << to_simple_string(microsec_clock::universal_time()) << " ==> port map request: " << (m.protocol == 1 ? "udp" : "tcp") << " local: " << m.local_port << " external: " << m.external_port << " ttl: " << ttl << std::endl; #endif m_socket.send_to(asio::buffer(buf, 12), m_nat_endpoint); // linear back-off instead of exponential ++m_retry_count; m_send_timer.expires_from_now(milliseconds(250 * m_retry_count)); m_send_timer.async_wait(bind(&natpmp::resend_request, this, i, _1)); } catch (std::exception& e) { std::string err = e.what(); } void natpmp::resend_request(int i, asio::error_code const& e) { using boost::posix_time::hours; if (e) return; if (m_retry_count >= 9) { m_mappings[i].need_update = false; // try again in two hours m_mappings[i].expires = boost::posix_time::second_clock::universal_time() + hours(2); return; } send_map_request(i); } void natpmp::on_reply(asio::error_code const& e , std::size_t bytes_transferred) { using namespace libtorrent::detail; using boost::posix_time::seconds; if (e) return; try { if (m_remote != m_nat_endpoint) { m_socket.async_receive_from(asio::buffer(&m_response_buffer, 16) , m_remote, bind(&natpmp::on_reply, this, _1, _2)); return; } m_send_timer.cancel(); assert(m_currently_mapping >= 0); int i = m_currently_mapping; mapping& m = m_mappings[i]; char* in = m_response_buffer; int version = read_uint8(in); int cmd = read_uint8(in); int result = read_uint16(in); int time = read_uint32(in); int private_port = read_uint16(in); int public_port = read_uint16(in); int lifetime = read_uint32(in); #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << to_simple_string(microsec_clock::universal_time()) << " <== port map response: " << (cmd - 128 == 1 ? "udp" : "tcp") << " local: " << private_port << " external: " << public_port << " ttl: " << lifetime << std::endl; #endif #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) if (version != 0) { m_log << "*** unexpected version: " << version << std::endl; } #endif #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) if (private_port != m.local_port) { m_log << "*** unexpected local port: " << private_port << std::endl; } #endif #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) if (cmd != 128 + m.protocol) { m_log << "*** unexpected protocol: " << (cmd - 128) << std::endl; } #endif if (public_port == 0 || lifetime == 0) { // this means the mapping was // successfully closed m.local_port = 0; } else { m.expires = boost::posix_time::second_clock::universal_time() + seconds(int(lifetime * 0.7f)); m.external_port = public_port; } if (result != 0) { #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << "*** ERROR: " << result << std::endl; #endif std::stringstream errmsg; errmsg << "NAT router reports error (" << result << ") "; switch (result) { case 1: errmsg << "Unsupported protocol version"; break; case 2: errmsg << "Not authorized to create port map (enable NAT-PMP on your router)"; break; case 3: errmsg << "Network failure"; break; case 4: errmsg << "Out of resources"; break; case 5: errmsg << "Unsupported opcpde"; break; } throw std::runtime_error(errmsg.str()); } int tcp_port = 0; int udp_port = 0; if (m.protocol == 1) udp_port = m.external_port; else tcp_port = public_port; m_callback(tcp_port, udp_port, ""); } catch (std::exception& e) { using boost::posix_time::hours; // try again in two hours m_mappings[m_currently_mapping].expires = boost::posix_time::second_clock::universal_time() + hours(2); m_callback(0, 0, e.what()); } int i = m_currently_mapping; m_currently_mapping = -1; m_mappings[i].need_update = false; update_expiration_timer(); try_next_mapping(i); } void natpmp::update_expiration_timer() { using boost::posix_time::seconds; boost::posix_time::ptime now = boost::posix_time::second_clock::universal_time(); boost::posix_time::ptime min_expire = now + seconds(3600); int min_index = -1; for (int i = 0; i < 2; ++i) if (m_mappings[i].expires < min_expire && m_mappings[i].local_port != 0) { min_expire = m_mappings[i].expires; min_index = i; } if (min_index >= 0) { m_refresh_timer.expires_from_now(min_expire - now); m_refresh_timer.async_wait(bind(&natpmp::mapping_expired, this, _1, min_index)); } } void natpmp::mapping_expired(asio::error_code const& e, int i) { if (e) return; #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << "*** mapping " << i << " expired, updating" << std::endl; #endif refresh_mapping(i); } void natpmp::refresh_mapping(int i) { m_mappings[i].need_update = true; if (m_currently_mapping == -1) { // the socket is not currently in use // send out a mapping request m_retry_count = 0; send_map_request(i); m_socket.async_receive_from(asio::buffer(&m_response_buffer, 16) , m_remote, bind(&natpmp::on_reply, this, _1, _2)); } } void natpmp::try_next_mapping(int i) { ++i; if (i >= 2) i = 0; if (m_mappings[i].need_update) refresh_mapping(i); } void natpmp::close() { if (m_disabled) return; for (int i = 0; i < 2; ++i) { if (m_mappings[i].local_port == 0) continue; m_mappings[i].external_port = 0; refresh_mapping(i); } } <|endoftext|>
<commit_before>// -*- Mode:C++ -*- /**************************************************************************************************/ /* */ /* Copyright (C) 2013-2015 University of Hull */ /* */ /**************************************************************************************************/ /* */ /* module : scene/loader/mtl.cpp */ /* project : */ /* description: */ /* */ /**************************************************************************************************/ // include i/f header #include "loader/mtl.hpp" // includes, system // altough dealing w/ lowering the noise level for boost::spirit headers, the pragmas need to be // here #if defined(_MSC_VER) && (_MSC_VER < 1800) // warning C4100: 'x' : unreferenced formal parameter # pragma warning(disable:4100) // warning C4127: conditional expression is constant # pragma warning(disable:4127) #endif #include <boost/algorithm/string.hpp> // boost::trim #include <boost/config/warning_disable.hpp> #include <boost/fusion/include/adapt_struct.hpp> #include <boost/spirit/include/phoenix_core.hpp> #include <boost/spirit/include/phoenix_object.hpp> #include <boost/spirit/include/phoenix_operator.hpp> #include <boost/spirit/include/qi.hpp> #include <boost/tokenizer.hpp> // boost::char_separator<>, boost::tokenizer<> #include <cmath> // std::pow #include <fstream> // std::[i|o]fstream #include <istream> // std::istream #include <ostream> // std::ostream // includes, project // #include <> #define UKACHULLDCS_USE_TRACE // #undef UKACHULLDCS_USE_TRACE #include <support/trace.hpp> #include <support/type_info.hpp> #if defined(UKACHULLDCS_USE_TRACE) # include <boost/fusion/include/io.hpp> # include <glm/gtx/io.hpp> #endif BOOST_FUSION_ADAPT_STRUCT(glm::vec3, (glm::vec3::value_type, x) (glm::vec3::value_type, y) (glm::vec3::value_type, z) ); // internal unnamed namespace namespace { // types, internal (class, enum, struct, union, typedef) namespace qi = boost::spirit::qi; namespace ascii = boost::spirit::ascii; template <typename IT> struct rgb_parser : qi::grammar<IT, glm::vec3(), ascii::space_type> { rgb_parser() : rgb_parser::base_type(start) { TRACE_NEVER("scene::file::mtl::<unnamed>::rgb_parser::rgb_parser"); using qi::debug; using qi::float_; start %= float_ >> // x float_ >> // y float_ // z ; // debug(start); } qi::rule<IT, glm::vec3(), ascii::space_type> start; }; template <typename IT> struct xyz_parser : qi::grammar<IT, glm::vec3(), ascii::space_type> { xyz_parser() : xyz_parser::base_type(start) { TRACE_NEVER("scene::file::mtl::<unnamed>::xyz_parser::xyz_parser"); using qi::debug; using qi::float_; using qi::lit; start %= lit("xyz") >> // "xyz" float_ >> // x float_ >> // y float_ // z ; // debug(start); } qi::rule<IT, glm::vec3(), ascii::space_type> start; }; template <typename IT> struct float_parser : qi::grammar<IT, float(), ascii::space_type> { float_parser() : float_parser::base_type(start) { TRACE_NEVER("scene::file::mtl::<unnamed>::float_parser::float_parser"); using qi::debug; using qi::float_; start %= float_ ; // debug(start); } qi::rule<IT, float(), ascii::space_type> start; }; // variables, internal // functions, internal template <typename P, typename O> bool parse(std::string const& exp, O& o) { TRACE_NEVER("scene::file::mtl::<unamed>::parse<" + support::demangle(typeid(P)) + "," + support::demangle(typeid(O)) + ">"); auto first (exp.begin()); auto last (exp.end()); bool const result(phrase_parse(first, last, P(), ascii::space, o)); #if 0 // defined(UKACHULLDCS_USE_TRACE) if (result && first == last) { std::cout << support::trace::prefix() << "scene::file::mtl::parse<" << support::demangle(typeid(P)) << ',' << support::demangle(typeid(O)) << ">: " << boost::fusion::tuple_open('[') << boost::fusion::tuple_close(']') << boost::fusion::tuple_delimiter(", ") << "in:'" << exp << "', out:" << o << std::endl; } else { std::cout << support::trace::prefix() << "scene::file::mtl::parse<" << support::demangle(typeid(P)) << ',' << support::demangle(typeid(O)) << ">: " << "failed to parse '" << exp << "'" << std::endl; } #endif return (result && first == last); } /* * see [http://www.wikipedia.org/wiki/SRGB] */ glm::vec3 xyz_to_rgb(glm::vec3 const& xyz) { static float const a( 0.055); static float const b(12.920); static glm::mat3 const c(+3.2406, -1.5372, -0.4986, -0.9689, +1.8758, +0.0415, +0.0557, -0.2040, +1.0570); glm::vec3 result(c * (xyz / glm::vec3(100.0))); result.r = (result.r > 0.0031308) ? ((1.0 + a) * std::pow(result.r, 1/2.4)) : (b * result.r); result.g = (result.g > 0.0031308) ? ((1.0 + a) * std::pow(result.g, 1/2.4)) : (b * result.g); result.b = (result.b > 0.0031308) ? ((1.0 + a) * std::pow(result.b, 1/2.4)) : (b * result.b); return result; } } // namespace { namespace scene { namespace file { namespace mtl { // variables, exported // functions, exported list_type load(std::istream& is) { TRACE("scene::file::mtl::load(std::istream)"); list_type result; result.push_back(new scene::object::material); std::string line; while (std::getline(is, line)) { if (line.empty() || ('#' == line[0]) || ('!' == line[0]) || ('$' == line[0])) { continue; } static boost::char_separator<char> const token_separator_space(" "); typedef boost::tokenizer<boost::char_separator<char>> tokenizer; tokenizer tokens(line, token_separator_space); // bump -options args filename if ("d" == *tokens.begin()) { // d [-halo] f std::string const exp(line.begin() + (*tokens.begin()).length(), line.end()); float d; if (parse<float_parser<std::string::const_iterator>>(exp, d)) { (*result.rbegin())->alpha = d; } } else if ("illum" == *tokens.begin()) { // illum # // nothing to do (yet) } else if ("Ka" == *tokens.begin()) { // Ka [r g b] | [spectral file.refl f] | [xyz x y z] std::string const exp(line.begin() + (*tokens.begin()).length(), line.end()); glm::vec3 c; if (parse<rgb_parser<std::string::const_iterator>>(exp, c)) { (*result.rbegin())->ambient = c; } else if (parse<xyz_parser<std::string::const_iterator>>(exp, c)) { (*result.rbegin())->ambient = xyz_to_rgb(c); } } else if ("Ke" == *tokens.begin()) { // Ke [r g b] | [spectral file.refl f] | [xyz x y z] std::string const exp(line.begin() + (*tokens.begin()).length(), line.end()); glm::vec3 c; if (parse<rgb_parser<std::string::const_iterator>>(exp, c)) { (*result.rbegin())->emission = c; } else if (parse<xyz_parser<std::string::const_iterator>>(exp, c)) { (*result.rbegin())->emission = xyz_to_rgb(c); } } else if ("Kd" == *tokens.begin()) { // Kd [r g b] | [spectral file.refl f] | [xyz x y z] std::string const exp(line.begin() + (*tokens.begin()).length(), line.end()); glm::vec3 c; if (parse<rgb_parser<std::string::const_iterator>>(exp, c)) { (*result.rbegin())->diffuse = c; } else if (parse<xyz_parser<std::string::const_iterator>>(exp, c)) { (*result.rbegin())->diffuse = xyz_to_rgb(c); } } else if ("Ks" == *tokens.begin()) { // Ks [r g b] | [spectral file.refl f] | [xyz x y z] std::string const exp(line.begin() + (*tokens.begin()).length(), line.end()); glm::vec3 c; if (parse<rgb_parser<std::string::const_iterator>>(exp, c)) { (*result.rbegin())->specular = c; } else if (parse<xyz_parser<std::string::const_iterator>>(exp, c)) { (*result.rbegin())->specular = xyz_to_rgb(c); } } // else if ("map_d" == *tokens.begin()) { // map_d -options args filename // } // else if ("map_Ka" == *tokens.begin()) { // map_Ka -options args filenam // } // else if ("map_Ke" == *tokens.begin()) { // map_Ka -options args filenam // } // else if ("map_Kd" == *tokens.begin()) { // map_Kd -options args filename // } // else if ("map_Ks" == *tokens.begin()) { // map_Ks -options args filename // } // else if ("map_Ns" == *tokens.begin()) { // map_Ns -options args filename // } else if ("Ni" == *tokens.begin()) { // Ni f std::string const exp(line.begin() + (*tokens.begin()).length(), line.end()); float r; if (parse<float_parser<std::string::const_iterator>>(exp, r)) { (*result.rbegin())->refraction = r; } } else if ("Ns" == *tokens.begin()) { // Ns exp std::string const exp(line.begin() + (*tokens.begin()).length(), line.end()); float s; if (parse<float_parser<std::string::const_iterator>>(exp, s)) { (*result.rbegin())->shininess = s; } } else if ("newmtl" == *tokens.begin()) { // newmtl <string> result.push_back(new scene::object::material); } //else if ("refl" == *tokens.begin()) { //refl -type <type> -options -args filename //} else if ("Tf" == *tokens.begin()) { // Tf [r g b] | [spectral file.refl f] | [xyz x y z] std::string const exp(line.begin() + (*tokens.begin()).length(), line.end()); glm::vec3 c; if (parse<rgb_parser<std::string::const_iterator>>(exp, c)) { (*result.rbegin())->transmission = c; } else if (parse<xyz_parser<std::string::const_iterator>>(exp, c)) { (*result.rbegin())->transmission = xyz_to_rgb(c); } } else if ("Tr" == *tokens.begin()) { // Tr x (== 1 - alpha) std::string const exp(line.begin() + (*tokens.begin()).length(), line.end()); float t; if (parse<float_parser<std::string::const_iterator>>(exp, t)) { (*result.rbegin())->alpha = (1.0f - t); } } else if ("TWOSIDE" == *tokens.begin()) { // TWOSIDE (non-standard) (*result.rbegin())->front = true; (*result.rbegin())->back = true; } #if 0 // defined(UKACHULLDCS_USE_TRACE) else { std::cout << support::trace::prefix() << "scene::file::mtl::load(std::istream): " << "unhandled token '" << *tokens.begin() << "'; skipping " << "whole line '" << line << "'" << std::endl; } #endif } return result; } list_type load(std::string const& a) { TRACE("scene::file::mtl::load(std::string) [" + a + "]"); list_type result; std::ifstream ifs(a, std::ios::in|std::ios::binary); if (ifs.is_open()) { result = load(ifs); } return result; } bool save(std::ostream&, list_type const&) { TRACE("scene::file::mtl::save(std::ostream)"); return false; } bool save(std::string const& a, list_type const& b) { TRACE("scene::file::mtl::save(std::string) [" + a + "]"); bool result(false); std::ofstream ofs(a, std::ios::out|std::ios::binary|std::ios::trunc); if (ofs.is_open()) { result = save(ofs, b); } return result; } } // namespace mtl { } // namespace file { } // namespace scene { <commit_msg>cleanup + adding material name<commit_after>// -*- Mode:C++ -*- /**************************************************************************************************/ /* */ /* Copyright (C) 2013-2015 University of Hull */ /* */ /**************************************************************************************************/ /* */ /* module : scene/loader/mtl.cpp */ /* project : */ /* description: */ /* */ /**************************************************************************************************/ // include i/f header #include "loader/mtl.hpp" // includes, system // altough dealing w/ lowering the noise level for boost::spirit headers, the pragmas need to be // here #if defined(_MSC_VER) && (_MSC_VER < 1800) // warning C4100: 'x' : unreferenced formal parameter # pragma warning(disable:4100) // warning C4127: conditional expression is constant # pragma warning(disable:4127) #endif #include <boost/algorithm/string.hpp> // boost::trim #include <boost/config/warning_disable.hpp> #include <boost/fusion/include/adapt_struct.hpp> #include <boost/spirit/include/phoenix_core.hpp> #include <boost/spirit/include/phoenix_object.hpp> #include <boost/spirit/include/phoenix_operator.hpp> #include <boost/spirit/include/qi.hpp> #include <boost/tokenizer.hpp> // boost::char_separator<>, boost::tokenizer<> #include <cmath> // std::pow #include <fstream> // std::[i|o]fstream #include <istream> // std::istream #include <ostream> // std::ostream // includes, project // #include <> #define UKACHULLDCS_USE_TRACE #undef UKACHULLDCS_USE_TRACE #include <support/trace.hpp> #include <support/type_info.hpp> #if defined(UKACHULLDCS_USE_TRACE) # include <boost/fusion/include/io.hpp> # include <glm/gtx/io.hpp> #endif BOOST_FUSION_ADAPT_STRUCT(glm::vec3, (glm::vec3::value_type, x) (glm::vec3::value_type, y) (glm::vec3::value_type, z) ); // internal unnamed namespace namespace { // types, internal (class, enum, struct, union, typedef) namespace qi = boost::spirit::qi; namespace ascii = boost::spirit::ascii; template <typename IT> struct rgb_parser : qi::grammar<IT, glm::vec3(), ascii::space_type> { rgb_parser() : rgb_parser::base_type(start) { TRACE_NEVER("scene::file::mtl::<unnamed>::rgb_parser::rgb_parser"); using qi::debug; using qi::float_; start %= float_ >> // x float_ >> // y float_ // z ; // debug(start); } qi::rule<IT, glm::vec3(), ascii::space_type> start; }; template <typename IT> struct xyz_parser : qi::grammar<IT, glm::vec3(), ascii::space_type> { xyz_parser() : xyz_parser::base_type(start) { TRACE_NEVER("scene::file::mtl::<unnamed>::xyz_parser::xyz_parser"); using qi::debug; using qi::float_; using qi::lit; start %= lit("xyz") >> // "xyz" float_ >> // x float_ >> // y float_ // z ; // debug(start); } qi::rule<IT, glm::vec3(), ascii::space_type> start; }; template <typename IT> struct float_parser : qi::grammar<IT, float(), ascii::space_type> { float_parser() : float_parser::base_type(start) { TRACE_NEVER("scene::file::mtl::<unnamed>::float_parser::float_parser"); using qi::debug; using qi::float_; start %= float_ ; // debug(start); } qi::rule<IT, float(), ascii::space_type> start; }; // variables, internal // functions, internal template <typename P, typename O> bool parse(std::string const& exp, O& o) { TRACE_NEVER("scene::file::mtl::<unamed>::parse<" + support::demangle(typeid(P)) + "," + support::demangle(typeid(O)) + ">"); auto first (exp.begin()); auto last (exp.end()); bool const result(phrase_parse(first, last, P(), ascii::space, o)); #if 0 // defined(UKACHULLDCS_USE_TRACE) if (result && first == last) { std::cout << support::trace::prefix() << "scene::file::mtl::parse<" << support::demangle(typeid(P)) << ',' << support::demangle(typeid(O)) << ">: " << boost::fusion::tuple_open('[') << boost::fusion::tuple_close(']') << boost::fusion::tuple_delimiter(", ") << "in:'" << exp << "', out:" << o << std::endl; } else { std::cout << support::trace::prefix() << "scene::file::mtl::parse<" << support::demangle(typeid(P)) << ',' << support::demangle(typeid(O)) << ">: " << "failed to parse '" << exp << "'" << std::endl; } #endif return (result && first == last); } /* * see [http://www.wikipedia.org/wiki/SRGB] */ glm::vec3 xyz_to_rgb(glm::vec3 const& xyz) { static float const a( 0.055); static float const b(12.920); static glm::mat3 const c(+3.2406, -1.5372, -0.4986, -0.9689, +1.8758, +0.0415, +0.0557, -0.2040, +1.0570); glm::vec3 result(c * (xyz / glm::vec3(100.0))); result.r = (result.r > 0.0031308) ? ((1.0 + a) * std::pow(result.r, 1/2.4)) : (b * result.r); result.g = (result.g > 0.0031308) ? ((1.0 + a) * std::pow(result.g, 1/2.4)) : (b * result.g); result.b = (result.b > 0.0031308) ? ((1.0 + a) * std::pow(result.b, 1/2.4)) : (b * result.b); return result; } } // namespace { namespace scene { namespace file { namespace mtl { // variables, exported // functions, exported list_type load(std::istream& is) { TRACE("scene::file::mtl::load(std::istream)"); list_type result; { result.push_back(new scene::object::material); (*result.rbegin())->name = "default material"; } std::string line; while (std::getline(is, line)) { if (line.empty() || ('#' == line[0]) || ('!' == line[0]) || ('$' == line[0])) { continue; } static boost::char_separator<char> const token_separator_space(" "); using tokenizer = boost::tokenizer<boost::char_separator<char>>; tokenizer tokens(line, token_separator_space); // bump -options args filename if ("d" == *tokens.begin()) { // d [-halo] f std::string const exp(line.begin() + (*tokens.begin()).length(), line.end()); float d; if (parse<float_parser<std::string::const_iterator>>(exp, d)) { (*result.rbegin())->alpha = d; } } else if ("illum" == *tokens.begin()) { // illum # // nothing to do (yet) } else if ("Ka" == *tokens.begin()) { // Ka [r g b] | [spectral file.refl f] | [xyz x y z] std::string const exp(line.begin() + (*tokens.begin()).length(), line.end()); glm::vec3 c; if (parse<rgb_parser<std::string::const_iterator>>(exp, c)) { (*result.rbegin())->ambient = c; } else if (parse<xyz_parser<std::string::const_iterator>>(exp, c)) { (*result.rbegin())->ambient = xyz_to_rgb(c); } } else if ("Ke" == *tokens.begin()) { // Ke [r g b] | [spectral file.refl f] | [xyz x y z] std::string const exp(line.begin() + (*tokens.begin()).length(), line.end()); glm::vec3 c; if (parse<rgb_parser<std::string::const_iterator>>(exp, c)) { (*result.rbegin())->emission = c; } else if (parse<xyz_parser<std::string::const_iterator>>(exp, c)) { (*result.rbegin())->emission = xyz_to_rgb(c); } } else if ("Kd" == *tokens.begin()) { // Kd [r g b] | [spectral file.refl f] | [xyz x y z] std::string const exp(line.begin() + (*tokens.begin()).length(), line.end()); glm::vec3 c; if (parse<rgb_parser<std::string::const_iterator>>(exp, c)) { (*result.rbegin())->diffuse = c; } else if (parse<xyz_parser<std::string::const_iterator>>(exp, c)) { (*result.rbegin())->diffuse = xyz_to_rgb(c); } } else if ("Ks" == *tokens.begin()) { // Ks [r g b] | [spectral file.refl f] | [xyz x y z] std::string const exp(line.begin() + (*tokens.begin()).length(), line.end()); glm::vec3 c; if (parse<rgb_parser<std::string::const_iterator>>(exp, c)) { (*result.rbegin())->specular = c; } else if (parse<xyz_parser<std::string::const_iterator>>(exp, c)) { (*result.rbegin())->specular = xyz_to_rgb(c); } } // else if ("map_d" == *tokens.begin()) { // map_d -options args filename // } // else if ("map_Ka" == *tokens.begin()) { // map_Ka -options args filenam // } // else if ("map_Ke" == *tokens.begin()) { // map_Ka -options args filenam // } // else if ("map_Kd" == *tokens.begin()) { // map_Kd -options args filename // } // else if ("map_Ks" == *tokens.begin()) { // map_Ks -options args filename // } // else if ("map_Ns" == *tokens.begin()) { // map_Ns -options args filename // } else if ("Ni" == *tokens.begin()) { // Ni f std::string const exp(line.begin() + (*tokens.begin()).length(), line.end()); float r; if (parse<float_parser<std::string::const_iterator>>(exp, r)) { (*result.rbegin())->refraction = r; } } else if ("Ns" == *tokens.begin()) { // Ns exp std::string const exp(line.begin() + (*tokens.begin()).length(), line.end()); float s; if (parse<float_parser<std::string::const_iterator>>(exp, s)) { (*result.rbegin())->shininess = s; } } else if ("newmtl" == *tokens.begin()) { // newmtl <string> result.push_back(new scene::object::material); (*result.rbegin())->name = std::string(line.begin() + (*tokens.begin()).length() + 1, line.end()); } //else if ("refl" == *tokens.begin()) { //refl -type <type> -options -args filename //} else if ("Tf" == *tokens.begin()) { // Tf [r g b] | [spectral file.refl f] | [xyz x y z] std::string const exp(line.begin() + (*tokens.begin()).length(), line.end()); glm::vec3 c; if (parse<rgb_parser<std::string::const_iterator>>(exp, c)) { (*result.rbegin())->transmission = c; } else if (parse<xyz_parser<std::string::const_iterator>>(exp, c)) { (*result.rbegin())->transmission = xyz_to_rgb(c); } } else if ("Tr" == *tokens.begin()) { // Tr x (== 1 - alpha) std::string const exp(line.begin() + (*tokens.begin()).length(), line.end()); float t; if (parse<float_parser<std::string::const_iterator>>(exp, t)) { (*result.rbegin())->alpha = (1.0f - t); } } else if ("TWOSIDE" == *tokens.begin()) { // TWOSIDE (non-standard) (*result.rbegin())->front = true; (*result.rbegin())->back = true; } #if 0 // defined(UKACHULLDCS_USE_TRACE) else { std::cout << support::trace::prefix() << "scene::file::mtl::load(std::istream): " << "unhandled token '" << *tokens.begin() << "'; skipping " << "whole line '" << line << "'" << std::endl; } #endif } return result; } list_type load(std::string const& a) { TRACE("scene::file::mtl::load(std::string) [" + a + "]"); list_type result; std::ifstream ifs(a, std::ios::in|std::ios::binary); if (ifs.is_open()) { result = load(ifs); } return result; } bool save(std::ostream&, list_type const&) { TRACE("scene::file::mtl::save(std::ostream)"); return false; } bool save(std::string const& a, list_type const& b) { TRACE("scene::file::mtl::save(std::string) [" + a + "]"); bool result(false); std::ofstream ofs(a, std::ios::out|std::ios::binary|std::ios::trunc); if (ofs.is_open()) { result = save(ofs, b); } return result; } } // namespace mtl { } // namespace file { } // namespace scene { <|endoftext|>
<commit_before>#define _LOG_PROB_ neg_binomial_log #include <stan/prob/distributions/univariate/discrete/neg_binomial.hpp> #include <stan/prob/distributions/univariate/discrete/binomial.hpp> using std::vector; using std::numeric_limits; using stan::agrad::var; class AgradDistributionsNegBinomial : public AgradDistributionTest { public: void valid_values(vector<vector<double> >& parameters, vector<double>& log_prob) { vector<double> param(3); param[0] = 10; // n param[1] = 2.0; // alpha param[2] = 1.5; // beta parameters.push_back(param); log_prob.push_back(-7.786663); // expected log_prob param[0] = 100; // n param[1] = 3.0; // alpha param[2] = 3.5; // beta parameters.push_back(param); log_prob.push_back(-142.6147); // expected log_prob param[0] = 13; param[1] = 1e11; // alpha > 1e10, causes redux to Poisson param[2] = 1e10; // equiv to Poisson(1e11/1e10) = Poisson(10) parameters.push_back(param); log_prob.push_back(-2.618558); // log poisson(13|10) } void invalid_values(vector<size_t>& index, vector<double>& value) { // n index.push_back(0U); value.push_back(-1); // alpha index.push_back(1U); value.push_back(0); // beta index.push_back(2U); value.push_back(0); } template <class T_n, class T_shape, class T_inv_scale, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9> typename stan::return_type<T_shape,T_inv_scale>::type log_prob(const T_n& n, const T_shape& alpha, const T_inv_scale& beta, const T3&, const T4&, const T5&, const T6&, const T7&, const T8&, const T9&) { return stan::prob::neg_binomial_log(n, alpha, beta); } template <bool propto, class T_n, class T_shape, class T_inv_scale, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9> typename stan::return_type<T_shape,T_inv_scale>::type log_prob(const T_n& n, const T_shape& alpha, const T_inv_scale& beta, const T3&, const T4&, const T5&, const T6&, const T7&, const T8&, const T9&) { return stan::prob::neg_binomial_log<propto>(n, alpha, beta); } template <bool propto, class T_n, class T_shape, class T_inv_scale, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, class Policy> typename stan::return_type<T_shape,T_inv_scale>::type log_prob(const T_n& n, const T_shape& alpha, const T_inv_scale& beta, const T3&, const T4&, const T5&, const T6&, const T7&, const T8&, const T9&) { return stan::prob::neg_binomial_log<propto>(n, alpha, beta, Policy()); } template <class T_n, class T_shape, class T_inv_scale, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9> var log_prob_function(const T_n& n, const T_shape& alpha, const T_inv_scale& beta, const T3&, const T4&, const T5&, const T6&, const T7&, const T8&, const T9&) { using std::log; using stan::math::binomial_coefficient_log; using stan::math::log1m; using stan::math::multiply_log; using stan::prob::include_summand; var logp(0); // Special case where negative binomial reduces to Poisson if (alpha > 1e10) { if (include_summand<true>::value) logp -= lgamma(n + 1.0); if (include_summand<true,T_shape>::value || include_summand<true,T_inv_scale>::value) { typename stan::return_type<T_shape, T_inv_scale>::type lambda; lambda = alpha / beta; logp += multiply_log(n, lambda) - lambda; } return logp; } // More typical cases if (include_summand<true,T_shape>::value) if (n != 0) logp += binomial_coefficient_log<typename stan::scalar_type<T_shape>::type> (n + alpha - 1.0, n); if (include_summand<true,T_shape,T_inv_scale>::value) logp += -n * log1p(beta) + alpha * log(beta / (1 + beta)); return logp; } }; const double p = 0.57; const double beta = p / (1.0 - p); TEST(ProbDistributionsNegBinomialCDF,Values) { EXPECT_FLOAT_EQ(0.042817421, stan::prob::neg_binomial_cdf(30, 24, beta)); // Consistency with implemented Binomial EXPECT_FLOAT_EQ(stan::prob::binomial_cdf(24, 54, p), stan::prob::neg_binomial_cdf(30, 24, beta)); } <commit_msg>fixed neg_binomial test<commit_after>// Arguments: Ints, Doubles, Doubles #include <stan/prob/distributions/univariate/discrete/neg_binomial.hpp> #include <stan/prob/distributions/univariate/discrete/binomial.hpp> using std::vector; using std::numeric_limits; using stan::agrad::var; class AgradDistributionsNegBinomial : public AgradDistributionTest { public: void valid_values(vector<vector<double> >& parameters, vector<double>& log_prob) { vector<double> param(3); param[0] = 10; // n param[1] = 2.0; // alpha param[2] = 1.5; // beta parameters.push_back(param); log_prob.push_back(-7.786663); // expected log_prob param[0] = 100; // n param[1] = 3.0; // alpha param[2] = 3.5; // beta parameters.push_back(param); log_prob.push_back(-142.6147); // expected log_prob param[0] = 13; param[1] = 1e11; // alpha > 1e10, causes redux to Poisson param[2] = 1e10; // equiv to Poisson(1e11/1e10) = Poisson(10) parameters.push_back(param); log_prob.push_back(-2.618558); // log poisson(13|10) } void invalid_values(vector<size_t>& index, vector<double>& value) { // n index.push_back(0U); value.push_back(-1); // alpha index.push_back(1U); value.push_back(0); // beta index.push_back(2U); value.push_back(0); } template <class T_n, class T_shape, class T_inv_scale, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9> typename stan::return_type<T_shape,T_inv_scale>::type log_prob(const T_n& n, const T_shape& alpha, const T_inv_scale& beta, const T3&, const T4&, const T5&, const T6&, const T7&, const T8&, const T9&) { return stan::prob::neg_binomial_log(n, alpha, beta); } template <bool propto, class T_n, class T_shape, class T_inv_scale, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9> typename stan::return_type<T_shape,T_inv_scale>::type log_prob(const T_n& n, const T_shape& alpha, const T_inv_scale& beta, const T3&, const T4&, const T5&, const T6&, const T7&, const T8&, const T9&) { return stan::prob::neg_binomial_log<propto>(n, alpha, beta); } template <bool propto, class T_n, class T_shape, class T_inv_scale, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, class Policy> typename stan::return_type<T_shape,T_inv_scale>::type log_prob(const T_n& n, const T_shape& alpha, const T_inv_scale& beta, const T3&, const T4&, const T5&, const T6&, const T7&, const T8&, const T9&) { return stan::prob::neg_binomial_log<propto>(n, alpha, beta, Policy()); } template <class T_n, class T_shape, class T_inv_scale, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9> var log_prob_function(const T_n& n, const T_shape& alpha, const T_inv_scale& beta, const T3&, const T4&, const T5&, const T6&, const T7&, const T8&, const T9&) { using std::log; using stan::math::binomial_coefficient_log; using stan::math::log1m; using stan::math::multiply_log; using stan::prob::include_summand; var logp(0); // Special case where negative binomial reduces to Poisson if (alpha > 1e10) { if (include_summand<true>::value) logp -= lgamma(n + 1.0); if (include_summand<true,T_shape>::value || include_summand<true,T_inv_scale>::value) { typename stan::return_type<T_shape, T_inv_scale>::type lambda; lambda = alpha / beta; logp += multiply_log(n, lambda) - lambda; } return logp; } // More typical cases if (include_summand<true,T_shape>::value) if (n != 0) logp += binomial_coefficient_log<typename stan::scalar_type<T_shape>::type> (n + alpha - 1.0, n); if (include_summand<true,T_shape,T_inv_scale>::value) logp += -n * log1p(beta) + alpha * log(beta / (1 + beta)); return logp; } }; const double p = 0.57; const double beta = p / (1.0 - p); TEST(ProbDistributionsNegBinomialCDF,Values) { EXPECT_FLOAT_EQ(0.042817421, stan::prob::neg_binomial_cdf(30, 24, beta)); // Consistency with implemented Binomial EXPECT_FLOAT_EQ(stan::prob::binomial_cdf(24, 54, p), stan::prob::neg_binomial_cdf(30, 24, beta)); } <|endoftext|>
<commit_before>/* * File: histogramnew.cc * Author: ruehle * * Created on March 11, 2009, 4:29 PM */ #include "histogramnew.h" HistogramNew::HistogramNew() { _min=_max=_step=0; _weight = 1.; _periodic=false; } void HistogramNew::Initialize(double min, double max, int nbins) { _min = min; _max = max; _step = (_max - _min)/nbins; _weight = 1.; _data.resize(nbins); _nbins = nbins; int i; for(double v=_min, i=0; i<nbins; v+=_step,++i) _data.x(i)=v; _data.y()=ub::zero_vector<double>(_nbins); _data.flags()=ub::scalar_vector<char>(_nbins, 'i'); } void HistogramNew::Process(double &v) { int i = (int) ((v - _min) / _step); if (i < 0 || i >= _nbins) { if(!_periodic) return; if(i<0) i = _nbins - ((-i) % _nbins); else i = i % _nbins; } _data.y(i) += _weight; } void HistogramNew::Normalize() { double area = 0; area=ub::norm_1(_data.x()) * _step; _weight /= area; double scale = 1./area; _data.y() *= scale; } void HistogramNew::Clear() { _weight = 1.; _data.y() = ub::zero_vector<double>(_nbins); }<commit_msg>interval now centered around bins<commit_after>/* * File: histogramnew.cc * Author: ruehle * * Created on March 11, 2009, 4:29 PM */ #include "histogramnew.h" HistogramNew::HistogramNew() { _min=_max=_step=0; _weight = 1.; _periodic=false; } void HistogramNew::Initialize(double min, double max, int nbins) { _min = min; _max = max; _step = (_max - _min)/nbins; _weight = 1.; _data.resize(nbins); _nbins = nbins; int i; for(double v=_min, i=0; i<nbins; v+=_step,++i) _data.x(i)=v; _data.y()=ub::zero_vector<double>(_nbins); _data.flags()=ub::scalar_vector<char>(_nbins, 'i'); } void HistogramNew::Process(double &v) { int i = (int) ((v - _min) / _step + 0.5); if (i < 0 || i >= _nbins) { if(!_periodic) return; if(i<0) i = _nbins - ((-i) % _nbins); else i = i % _nbins; } _data.y(i) += _weight; } void HistogramNew::Normalize() { double area = 0; area=ub::norm_1(_data.x()) * _step; _weight /= area; double scale = 1./area; _data.y() *= scale; } void HistogramNew::Clear() { _weight = 1.; _data.y() = ub::zero_vector<double>(_nbins); }<|endoftext|>
<commit_before>/* * Copyright 2009-2021 The VOTCA Development Team * (http://www.votca.org) * * Licensed under the Apache License, Version 2.0 (the "License") * * You may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include "votca/xtp/gaussianwriter.h" #include "votca/xtp/basisset.h" #include <boost/algorithm/string.hpp> #include <boost/format.hpp> #include <sstream> #include <votca/tools/eigenio_matrixmarket.h> namespace votca { namespace xtp { /* * This function converts VOTCA's L enum to the gaussian equivalent. * Gaussian uses a minus sign to indicate spherical shells, but -1 for sp. */ Index GaussianWriter::toGaussianL(L l) const { switch (l) { case L::S: return 0; case L::P: return 1; default: return -1 * static_cast<Index>(l); } } std::string GaussianWriter::reorderedMOCoefficients( const Orbitals& orbitals) const { OrbReorder reorder(gaussianOrder, gaussianMultipliers, true); Eigen::MatrixXd moCoefficients = orbitals.MOs().eigenvectors(); reorder.reorderOrbitals(moCoefficients, orbitals.SetupDftBasis()); // put the reordered mos in a string std::stringstream mos_string; int temp_int = 1; for (Index i = 0; i < moCoefficients.rows(); ++i) { for (Index j = 0; j < moCoefficients.cols(); ++j) { mos_string << boost::format("%16.8e") % moCoefficients(j, i); if (temp_int % 5 == 0) { mos_string << "\n"; } temp_int++; } } mos_string << ((temp_int - 1) % 5 == 0 ? "" : "\n"); return mos_string.str(); } std::string GaussianWriter::densityMatrixToString( const Orbitals& orbitals) const { OrbReorder reorder(gaussianOrder, gaussianMultipliers, true); Eigen::MatrixXd density = orbitals.DensityMatrixGroundState(); reorder.reorderOperator(density, orbitals.SetupDftBasis()); // put the reordered mos in a string std::stringstream density_string; int temp_int = 1; for (Index i = 0; i < density.rows(); ++i) { for (Index j = 0; j <= i; ++j) { density_string << boost::format("%16.8e") % density(i, j); if (temp_int % 5 == 0) { density_string << "\n"; } temp_int++; } } density_string << ((temp_int - 1) % 5 == 0 ? "" : "\n"); return density_string.str(); } void GaussianWriter::WriteFile(const std::string& basename, const Orbitals& orbitals) const { if (!orbitals.hasDFTbasisName()) { throw std::runtime_error(".orb file does not contain a basisset name"); } AOBasis basis = orbitals.SetupDftBasis(); std::ofstream outFile(basename + ".fchk"); if (outFile.is_open()) { XTP_LOG(Log::error, _log) << "Start writing to " << (basename + ".fchk") << std::flush; int temp_int; // job description outFile << basename << ", fchk created by VOTCA-XTP\n"; outFile << "SP RHF " << orbitals.getDFTbasisName() << "\n"; // clang-format off outFile << boost::format("%-43s%-2s%15d\n") % "Number of atoms" % "I" % orbitals.QMAtoms().size(); outFile << boost::format("%-43s%-2s%15d\n") % "Charge" % "I" % 0; outFile << boost::format("%-43s%-2s%15d\n") % "Multiplicity" % "I" % 1; outFile << boost::format("%-43s%-2s%15d\n") % "Number of electrons" % "I" % (2*orbitals.getNumberOfAlphaElectrons()); outFile << boost::format("%-43s%-2s%15d\n") % "Number of alpha electrons" % "I" % orbitals.getNumberOfAlphaElectrons(); outFile << boost::format("%-43s%-2s%15d\n") % "Number of beta electrons" % "I" % orbitals.getNumberOfAlphaElectrons(); outFile << boost::format("%-43s%-2s%15d\n") % "Number of basis functions" % "I" % basis.AOBasisSize(); outFile << boost::format("%-43s%-2s%15d\n") % "Number of independent functions" % "I" % basis.AOBasisSize(); // clang-format on // ATOMIC NUMBERS outFile << boost::format("%-43s%-2s N= %10d\n") % "Atomic numbers" % "I" % orbitals.QMAtoms().size(); temp_int = 1; for (const auto& atom : orbitals.QMAtoms()) { outFile << boost::format("%12d") % atom.getElementNumber(); if (temp_int % 6 == 0) { outFile << "\n"; } temp_int++; } outFile << ((temp_int - 1) % 6 == 0 ? "" : "\n"); // NUCLEAR CHARGES outFile << boost::format("%-43s%-2s N= %10d\n") % "Nuclear charges" % "R" % orbitals.QMAtoms().size(); temp_int = 1; for (const auto& atom : orbitals.QMAtoms()) { outFile << boost::format("%16.8e") % (double)atom.getNuccharge(); if (temp_int % 5 == 0) { outFile << "\n"; } temp_int++; } outFile << ((temp_int - 1) % 5 == 0 ? "" : "\n"); // CURRENT CARTESIAN COORDINATES outFile << boost::format("%-43s%-2s N= %10d\n") % "Current cartesian coordinates" % "R" % (3 * orbitals.QMAtoms().size()); temp_int = 1; for (const auto& atom : orbitals.QMAtoms()) { for (int i = 0; i < 3; ++i) { outFile << boost::format("%16.8e") % atom.getPos()(i); if (temp_int % 5 == 0) { outFile << "\n"; } temp_int++; } } outFile << ((temp_int - 1) % 5 == 0 ? "" : "\n"); // NUMBER OF PRIMITIVE SHELLS outFile << boost::format("%-43s%-2s%15d\n") % "Number of primitive shells" % "I" % basis.getNumberOfPrimitives(); // NUMBER OF CONTRACTED SHELLS outFile << boost::format("%-43s%-2s%15d\n") % "Number of contracted shells" % "I" % basis.getNumofShells(); // PURE/CARTESIAN D outFile << boost::format("%-43s%-2s%15d\n") % "Pure/Cartesian d shells " % "I" % 0; // PURE/CARTESIAN F outFile << boost::format("%-43s%-2s%15d\n") % "Pure/Cartesian f shells " % "I" % 0; // HIGHEST ANGULAR MOMENTUM outFile << boost::format("%-43s%-2s%15d\n") % "Highest angular momentum " % "I" % basis.getMaxL(); // HIGHEST ANGULAR MOMENTUM outFile << boost::format("%-43s%-2s%15d\n") % "Largest degree of contraction " % "I" % basis.getMaxNprim(); // SHELL TYPES outFile << boost::format("%-43s%-2s N= %10d\n") % "Shell types" % "I" % (basis.getNumofShells()); temp_int = 1; for (const auto& shell : basis) { outFile << boost::format("%12d") % toGaussianL(shell.getL()); if (temp_int % 6 == 0) { outFile << "\n"; } temp_int++; } outFile << ((temp_int - 1) % 6 == 0 ? "" : "\n"); // NR OF PRIMITIVES PER SHELL outFile << boost::format("%-43s%-2s N= %10d\n") % "Number of primitives per shell" % "I" % (basis.getNumofShells()); temp_int = 1; for (const AOShell& shell : basis) { outFile << boost::format("%12d") % shell.getSize(); if (temp_int % 6 == 0) { outFile << "\n"; } temp_int++; } outFile << ((temp_int - 1) % 6 == 0 ? "" : "\n"); // SHELL TO ATOM MAP outFile << boost::format("%-43s%-2s N= %10d\n") % "Shell to atom map" % "I" % (basis.getNumofShells()); temp_int = 1; for (const AOShell& shell : basis) { // Gaussian indices start at 1, hence the + 1 outFile << boost::format("%12d") % (shell.getAtomIndex() + 1); if (temp_int % 6 == 0) { outFile << "\n"; } temp_int++; } outFile << ((temp_int - 1) % 6 == 0 ? "" : "\n"); // PRIMITIVE EXPONENTS outFile << boost::format("%-43s%-2s N= %10d\n") % "Primitive exponents" % "R" % basis.getNumberOfPrimitives(); temp_int = 1; for (const AOShell& shell : basis) { for (const AOGaussianPrimitive& prim : shell) { outFile << boost::format("%16.8e") % prim.getDecay(); if (temp_int % 5 == 0) { outFile << "\n"; } temp_int++; } } outFile << ((temp_int - 1) % 5 == 0 ? "" : "\n"); // CONTRACTION COEFFICIENTS outFile << boost::format("%-43s%-2s N= %10d\n") % "Contraction coefficients" % "R" % basis.getNumberOfPrimitives(); temp_int = 1; for (const AOShell& shell : basis) { for (const AOGaussianPrimitive& prim : shell) { outFile << boost::format("%16.8e") % prim.getContraction(); if (temp_int % 5 == 0) { outFile << "\n"; } temp_int++; } } outFile << ((temp_int - 1) % 5 == 0 ? "" : "\n"); // SHELL COORDINATES outFile << boost::format("%-43s%-2s N= %10d\n") % "Coordinates of each shell" % "R" % (3 * basis.getNumofShells()); temp_int = 1; for (const AOShell& shell : basis) { for (int i = 0; i < 3; ++i) { outFile << boost::format("%16.8e") % shell.getPos()(i); if (temp_int % 5 == 0) { outFile << "\n"; } temp_int++; } } outFile << ((temp_int - 1) % 5 == 0 ? "" : "\n"); // TOTAL ENERGY outFile << boost::format("%-43s%-2s%22.15e\n") % "Total Energy" % "R" % orbitals.getDFTTotalEnergy(); // ALPHA ORBITAL ENERGIES outFile << boost::format("%-43s%-2s N= %10d\n") % "Alpha Orbital Energies" % "R" % orbitals.MOs().eigenvalues().size(); temp_int = 1; for (Index i = 0; i < orbitals.MOs().eigenvalues().size(); ++i) { outFile << boost::format("%16.8e") % orbitals.MOs().eigenvalues()[i]; if (temp_int % 5 == 0) { outFile << "\n"; } temp_int++; } outFile << ((temp_int - 1) % 5 == 0 ? "" : "\n"); // ALPHA ORBITAL ENERGIES outFile << boost::format("%-43s%-2s N= %10d\n") % "Alpha MO coefficients" % "R" % (orbitals.MOs().eigenvalues().size() * orbitals.MOs().eigenvalues().size()); outFile << reorderedMOCoefficients(orbitals); // DENSITY MATRIX outFile << boost::format("%-43s%-2s N= %10d\n") % "Total SCF Density" % "R" % ((orbitals.MOs().eigenvalues().size() * (orbitals.MOs().eigenvalues().size() - 1)) / 2 + orbitals.MOs().eigenvalues().size()); outFile << densityMatrixToString(orbitals); XTP_LOG(Log::error, _log) << "Done writing \n" << std::flush; } } } // namespace xtp } // namespace votca<commit_msg>Format code using clang-format version 11.0.0 (Fedora 11.0.0-2.fc33)<commit_after>/* * Copyright 2009-2021 The VOTCA Development Team * (http://www.votca.org) * * Licensed under the Apache License, Version 2.0 (the "License") * * You may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include "votca/xtp/gaussianwriter.h" #include "votca/xtp/basisset.h" #include <boost/algorithm/string.hpp> #include <boost/format.hpp> #include <sstream> #include <votca/tools/eigenio_matrixmarket.h> namespace votca { namespace xtp { /* * This function converts VOTCA's L enum to the gaussian equivalent. * Gaussian uses a minus sign to indicate spherical shells, but -1 for sp. */ Index GaussianWriter::toGaussianL(L l) const { switch (l) { case L::S: return 0; case L::P: return 1; default: return -1 * static_cast<Index>(l); } } std::string GaussianWriter::reorderedMOCoefficients( const Orbitals& orbitals) const { OrbReorder reorder(gaussianOrder, gaussianMultipliers, true); Eigen::MatrixXd moCoefficients = orbitals.MOs().eigenvectors(); reorder.reorderOrbitals(moCoefficients, orbitals.SetupDftBasis()); // put the reordered mos in a string std::stringstream mos_string; int temp_int = 1; for (Index i = 0; i < moCoefficients.rows(); ++i) { for (Index j = 0; j < moCoefficients.cols(); ++j) { mos_string << boost::format("%16.8e") % moCoefficients(j, i); if (temp_int % 5 == 0) { mos_string << "\n"; } temp_int++; } } mos_string << ((temp_int - 1) % 5 == 0 ? "" : "\n"); return mos_string.str(); } std::string GaussianWriter::densityMatrixToString( const Orbitals& orbitals) const { OrbReorder reorder(gaussianOrder, gaussianMultipliers, true); Eigen::MatrixXd density = orbitals.DensityMatrixGroundState(); reorder.reorderOperator(density, orbitals.SetupDftBasis()); // put the reordered mos in a string std::stringstream density_string; int temp_int = 1; for (Index i = 0; i < density.rows(); ++i) { for (Index j = 0; j <= i; ++j) { density_string << boost::format("%16.8e") % density(i, j); if (temp_int % 5 == 0) { density_string << "\n"; } temp_int++; } } density_string << ((temp_int - 1) % 5 == 0 ? "" : "\n"); return density_string.str(); } void GaussianWriter::WriteFile(const std::string& basename, const Orbitals& orbitals) const { if (!orbitals.hasDFTbasisName()) { throw std::runtime_error(".orb file does not contain a basisset name"); } AOBasis basis = orbitals.SetupDftBasis(); std::ofstream outFile(basename + ".fchk"); if (outFile.is_open()) { XTP_LOG(Log::error, _log) << "Start writing to " << (basename + ".fchk") << std::flush; int temp_int; // job description outFile << basename << ", fchk created by VOTCA-XTP\n"; outFile << "SP RHF " << orbitals.getDFTbasisName() << "\n"; // clang-format off outFile << boost::format("%-43s%-2s%15d\n") % "Number of atoms" % "I" % orbitals.QMAtoms().size(); outFile << boost::format("%-43s%-2s%15d\n") % "Charge" % "I" % 0; outFile << boost::format("%-43s%-2s%15d\n") % "Multiplicity" % "I" % 1; outFile << boost::format("%-43s%-2s%15d\n") % "Number of electrons" % "I" % (2*orbitals.getNumberOfAlphaElectrons()); outFile << boost::format("%-43s%-2s%15d\n") % "Number of alpha electrons" % "I" % orbitals.getNumberOfAlphaElectrons(); outFile << boost::format("%-43s%-2s%15d\n") % "Number of beta electrons" % "I" % orbitals.getNumberOfAlphaElectrons(); outFile << boost::format("%-43s%-2s%15d\n") % "Number of basis functions" % "I" % basis.AOBasisSize(); outFile << boost::format("%-43s%-2s%15d\n") % "Number of independent functions" % "I" % basis.AOBasisSize(); // clang-format on // ATOMIC NUMBERS outFile << boost::format("%-43s%-2s N= %10d\n") % "Atomic numbers" % "I" % orbitals.QMAtoms().size(); temp_int = 1; for (const auto& atom : orbitals.QMAtoms()) { outFile << boost::format("%12d") % atom.getElementNumber(); if (temp_int % 6 == 0) { outFile << "\n"; } temp_int++; } outFile << ((temp_int - 1) % 6 == 0 ? "" : "\n"); // NUCLEAR CHARGES outFile << boost::format("%-43s%-2s N= %10d\n") % "Nuclear charges" % "R" % orbitals.QMAtoms().size(); temp_int = 1; for (const auto& atom : orbitals.QMAtoms()) { outFile << boost::format("%16.8e") % (double)atom.getNuccharge(); if (temp_int % 5 == 0) { outFile << "\n"; } temp_int++; } outFile << ((temp_int - 1) % 5 == 0 ? "" : "\n"); // CURRENT CARTESIAN COORDINATES outFile << boost::format("%-43s%-2s N= %10d\n") % "Current cartesian coordinates" % "R" % (3 * orbitals.QMAtoms().size()); temp_int = 1; for (const auto& atom : orbitals.QMAtoms()) { for (int i = 0; i < 3; ++i) { outFile << boost::format("%16.8e") % atom.getPos()(i); if (temp_int % 5 == 0) { outFile << "\n"; } temp_int++; } } outFile << ((temp_int - 1) % 5 == 0 ? "" : "\n"); // NUMBER OF PRIMITIVE SHELLS outFile << boost::format("%-43s%-2s%15d\n") % "Number of primitive shells" % "I" % basis.getNumberOfPrimitives(); // NUMBER OF CONTRACTED SHELLS outFile << boost::format("%-43s%-2s%15d\n") % "Number of contracted shells" % "I" % basis.getNumofShells(); // PURE/CARTESIAN D outFile << boost::format("%-43s%-2s%15d\n") % "Pure/Cartesian d shells " % "I" % 0; // PURE/CARTESIAN F outFile << boost::format("%-43s%-2s%15d\n") % "Pure/Cartesian f shells " % "I" % 0; // HIGHEST ANGULAR MOMENTUM outFile << boost::format("%-43s%-2s%15d\n") % "Highest angular momentum " % "I" % basis.getMaxL(); // HIGHEST ANGULAR MOMENTUM outFile << boost::format("%-43s%-2s%15d\n") % "Largest degree of contraction " % "I" % basis.getMaxNprim(); // SHELL TYPES outFile << boost::format("%-43s%-2s N= %10d\n") % "Shell types" % "I" % (basis.getNumofShells()); temp_int = 1; for (const auto& shell : basis) { outFile << boost::format("%12d") % toGaussianL(shell.getL()); if (temp_int % 6 == 0) { outFile << "\n"; } temp_int++; } outFile << ((temp_int - 1) % 6 == 0 ? "" : "\n"); // NR OF PRIMITIVES PER SHELL outFile << boost::format("%-43s%-2s N= %10d\n") % "Number of primitives per shell" % "I" % (basis.getNumofShells()); temp_int = 1; for (const AOShell& shell : basis) { outFile << boost::format("%12d") % shell.getSize(); if (temp_int % 6 == 0) { outFile << "\n"; } temp_int++; } outFile << ((temp_int - 1) % 6 == 0 ? "" : "\n"); // SHELL TO ATOM MAP outFile << boost::format("%-43s%-2s N= %10d\n") % "Shell to atom map" % "I" % (basis.getNumofShells()); temp_int = 1; for (const AOShell& shell : basis) { // Gaussian indices start at 1, hence the + 1 outFile << boost::format("%12d") % (shell.getAtomIndex() + 1); if (temp_int % 6 == 0) { outFile << "\n"; } temp_int++; } outFile << ((temp_int - 1) % 6 == 0 ? "" : "\n"); // PRIMITIVE EXPONENTS outFile << boost::format("%-43s%-2s N= %10d\n") % "Primitive exponents" % "R" % basis.getNumberOfPrimitives(); temp_int = 1; for (const AOShell& shell : basis) { for (const AOGaussianPrimitive& prim : shell) { outFile << boost::format("%16.8e") % prim.getDecay(); if (temp_int % 5 == 0) { outFile << "\n"; } temp_int++; } } outFile << ((temp_int - 1) % 5 == 0 ? "" : "\n"); // CONTRACTION COEFFICIENTS outFile << boost::format("%-43s%-2s N= %10d\n") % "Contraction coefficients" % "R" % basis.getNumberOfPrimitives(); temp_int = 1; for (const AOShell& shell : basis) { for (const AOGaussianPrimitive& prim : shell) { outFile << boost::format("%16.8e") % prim.getContraction(); if (temp_int % 5 == 0) { outFile << "\n"; } temp_int++; } } outFile << ((temp_int - 1) % 5 == 0 ? "" : "\n"); // SHELL COORDINATES outFile << boost::format("%-43s%-2s N= %10d\n") % "Coordinates of each shell" % "R" % (3 * basis.getNumofShells()); temp_int = 1; for (const AOShell& shell : basis) { for (int i = 0; i < 3; ++i) { outFile << boost::format("%16.8e") % shell.getPos()(i); if (temp_int % 5 == 0) { outFile << "\n"; } temp_int++; } } outFile << ((temp_int - 1) % 5 == 0 ? "" : "\n"); // TOTAL ENERGY outFile << boost::format("%-43s%-2s%22.15e\n") % "Total Energy" % "R" % orbitals.getDFTTotalEnergy(); // ALPHA ORBITAL ENERGIES outFile << boost::format("%-43s%-2s N= %10d\n") % "Alpha Orbital Energies" % "R" % orbitals.MOs().eigenvalues().size(); temp_int = 1; for (Index i = 0; i < orbitals.MOs().eigenvalues().size(); ++i) { outFile << boost::format("%16.8e") % orbitals.MOs().eigenvalues()[i]; if (temp_int % 5 == 0) { outFile << "\n"; } temp_int++; } outFile << ((temp_int - 1) % 5 == 0 ? "" : "\n"); // ALPHA ORBITAL ENERGIES outFile << boost::format("%-43s%-2s N= %10d\n") % "Alpha MO coefficients" % "R" % (orbitals.MOs().eigenvalues().size() * orbitals.MOs().eigenvalues().size()); outFile << reorderedMOCoefficients(orbitals); // DENSITY MATRIX outFile << boost::format("%-43s%-2s N= %10d\n") % "Total SCF Density" % "R" % ((orbitals.MOs().eigenvalues().size() * (orbitals.MOs().eigenvalues().size() - 1)) / 2 + orbitals.MOs().eigenvalues().size()); outFile << densityMatrixToString(orbitals); XTP_LOG(Log::error, _log) << "Done writing \n" << std::flush; } } } // namespace xtp } // namespace votca<|endoftext|>
<commit_before>//============================================================================================================= /** * @file test_mne_project_to_surface.cpp * @author Ruben Dörfel <doerfelruben@aol.com> * @since 0.1.6 * @date August, 2020 * * @section LICENSE * * Copyright (C) 2020, Ruben Dörfel. 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 MNE-CPP authors 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. * * * @brief Test the MNEProjectToSurface class.. * */ //============================================================================================================= // INCLUDES //============================================================================================================= #include <utils/generics/applicationlogger.h> #include <mne/mne_project_to_surface.h> #include <mne/mne_bem.h> #include <mne/mne_bem_surface.h> #include <utils/ioutils.h> //============================================================================================================= // QT INCLUDES //============================================================================================================= #include <QtCore/QCoreApplication> #include <QtTest> //============================================================================================================= // Eigen //============================================================================================================= #include <Eigen/Dense> //============================================================================================================= // Using NAMESPACE //============================================================================================================= using namespace MNELIB; using namespace Eigen; //============================================================================================================= /** * DECLARE CLASS TestMNEProjectToSurface * * @brief The TestMNEProjectToSurface class provides read write read fiff verification tests * */ class TestMNEProjectToSurface: public QObject { Q_OBJECT public: TestMNEProjectToSurface(); private slots: void initTestCase(); void compareValue(); // add other compareFunctions here void cleanupTestCase(); private: // declare your thresholds, variables and error values here double dEpsilon; MatrixXf matResult; MatrixXd matRef; }; //============================================================================================================= TestMNEProjectToSurface::TestMNEProjectToSurface() : dEpsilon(0.000001) { } //============================================================================================================= void TestMNEProjectToSurface::initTestCase() { QFile t_fileBem(QCoreApplication::applicationDirPath() + "/mne-cpp-test-data/subjects/sample/bem/sample-1280-1280-1280-bem.fif"); QString sRef(QCoreApplication::applicationDirPath() + "/mne-cpp-test-data/Result/mne_project_to_surface.txt"); MNEBem bemHead(t_fileBem); MNEBemSurface::SPtr bemSurface = MNEBemSurface::SPtr::create(bemHead[0]); MNEProjectToSurface::SPtr mneSurfacePoints = MNEProjectToSurface::SPtr::create(*bemSurface); VectorXi vecNearest; // Triangle of the new point VectorXf vecDist; // The Distance between matX and matP MatrixXf matPointsShifted = bemSurface->rr.cast<float>() * 1.1; // Move all points with same amout from surface int iNP = matPointsShifted.rows(); mneSurfacePoints->mne_find_closest_on_surface(matPointsShifted, iNP, matResult, vecNearest, vecDist); // read reference // UTILSLIB::IOUtils::write_eigen_matrix(matResult,sRef); UTILSLIB::IOUtils::read_eigen_matrix(matRef,sRef); } //============================================================================================================= void TestMNEProjectToSurface::compareValue() { // check if MNEProjectToSurface was able to get original points on surface MatrixXf matDiff = matRef.cast<float>() - matResult; qDebug() << "Summed Difference: " << std::abs(matDiff.sum()); QVERIFY(std::abs(matDiff.sum()) < dEpsilon); } //============================================================================================================= void TestMNEProjectToSurface::cleanupTestCase() { } //============================================================================================================= // MAIN //============================================================================================================= QTEST_GUILESS_MAIN(TestMNEProjectToSurface) #include "test_mne_project_to_surface.moc" <commit_msg>Maint: apply change requests<commit_after>//============================================================================================================= /** * @file test_mne_project_to_surface.cpp * @author Ruben Dörfel <doerfelruben@aol.com> * @since 0.1.6 * @date August, 2020 * * @section LICENSE * * Copyright (C) 2020, Ruben Dörfel. 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 MNE-CPP authors 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. * * * @brief Test the MNEProjectToSurface class. * */ //============================================================================================================= // INCLUDES //============================================================================================================= #include <utils/generics/applicationlogger.h> #include <mne/mne_project_to_surface.h> #include <mne/mne_bem.h> #include <mne/mne_bem_surface.h> #include <utils/ioutils.h> //============================================================================================================= // QT INCLUDES //============================================================================================================= #include <QtCore/QCoreApplication> #include <QtTest> //============================================================================================================= // Eigen //============================================================================================================= #include <Eigen/Dense> //============================================================================================================= // Using NAMESPACE //============================================================================================================= using namespace MNELIB; using namespace Eigen; //============================================================================================================= /** * DECLARE CLASS TestMNEProjectToSurface * * @brief The TestMNEProjectToSurface class provides MNEProjectToSurface verification tests * */ class TestMNEProjectToSurface: public QObject { Q_OBJECT public: TestMNEProjectToSurface(); private slots: void initTestCase(); void compareValue(); void cleanupTestCase(); private: // declare thresholds, and variables double dEpsilon; MatrixXf matResult; MatrixXd matRef; }; //============================================================================================================= TestMNEProjectToSurface::TestMNEProjectToSurface() : dEpsilon(0.000001) { } //============================================================================================================= void TestMNEProjectToSurface::initTestCase() { QFile t_fileBem(QCoreApplication::applicationDirPath() + "/mne-cpp-test-data/subjects/sample/bem/sample-1280-1280-1280-bem.fif"); QString sRef(QCoreApplication::applicationDirPath() + "/mne-cpp-test-data/Result/mne_project_to_surface.txt"); MNEBem bemHead(t_fileBem); MNEBemSurface::SPtr bemSurface = MNEBemSurface::SPtr::create(bemHead[0]); MNEProjectToSurface::SPtr mneSurfacePoints = MNEProjectToSurface::SPtr::create(*bemSurface); VectorXi vecNearest; // Triangle of the new point VectorXf vecDist; // The Distance between matX and matP MatrixXf matPointsShifted = bemSurface->rr.cast<float>() * 1.1; // Move all points with same amout from surface int iNP = matPointsShifted.rows(); mneSurfacePoints->mne_find_closest_on_surface(matPointsShifted, iNP, matResult, vecNearest, vecDist); // read reference UTILSLIB::IOUtils::read_eigen_matrix(matRef,sRef); } //============================================================================================================= void TestMNEProjectToSurface::compareValue() { // check if MNEProjectToSurface was able to get original points on surface MatrixXf matDiff = matRef.cast<float>() - matResult; qDebug() << "Summed Difference: " << std::abs(matDiff.sum()); QVERIFY(std::abs(matDiff.sum()) < dEpsilon); } //============================================================================================================= void TestMNEProjectToSurface::cleanupTestCase() { } //============================================================================================================= // MAIN //============================================================================================================= QTEST_GUILESS_MAIN(TestMNEProjectToSurface) #include "test_mne_project_to_surface.moc" <|endoftext|>
<commit_before> <commit_msg>Delete output.hpp<commit_after><|endoftext|>
<commit_before>#include <iostream> #include <cstdlib> #include <cmath> #include <cstdio> #include "consts.h" #include "circuits/circuit.h" #include "matrix/newtonraphson.h" using namespace std; static const int MAX_ATTEMPTS = 10; static const int MAX_LOOPS = 100; static const double TOLERANCE = 1e-9; void randomize(int numVariables, double solution[MAX_NODES+1]){ solution[0]; // gnd for(int i=1; i<=numVariables; i++){ solution[i] = (double) (rand()%10); } } double calcDistance(int numVariables, double x[MAX_NODES+1], double y[MAX_NODES+1]){ double sum=0; double distance=0; for(int i=1; i<=numVariables ;i++) { sum += pow((x[i]-y[i]),2); } distance = sqrt(sum); return distance; } void printSolution(int numVariables, double solution[MAX_NODES+1]){ for(int i=1; i<=numVariables; i++){ cout << solution[i] << endl; } cout << endl; } int runNewtonRaphson(Circuit circuit, double (&finalSolution)[MAX_NODES+1], double t, double (&lastSolution)[MAX_NODES+1]){ int rc=0; int numAttempts=0; int numLoops=0; bool converged=false; double solution[MAX_NODES+1]; double distance=0; double previousSolution[MAX_NODES+1]; double Yn[MAX_NODES+1][MAX_NODES+2]; while(!converged && numAttempts <= MAX_ATTEMPTS ){ numAttempts++; numLoops=0; while(!converged && numLoops <= MAX_LOOPS){ numLoops++; init(circuit.getNumVariables(), Yn); circuit.applyStamps(Yn, previousSolution, t, lastSolution); rc = solve(circuit.getNumVariables(), Yn); if (rc) // Let's try a new randomized initial solution! break; getSolution(circuit.getNumVariables(), Yn, solution); distance = calcDistance(circuit.getNumVariables(), solution, previousSolution); if (distance < TOLERANCE){ converged = true; solution[0] = 0; // Ground! copySolution(circuit.getNumVariables(), solution, finalSolution); } else { copySolution(circuit.getNumVariables(), solution, previousSolution); } } if (!converged){ cout << "Newton Raphson did not converge."; return (EXIT_FAILURE); } } return 0; } <commit_msg>Fixes lack of randomization<commit_after>#include <iostream> #include <cstdlib> #include <cmath> #include <cstdio> #include "consts.h" #include "circuits/circuit.h" #include "matrix/newtonraphson.h" using namespace std; static const int MAX_ATTEMPTS = 10; static const int MAX_LOOPS = 100; static const double TOLERANCE = 1e-9; void randomize(int numVariables, double solution[MAX_NODES+1]){ solution[0]; // gnd for(int i=1; i<=numVariables; i++){ solution[i] = (double) (rand()%10); } } double calcDistance(int numVariables, double x[MAX_NODES+1], double y[MAX_NODES+1]){ double sum=0; double distance=0; for(int i=1; i<=numVariables ;i++) { sum += pow((x[i]-y[i]),2); } distance = sqrt(sum); return distance; } void printSolution(int numVariables, double solution[MAX_NODES+1]){ for(int i=1; i<=numVariables; i++){ cout << solution[i] << endl; } cout << endl; } int runNewtonRaphson(Circuit circuit, double (&finalSolution)[MAX_NODES+1], double t, double (&lastSolution)[MAX_NODES+1]){ int rc=0; int numAttempts=0; int numLoops=0; bool converged=false; double solution[MAX_NODES+1]; double distance=0; double previousSolution[MAX_NODES+1]; double Yn[MAX_NODES+1][MAX_NODES+2]; while(!converged && numAttempts <= MAX_ATTEMPTS ){ numAttempts++; numLoops=0; randomize(circuit.getNumVariables(), previousSolution); while(!converged && numLoops <= MAX_LOOPS){ numLoops++; init(circuit.getNumVariables(), Yn); circuit.applyStamps(Yn, previousSolution, t, lastSolution); rc = solve(circuit.getNumVariables(), Yn); if (rc) // Let's try a new randomized initial solution! break; getSolution(circuit.getNumVariables(), Yn, solution); distance = calcDistance(circuit.getNumVariables(), solution, previousSolution); if (distance < TOLERANCE){ converged = true; solution[0] = 0; // Ground! copySolution(circuit.getNumVariables(), solution, finalSolution); } else { copySolution(circuit.getNumVariables(), solution, previousSolution); } } if (!converged){ cout << "Newton Raphson did not converge."; return (EXIT_FAILURE); } } return 0; } <|endoftext|>
<commit_before>#include "parser.h" #include "ast.h" #include "utils.h" #include "token.h" #include "exceptions.h" #include <string> #include <vector> #include <fstream> #include <iostream> namespace sota { std::string Parser::Load(const std::string &filename) { if (!exists(filename)) SotaException(filename + " doesn't exist or is unreadable"); std::ifstream file(filename); std::string text((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>()); return text; } Token Parser::Take(Token token) { if (token) _tokens.push_back(token); return token; } Token Parser::Emit() { Token token = Token(); if (_tokens.size()) { token = _tokens.front(); _tokens.pop_front(); } return token; } Token Parser::Scan() { if (index < source.length()) { size_t end = index; Symbol *match = nullptr; for (auto kvp : symbols) { auto symbol = kvp.second; size_t pos = symbol->scan(symbol, source.substr(index, source.length() - index), index); if (pos > end || (match != nullptr && symbol->lbp > match->lbp && pos == end)) { match = symbol; end = pos; } } if (index == end) throw SotaException("Parser::Scan: invalid symbol"); return Token(*match, source, index, end - index); } return Token(); } /*public*/ Parser::Parser(const Types2Symbols &symbols) : symbols(symbols) , source("") , index(0) {} Ast * Parser::ParseFile(const std::string &filename) { auto source = Load(filename); return Parse(source); } Ast * Parser::Parse(std::string source) { this->source = source; return Parse(); } Ast * Parser::Parse(size_t lbp/* = 0 */) { Token token = Consume(); Ast *left = token.Nud(this, &token); std::cout << "lbp: " << lbp << " token.symbol.lbp: " << token.symbol.lbp << std::endl; while (lbp < token.symbol.lbp) { std::cout << "lbp test passed" << std::endl; Token token = Consume(); left = token.Led(this, left, &token); } return left; } Token Parser::LookAhead(size_t distance) { Token token; while(distance >= _tokens.size()) token = Take(Scan()); if (token) return token; return Scan(); } Token Parser::Consume() { if (auto token = Emit()) return token; return Scan(); } Token Parser::Consume(const size_t &expected, const std::string &message) { auto token = Consume(); if (token.symbol.type != expected) throw SotaException(message); return token; } size_t Parser::Line() { return 0; } size_t Parser::Column() { return 0; } } <commit_msg>got lookahead working but not skipping ws yet... -sai<commit_after>#include "parser.h" #include "ast.h" #include "utils.h" #include "token.h" #include "exceptions.h" #include <string> #include <vector> #include <fstream> #include <iostream> namespace sota { std::string Parser::Load(const std::string &filename) { if (!exists(filename)) SotaException(filename + " doesn't exist or is unreadable"); std::ifstream file(filename); std::string text((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>()); return text; } Token Parser::Take(Token token) { if (token) _tokens.push_back(token); return token; } Token Parser::Emit() { Token token = Token(); if (_tokens.size()) { token = _tokens.front(); _tokens.pop_front(); } return token; } Token Parser::Scan() { if (index < source.length()) { size_t end = index; Symbol *match = nullptr; for (auto kvp : symbols) { auto symbol = kvp.second; size_t pos = symbol->scan(symbol, source.substr(index, source.length() - index), index); if (pos > end || (match != nullptr && symbol->lbp > match->lbp && pos == end)) { match = symbol; end = pos; } } if (index == end) throw SotaException("Parser::Scan: invalid symbol"); return Token(*match, source, index, end - index); } return Token(); } /*public*/ Parser::Parser(const Types2Symbols &symbols) : symbols(symbols) , source("") , index(0) {} Ast * Parser::ParseFile(const std::string &filename) { auto source = Load(filename); return Parse(source); } Ast * Parser::Parse(std::string source) { this->source = source; return Parse(); } Ast * Parser::Parse(size_t lbp/* = 0 */) { Token curr = Consume(); std::cout << "curr: " << curr << std::endl; Ast *left = curr.Nud(this, &curr); Token next = LookAhead(1); std::cout << "next: " << next << std::endl; std::cout << "lbp: " << lbp << " next.symbol.lbp: " << next.symbol.lbp << std::endl; while (lbp < next.symbol.lbp) { std::cout << "lbp test passed" << std::endl; Token next = Consume(); left = next.Led(this, left, &next); } return left; } Token Parser::LookAhead(size_t distance) { if (distance == 0) { return Scan(); } Token token; while(distance > _tokens.size()) { token = Take(Scan()); } return token; } Token Parser::Consume() { auto la = LookAhead(1); index += la.length; return Emit(); } Token Parser::Consume(const size_t &expected, const std::string &message) { auto token = Consume(); if (token.symbol.type != expected) throw SotaException(message); return token; } size_t Parser::Line() { return 0; } size_t Parser::Column() { return 0; } } <|endoftext|>
<commit_before>#include <stdio.h> #include "ys_matrixTool.h" #include "ys_matrix.h" using namespace ys; int main(void) { DMatrix<int> matrix1; matrix1[0][0] = 7; matrix1[0][1] = 6; matrix1[0][2] = 2; matrix1[1][0] = 3; matrix1[1][1] = 2; matrix1[1][2] = 5; for (int i = 0; i < matrix1.getDimX(); ++i) { for (int j = 0; j < matrix1.getDimY(); ++j) { printf ("%d ", matrix1[i][j]); } printf ("\n"); } printf ("----------------------------\n"); DMatrix<int> matrix2; matrix1[0][0] = 8; matrix1[0][1] = 9; matrix1[1][0] = 1; matrix1[1][1] = 6; matrix1[2][0] = 3; matrix1[2][1] = 8; for (int i = 0; i < matrix2.getDimX(); ++i) { for (int j = 0; j < matrix2.getDimY(); ++j) { printf ("%d ", matrix2[i][j]); } printf ("\n"); } printf ("----------------------------\n"); DMatrix<int>* matrix3 = Matrixs<int>::mul(matrix1, matrix2); for (int i = 0; i < matrix3->getDimX(); ++i) { for (int j = 0; j < matrix3->getDimY(); ++j) { printf ("%d ", matrix3[i][j]); } printf ("\n"); } delete matrix3; return 0; } <commit_msg>modify<commit_after>#include <stdio.h> #include "ys_matrixTool.h" #include "ys_matrix.h" using namespace ys; int main(void) { DMatrix<int> matrix1(2, 3); printf ("1\n"); matrix1[0][0] = 7; printf ("1\n"); matrix1[0][1] = 6; matrix1[0][2] = 2; matrix1[1][0] = 3; matrix1[1][1] = 2; matrix1[1][2] = 5; for (int i = 0; i < matrix1.getDimX(); ++i) { for (int j = 0; j < matrix1.getDimY(); ++j) { printf ("%d ", matrix1[i][j]); } printf ("\n"); } printf ("----------------------------\n"); DMatrix<int> matrix2(3, 4); matrix1[0][0] = 8; matrix1[0][1] = 9; matrix1[1][0] = 1; matrix1[1][1] = 6; matrix1[2][0] = 3; matrix1[2][1] = 8; for (int i = 0; i < matrix2.getDimX(); ++i) { for (int j = 0; j < matrix2.getDimY(); ++j) { printf ("%d ", matrix2[i][j]); } printf ("\n"); } printf ("----------------------------\n"); DMatrix<int>* matrix3 = Matrixs<int>::mul(matrix1, matrix2); for (int i = 0; i < matrix3->getDimX(); ++i) { for (int j = 0; j < matrix3->getDimY(); ++j) { printf ("%d ", matrix3[i][j]); } printf ("\n"); } delete matrix3; return 0; } <|endoftext|>
<commit_before>#include "parser.hpp" #include "ast_data.hpp" namespace klang { Parser::Parser(TokenVector tokens) : tokens_(std::move(tokens)), current_(std::begin(tokens_)) {} bool Parser::parse_symbol(const char* str) { if (current_type() == TokenType::SYMBOL && current_string() == std::string{str}) { advance(1); return true; } else { return false; } } ast::IdentifierPtr Parser::parse_identifier() { if (current_type() == TokenType::IDENTIFIER) { advance(1); return make_unique<ast::IdentifierData>(current_string()); } else { return nullptr; } } ast::TypePtr Parser::parse_type() { if (current_type() == TokenType::SYMBOL) { advance(1); return make_unique<ast::TypeData>(current_string()); } else { return nullptr; } } ast::IntegerLiteralPtr Parser::parse_integer_literal() { if (current_type() == TokenType::NUMBER) { advance(1); return make_unique<ast::IntegerLiteralData>(current_string()); } else { return nullptr; } } ast::CharacterLiteralPtr Parser::parse_character_literal() { if (current_type() == TokenType::CHARACTER) { advance(1); return make_unique<ast::CharacterLiteralData>(current_string()); } else { return nullptr; } } ast::StringLiteralPtr Parser::parse_string_literal() { if (current_type() == TokenType::STRING) { advance(1); return make_unique<ast::StringLiteralData>(current_string()); } else { return nullptr; } } ast::TranslationUnitPtr Parser::parse_translation_unit() { std::vector<ast::FunctionDefinitionPtr> functions; while (auto function = parse_function_definition()) { functions.push_back(std::move(function)); } return make_unique<ast::TranslationUnitData>(std::move(functions)); } ast::FunctionDefinitionPtr Parser::parse_function_definition() { const auto s = snapshot(); if (parse_symbol("def")) { if (auto function_name = parse_identifier()) { if (parse_symbol("(")) { if (auto arguments = parse_argument_list()) { if (parse_symbol(")") && parse_symbol("->") && parse_symbol("(")) { if (auto return_type = parse_type()) { if (parse_symbol(")")) { if (auto function_body = parse_compound_statement()) { return make_unique<ast::FunctionDefinitionData>( std::move(function_name), std::move(arguments), std::move(return_type), std::move(function_body)); } } } } } } } } rewind(s); return nullptr; } ast::ArgumentListPtr Parser::parse_argument_list() { std::vector<ast::ArgumentPtr> arguments; if (auto first_argument = parse_argument()) { arguments.push_back(std::move(first_argument)); while (true) { const auto s = snapshot(); if (parse_symbol(",")) { if (auto argument = parse_argument()) { arguments.push_back(std::move(argument)); continue; } } rewind(s); break; } } return make_unique<ast::ArgumentListData>(std::move(arguments)); } ast::ArgumentPtr Parser::parse_argument() { const auto s = snapshot(); if (auto argument_type = parse_type()) { if (auto argument_name = parse_identifier()) { return make_unique<ast::ArgumentData>(std::move(argument_type), std::move(argument_name)); } } rewind(s); return nullptr; } ast::StatementPtr Parser::parse_statement() { if (auto statement = parse_compound_statement()) { return std::move(statement); } else if (auto statement = parse_if_statement()){ return std::move(statement); } else if (auto statement = parse_while_statement()){ return std::move(statement); } else if (auto statement = parse_for_statement()){ return std::move(statement); } else if (auto statement = parse_return_statement()){ return std::move(statement); } else if (auto statement = parse_break_statement()){ return std::move(statement); } else if (auto statement = parse_continue_statement()){ return std::move(statement); } else if (auto statement = parse_variable_definition_statement()){ return std::move(statement); } else if (auto statement = parse_expression_statement()){ return std::move(statement); } return nullptr; } ast::CompoundStatementPtr Parser::parse_compound_statement() { std::vector<ast::StatementPtr> statements; const auto s = snapshot(); if (parse_symbol("{")) { while (auto statement = parse_statement()) { statements.push_back(std::move(statement)); } if (parse_symbol("}")) { return make_unique<ast::CompoundStatementData>(std::move(statements)); } } rewind(s); return nullptr; } ast::IfStatementPtr Parser::parse_if_statement() { const auto s = snapshot(); if (parse_symbol("if") && parse_symbol("(")) { if (auto condition = parse_expression()) { if (parse_symbol(")")) { if (auto compound_statement = parse_compound_statement()) { return make_unique<ast::IfStatementData>( std::move(condition), std::move(compound_statement), parse_else_statement()); } } } } rewind(s); return nullptr; } ast::IfStatementPtr Parser::parse_else_statement() { const auto s = snapshot(); if (parse_symbol("else")) { if (auto else_if_statement = parse_if_statement()) { return std::move(else_if_statement); } else if (auto compound_statement = parse_compound_statement()) { return make_unique<ast::ElseStatementData>(std::move(compound_statement)); } } rewind(s); return nullptr; } TokenType Parser::current_type() const { return is_eof() ? TokenType::IGNORE : current_->type(); } std::string Parser::current_string() const { static const std::string empty_string{""}; return is_eof() ? empty_string : current_->str(); } bool Parser::is_eof() const { using std::end; return current_ == end(tokens_); } bool Parser::advance(int count) { using std::begin; using std::end; const auto b = begin(tokens_); const auto e = end(tokens_); while (count < 0) { if (current_ != b) { ++count; --current_; } else { return false; } } while (0 < count) { if (current_ != e) { --count; ++current_; } else { return false; } } return true; } auto Parser::snapshot() const -> Pointer { return current_; } void Parser::rewind(Pointer p) { current_ = p; } } // namespace klang <commit_msg>Add parse_while_statement() member<commit_after>#include "parser.hpp" #include "ast_data.hpp" namespace klang { Parser::Parser(TokenVector tokens) : tokens_(std::move(tokens)), current_(std::begin(tokens_)) {} bool Parser::parse_symbol(const char* str) { if (current_type() == TokenType::SYMBOL && current_string() == std::string{str}) { advance(1); return true; } else { return false; } } ast::IdentifierPtr Parser::parse_identifier() { if (current_type() == TokenType::IDENTIFIER) { advance(1); return make_unique<ast::IdentifierData>(current_string()); } else { return nullptr; } } ast::TypePtr Parser::parse_type() { if (current_type() == TokenType::SYMBOL) { advance(1); return make_unique<ast::TypeData>(current_string()); } else { return nullptr; } } ast::IntegerLiteralPtr Parser::parse_integer_literal() { if (current_type() == TokenType::NUMBER) { advance(1); return make_unique<ast::IntegerLiteralData>(current_string()); } else { return nullptr; } } ast::CharacterLiteralPtr Parser::parse_character_literal() { if (current_type() == TokenType::CHARACTER) { advance(1); return make_unique<ast::CharacterLiteralData>(current_string()); } else { return nullptr; } } ast::StringLiteralPtr Parser::parse_string_literal() { if (current_type() == TokenType::STRING) { advance(1); return make_unique<ast::StringLiteralData>(current_string()); } else { return nullptr; } } ast::TranslationUnitPtr Parser::parse_translation_unit() { std::vector<ast::FunctionDefinitionPtr> functions; while (auto function = parse_function_definition()) { functions.push_back(std::move(function)); } return make_unique<ast::TranslationUnitData>(std::move(functions)); } ast::FunctionDefinitionPtr Parser::parse_function_definition() { const auto s = snapshot(); if (parse_symbol("def")) { if (auto function_name = parse_identifier()) { if (parse_symbol("(")) { if (auto arguments = parse_argument_list()) { if (parse_symbol(")") && parse_symbol("->") && parse_symbol("(")) { if (auto return_type = parse_type()) { if (parse_symbol(")")) { if (auto function_body = parse_compound_statement()) { return make_unique<ast::FunctionDefinitionData>( std::move(function_name), std::move(arguments), std::move(return_type), std::move(function_body)); } } } } } } } } rewind(s); return nullptr; } ast::ArgumentListPtr Parser::parse_argument_list() { std::vector<ast::ArgumentPtr> arguments; if (auto first_argument = parse_argument()) { arguments.push_back(std::move(first_argument)); while (true) { const auto s = snapshot(); if (parse_symbol(",")) { if (auto argument = parse_argument()) { arguments.push_back(std::move(argument)); continue; } } rewind(s); break; } } return make_unique<ast::ArgumentListData>(std::move(arguments)); } ast::ArgumentPtr Parser::parse_argument() { const auto s = snapshot(); if (auto argument_type = parse_type()) { if (auto argument_name = parse_identifier()) { return make_unique<ast::ArgumentData>(std::move(argument_type), std::move(argument_name)); } } rewind(s); return nullptr; } ast::StatementPtr Parser::parse_statement() { if (auto statement = parse_compound_statement()) { return std::move(statement); } else if (auto statement = parse_if_statement()){ return std::move(statement); } else if (auto statement = parse_while_statement()){ return std::move(statement); } else if (auto statement = parse_for_statement()){ return std::move(statement); } else if (auto statement = parse_return_statement()){ return std::move(statement); } else if (auto statement = parse_break_statement()){ return std::move(statement); } else if (auto statement = parse_continue_statement()){ return std::move(statement); } else if (auto statement = parse_variable_definition_statement()){ return std::move(statement); } else if (auto statement = parse_expression_statement()){ return std::move(statement); } return nullptr; } ast::CompoundStatementPtr Parser::parse_compound_statement() { std::vector<ast::StatementPtr> statements; const auto s = snapshot(); if (parse_symbol("{")) { while (auto statement = parse_statement()) { statements.push_back(std::move(statement)); } if (parse_symbol("}")) { return make_unique<ast::CompoundStatementData>(std::move(statements)); } } rewind(s); return nullptr; } ast::IfStatementPtr Parser::parse_if_statement() { const auto s = snapshot(); if (parse_symbol("if") && parse_symbol("(")) { if (auto condition = parse_expression()) { if (parse_symbol(")")) { if (auto compound_statement = parse_compound_statement()) { return make_unique<ast::IfStatementData>( std::move(condition), std::move(compound_statement), parse_else_statement()); } } } } rewind(s); return nullptr; } ast::IfStatementPtr Parser::parse_else_statement() { const auto s = snapshot(); if (parse_symbol("else")) { if (auto else_if_statement = parse_if_statement()) { return std::move(else_if_statement); } else if (auto compound_statement = parse_compound_statement()) { return make_unique<ast::ElseStatementData>(std::move(compound_statement)); } } rewind(s); return nullptr; } ast::WhileStatementPtr Parser::parse_while_statement() { const auto s = snapshot(); if (parse_symbol("while") && parse_symbol("(")) { if (auto condition = parse_expression()) { if (parse_symbol(")")) { if (auto compound_statement = parse_compound_statement()) { return make_unique<ast::WhileStatementData>( std::move(condition), std::move(compound_statement)); } } } } rewind(s); return nullptr; } TokenType Parser::current_type() const { return is_eof() ? TokenType::IGNORE : current_->type(); } std::string Parser::current_string() const { static const std::string empty_string{""}; return is_eof() ? empty_string : current_->str(); } bool Parser::is_eof() const { using std::end; return current_ == end(tokens_); } bool Parser::advance(int count) { using std::begin; using std::end; const auto b = begin(tokens_); const auto e = end(tokens_); while (count < 0) { if (current_ != b) { ++count; --current_; } else { return false; } } while (0 < count) { if (current_ != e) { --count; ++current_; } else { return false; } } return true; } auto Parser::snapshot() const -> Pointer { return current_; } void Parser::rewind(Pointer p) { current_ = p; } } // namespace klang <|endoftext|>
<commit_before>#include "pbview.h" #include <cinttypes> #include <cstdio> #include <cstring> #include <curses.h> #include <iostream> #include <sstream> #include "config.h" #include "configcontainer.h" #include "dllist.h" #include "download.h" #include "fmtstrformatter.h" #include "help.h" #include "logger.h" #include "pbcontroller.h" #include "poddlthread.h" #include "strprintf.h" #include "utils.h" using namespace newsboat; namespace podboat { PbView::PbView(PbController* c) : ctrl(c) , dllist_form(dllist_str) , help_form(help_str) , keys(0) { if (getenv("ESCDELAY") == nullptr) { set_escdelay(25); } } PbView::~PbView() { Stfl::reset(); } void PbView::run(bool auto_download) { bool quit = false; set_dllist_keymap_hint(); do { if (ctrl->view_update_necessary()) { const double total_kbps = ctrl->get_total_kbps(); const auto speed = get_speed_human_readable(total_kbps); char parbuf[128] = ""; if (ctrl->get_maxdownloads() > 1) { snprintf(parbuf, sizeof(parbuf), _(" - %u parallel downloads"), ctrl->get_maxdownloads()); } char buf[1024]; snprintf(buf, sizeof(buf), _("Queue (%u downloads in progress, %u total) " "- %.2f %s total%s"), static_cast<unsigned int>( ctrl->downloads_in_progress()), static_cast<unsigned int>( ctrl->downloads().size()), speed.first, speed.second.c_str(), parbuf); dllist_form.set("head", buf); LOG(Level::DEBUG, "PbView::run: updating view... " "downloads().size() " "= %" PRIu64, static_cast<uint64_t>(ctrl->downloads().size())); std::string code = "{list"; std::string formatstring = ctrl->get_formatstr(); dllist_form.run(-3); // compute all widget dimensions unsigned int width = utils::to_u(dllist_form.get("dls:w")); unsigned int i = 0; for (const auto& dl : ctrl->downloads()) { auto lbuf = format_line(formatstring, dl, i, width); code.append( strprintf::fmt("{listitem[%u] text:%s}", i, Stfl::quote(lbuf))); i++; } code.append("}"); dllist_form.modify("dls", "replace_inner", code); ctrl->set_view_update_necessary(false); } const char* event = dllist_form.run(500); if (auto_download) { if (ctrl->get_maxdownloads() > ctrl->downloads_in_progress()) { ctrl->start_downloads(); } } if (!event || strcmp(event, "TIMEOUT") == 0) { continue; } Operation op = keys->get_operation(event, "podbeuter"); if (dllist_form.get("msg").length() > 0) { dllist_form.set("msg", ""); ctrl->set_view_update_necessary(true); } switch (op) { case OP_PB_TOGGLE_DLALL: auto_download = !auto_download; break; case OP_HARDQUIT: case OP_QUIT: if (ctrl->downloads_in_progress() > 0) { dllist_form.set("msg", _("Error: can't quit: download(s) in " "progress.")); ctrl->set_view_update_necessary(true); } else { quit = true; } break; case OP_PB_MOREDL: ctrl->increase_parallel_downloads(); break; case OP_PB_LESSDL: ctrl->decrease_parallel_downloads(); break; case OP_PB_DOWNLOAD: { std::istringstream os(dllist_form.get("dlposname")); int idx = -1; os >> idx; if (idx != -1) { if (ctrl->downloads()[idx].status() != DlStatus::DOWNLOADING) { std::thread t{PodDlThread( &ctrl->downloads()[idx], ctrl->get_cfgcont())}; t.detach(); } } } break; case OP_PB_PLAY: { std::istringstream os(dllist_form.get("dlposname")); int idx = -1; os >> idx; if (idx != -1) { DlStatus status = ctrl->downloads()[idx].status(); if (status == DlStatus::FINISHED || status == DlStatus::PLAYED || status == DlStatus::READY) { ctrl->play_file(ctrl->downloads()[idx] .filename()); ctrl->downloads()[idx].set_status( DlStatus::PLAYED); } else { dllist_form.set("msg", _("Error: download needs to be " "finished before the file " "can be played.")); } } } break; case OP_PB_MARK_FINISHED: { std::istringstream os(dllist_form.get("dlposname")); int idx = -1; os >> idx; if (idx != -1) { DlStatus status = ctrl->downloads()[idx].status(); if (status == DlStatus::PLAYED) { ctrl->downloads()[idx].set_status( DlStatus::FINISHED); } } } break; case OP_PB_CANCEL: { std::istringstream os(dllist_form.get("dlposname")); int idx = -1; os >> idx; if (idx != -1) { if (ctrl->downloads()[idx].status() == DlStatus::DOWNLOADING) { ctrl->downloads()[idx].set_status( DlStatus::CANCELLED); } } } break; case OP_PB_DELETE: { std::istringstream os(dllist_form.get("dlposname")); int idx = -1; os >> idx; if (idx != -1) { if (ctrl->downloads()[idx].status() != DlStatus::DOWNLOADING) { ctrl->downloads()[idx].set_status( DlStatus::DELETED); } } } break; case OP_PB_PURGE: if (ctrl->downloads_in_progress() > 0) { dllist_form.set("msg", _("Error: unable to perform operation: " "download(s) in progress.")); } else { ctrl->purge_queue(); } ctrl->set_view_update_necessary(true); break; case OP_HELP: run_help(); break; default: break; } } while (!quit); } void PbView::set_bindings() { if (keys) { std::string upkey("** "); upkey.append(keys->getkey(OP_SK_UP, "podbeuter")); std::string downkey("** "); downkey.append(keys->getkey(OP_SK_DOWN, "podbeuter")); std::string pgupkey("** "); pgupkey.append(keys->getkey(OP_SK_PGUP, "podbeuter")); std::string pgdownkey("** "); pgdownkey.append(keys->getkey(OP_SK_PGDOWN, "podbeuter")); std::string homekey("** "); homekey.append(keys->getkey(OP_SK_HOME, "podbeuter")); std::string endkey("** "); endkey.append(keys->getkey(OP_SK_END, "podbeuter")); dllist_form.set("bind_up", upkey); dllist_form.set("bind_down", downkey); dllist_form.set("bind_page_up", pgupkey); dllist_form.set("bind_page_down", pgdownkey); dllist_form.set("bind_home", homekey); dllist_form.set("bind_end", endkey); help_form.set("bind_up", upkey); help_form.set("bind_down", downkey); help_form.set("bind_page_up", pgupkey); help_form.set("bind_page_down", pgdownkey); help_form.set("bind_home", homekey); help_form.set("bind_end", endkey); } } std::pair<double, std::string> PbView::get_speed_human_readable(double kbps) { if (kbps < 1024) { return std::make_pair(kbps, _("KB/s")); } else if (kbps < 1024 * 1024) { return std::make_pair(kbps / 1024, _("MB/s")); } else { return std::make_pair(kbps / 1024 / 1024, _("GB/s")); } } void PbView::run_help() { set_help_keymap_hint(); help_form.set("head", _("Help")); std::vector<KeyMapDesc> descs; keys->get_keymap_descriptions(descs, KM_PODBOAT); std::string code = "{list"; for (const auto& desc : descs) { std::string line = "{listitem text:"; std::string descline; descline.append(desc.key); descline.append(8 - desc.key.length(), ' '); descline.append(desc.cmd); descline.append(24 - desc.cmd.length(), ' '); descline.append(desc.desc); line.append(Stfl::quote(descline)); line.append("}"); code.append(line); } code.append("}"); help_form.modify("helptext", "replace_inner", code); bool quit = false; do { const char* event = help_form.run(0); if (!event) { continue; } Operation op = keys->get_operation(event, "help"); switch (op) { case OP_HARDQUIT: case OP_QUIT: quit = true; break; default: break; } } while (!quit); } std::string PbView::prepare_keymaphint(KeyMapHintEntry* hints) { std::string keymap_hint; for (int i = 0; hints[i].op != OP_NIL; ++i) { keymap_hint.append(keys->getkey(hints[i].op, "podbeuter")); keymap_hint.append(":"); keymap_hint.append(hints[i].text); keymap_hint.append(" "); } return keymap_hint; } void PbView::set_help_keymap_hint() { KeyMapHintEntry hints[] = {{OP_QUIT, _("Quit")}, {OP_NIL, nullptr}}; std::string keymap_hint = prepare_keymaphint(hints); help_form.set("help", keymap_hint); } void PbView::set_dllist_keymap_hint() { KeyMapHintEntry hints[] = {{OP_QUIT, _("Quit")}, {OP_PB_DOWNLOAD, _("Download")}, {OP_PB_CANCEL, _("Cancel")}, {OP_PB_DELETE, _("Delete")}, {OP_PB_PURGE, _("Purge Finished")}, {OP_PB_TOGGLE_DLALL, _("Toggle Automatic Download")}, {OP_PB_PLAY, _("Play")}, {OP_PB_MARK_FINISHED, _("Mark as Finished")}, {OP_HELP, _("Help")}, {OP_NIL, nullptr} }; std::string keymap_hint = prepare_keymaphint(hints); dllist_form.set("help", keymap_hint); } std::string PbView::format_line(const std::string& podlist_format, const Download& dl, unsigned int pos, unsigned int width) { FmtStrFormatter fmt; const double speed_kbps = dl.kbps(); const auto speed = get_speed_human_readable(speed_kbps); fmt.register_fmt('i', strprintf::fmt("%u", pos + 1)); fmt.register_fmt('d', strprintf::fmt("%.1f", dl.current_size() / (1024 * 1024))); fmt.register_fmt( 't', strprintf::fmt("%.1f", dl.total_size() / (1024 * 1024))); fmt.register_fmt('p', strprintf::fmt("%.1f", dl.percents_finished())); fmt.register_fmt('k', strprintf::fmt("%.2f", speed_kbps)); fmt.register_fmt('K', strprintf::fmt("%.2f %s", speed.first, speed.second)); fmt.register_fmt('S', strprintf::fmt("%s", dl.status_text())); fmt.register_fmt('u', strprintf::fmt("%s", dl.url())); fmt.register_fmt('F', strprintf::fmt("%s", dl.filename())); fmt.register_fmt('b', strprintf::fmt("%s", dl.basename())); auto formattedLine = fmt.do_format(podlist_format, width); return formattedLine; } } // namespace podboat <commit_msg>Podboat: Hide cursor<commit_after>#include "pbview.h" #include <cinttypes> #include <cstdio> #include <cstring> #include <curses.h> #include <iostream> #include <sstream> #include "config.h" #include "configcontainer.h" #include "dllist.h" #include "download.h" #include "fmtstrformatter.h" #include "help.h" #include "logger.h" #include "pbcontroller.h" #include "poddlthread.h" #include "strprintf.h" #include "utils.h" using namespace newsboat; namespace podboat { PbView::PbView(PbController* c) : ctrl(c) , dllist_form(dllist_str) , help_form(help_str) , keys(0) { if (getenv("ESCDELAY") == nullptr) { set_escdelay(25); } } PbView::~PbView() { Stfl::reset(); } void PbView::run(bool auto_download) { bool quit = false; // Make sure curses is initialized dllist_form.run(-3); // Hide cursor using curses curs_set(0); set_dllist_keymap_hint(); do { if (ctrl->view_update_necessary()) { const double total_kbps = ctrl->get_total_kbps(); const auto speed = get_speed_human_readable(total_kbps); char parbuf[128] = ""; if (ctrl->get_maxdownloads() > 1) { snprintf(parbuf, sizeof(parbuf), _(" - %u parallel downloads"), ctrl->get_maxdownloads()); } char buf[1024]; snprintf(buf, sizeof(buf), _("Queue (%u downloads in progress, %u total) " "- %.2f %s total%s"), static_cast<unsigned int>( ctrl->downloads_in_progress()), static_cast<unsigned int>( ctrl->downloads().size()), speed.first, speed.second.c_str(), parbuf); dllist_form.set("head", buf); LOG(Level::DEBUG, "PbView::run: updating view... " "downloads().size() " "= %" PRIu64, static_cast<uint64_t>(ctrl->downloads().size())); std::string code = "{list"; std::string formatstring = ctrl->get_formatstr(); dllist_form.run(-3); // compute all widget dimensions unsigned int width = utils::to_u(dllist_form.get("dls:w")); unsigned int i = 0; for (const auto& dl : ctrl->downloads()) { auto lbuf = format_line(formatstring, dl, i, width); code.append( strprintf::fmt("{listitem[%u] text:%s}", i, Stfl::quote(lbuf))); i++; } code.append("}"); dllist_form.modify("dls", "replace_inner", code); ctrl->set_view_update_necessary(false); } const char* event = dllist_form.run(500); if (auto_download) { if (ctrl->get_maxdownloads() > ctrl->downloads_in_progress()) { ctrl->start_downloads(); } } if (!event || strcmp(event, "TIMEOUT") == 0) { continue; } Operation op = keys->get_operation(event, "podbeuter"); if (dllist_form.get("msg").length() > 0) { dllist_form.set("msg", ""); ctrl->set_view_update_necessary(true); } switch (op) { case OP_PB_TOGGLE_DLALL: auto_download = !auto_download; break; case OP_HARDQUIT: case OP_QUIT: if (ctrl->downloads_in_progress() > 0) { dllist_form.set("msg", _("Error: can't quit: download(s) in " "progress.")); ctrl->set_view_update_necessary(true); } else { quit = true; } break; case OP_PB_MOREDL: ctrl->increase_parallel_downloads(); break; case OP_PB_LESSDL: ctrl->decrease_parallel_downloads(); break; case OP_PB_DOWNLOAD: { std::istringstream os(dllist_form.get("dlposname")); int idx = -1; os >> idx; if (idx != -1) { if (ctrl->downloads()[idx].status() != DlStatus::DOWNLOADING) { std::thread t{PodDlThread( &ctrl->downloads()[idx], ctrl->get_cfgcont())}; t.detach(); } } } break; case OP_PB_PLAY: { std::istringstream os(dllist_form.get("dlposname")); int idx = -1; os >> idx; if (idx != -1) { DlStatus status = ctrl->downloads()[idx].status(); if (status == DlStatus::FINISHED || status == DlStatus::PLAYED || status == DlStatus::READY) { ctrl->play_file(ctrl->downloads()[idx] .filename()); ctrl->downloads()[idx].set_status( DlStatus::PLAYED); } else { dllist_form.set("msg", _("Error: download needs to be " "finished before the file " "can be played.")); } } } break; case OP_PB_MARK_FINISHED: { std::istringstream os(dllist_form.get("dlposname")); int idx = -1; os >> idx; if (idx != -1) { DlStatus status = ctrl->downloads()[idx].status(); if (status == DlStatus::PLAYED) { ctrl->downloads()[idx].set_status( DlStatus::FINISHED); } } } break; case OP_PB_CANCEL: { std::istringstream os(dllist_form.get("dlposname")); int idx = -1; os >> idx; if (idx != -1) { if (ctrl->downloads()[idx].status() == DlStatus::DOWNLOADING) { ctrl->downloads()[idx].set_status( DlStatus::CANCELLED); } } } break; case OP_PB_DELETE: { std::istringstream os(dllist_form.get("dlposname")); int idx = -1; os >> idx; if (idx != -1) { if (ctrl->downloads()[idx].status() != DlStatus::DOWNLOADING) { ctrl->downloads()[idx].set_status( DlStatus::DELETED); } } } break; case OP_PB_PURGE: if (ctrl->downloads_in_progress() > 0) { dllist_form.set("msg", _("Error: unable to perform operation: " "download(s) in progress.")); } else { ctrl->purge_queue(); } ctrl->set_view_update_necessary(true); break; case OP_HELP: run_help(); break; default: break; } } while (!quit); } void PbView::set_bindings() { if (keys) { std::string upkey("** "); upkey.append(keys->getkey(OP_SK_UP, "podbeuter")); std::string downkey("** "); downkey.append(keys->getkey(OP_SK_DOWN, "podbeuter")); std::string pgupkey("** "); pgupkey.append(keys->getkey(OP_SK_PGUP, "podbeuter")); std::string pgdownkey("** "); pgdownkey.append(keys->getkey(OP_SK_PGDOWN, "podbeuter")); std::string homekey("** "); homekey.append(keys->getkey(OP_SK_HOME, "podbeuter")); std::string endkey("** "); endkey.append(keys->getkey(OP_SK_END, "podbeuter")); dllist_form.set("bind_up", upkey); dllist_form.set("bind_down", downkey); dllist_form.set("bind_page_up", pgupkey); dllist_form.set("bind_page_down", pgdownkey); dllist_form.set("bind_home", homekey); dllist_form.set("bind_end", endkey); help_form.set("bind_up", upkey); help_form.set("bind_down", downkey); help_form.set("bind_page_up", pgupkey); help_form.set("bind_page_down", pgdownkey); help_form.set("bind_home", homekey); help_form.set("bind_end", endkey); } } std::pair<double, std::string> PbView::get_speed_human_readable(double kbps) { if (kbps < 1024) { return std::make_pair(kbps, _("KB/s")); } else if (kbps < 1024 * 1024) { return std::make_pair(kbps / 1024, _("MB/s")); } else { return std::make_pair(kbps / 1024 / 1024, _("GB/s")); } } void PbView::run_help() { set_help_keymap_hint(); help_form.set("head", _("Help")); std::vector<KeyMapDesc> descs; keys->get_keymap_descriptions(descs, KM_PODBOAT); std::string code = "{list"; for (const auto& desc : descs) { std::string line = "{listitem text:"; std::string descline; descline.append(desc.key); descline.append(8 - desc.key.length(), ' '); descline.append(desc.cmd); descline.append(24 - desc.cmd.length(), ' '); descline.append(desc.desc); line.append(Stfl::quote(descline)); line.append("}"); code.append(line); } code.append("}"); help_form.modify("helptext", "replace_inner", code); bool quit = false; do { const char* event = help_form.run(0); if (!event) { continue; } Operation op = keys->get_operation(event, "help"); switch (op) { case OP_HARDQUIT: case OP_QUIT: quit = true; break; default: break; } } while (!quit); } std::string PbView::prepare_keymaphint(KeyMapHintEntry* hints) { std::string keymap_hint; for (int i = 0; hints[i].op != OP_NIL; ++i) { keymap_hint.append(keys->getkey(hints[i].op, "podbeuter")); keymap_hint.append(":"); keymap_hint.append(hints[i].text); keymap_hint.append(" "); } return keymap_hint; } void PbView::set_help_keymap_hint() { KeyMapHintEntry hints[] = {{OP_QUIT, _("Quit")}, {OP_NIL, nullptr}}; std::string keymap_hint = prepare_keymaphint(hints); help_form.set("help", keymap_hint); } void PbView::set_dllist_keymap_hint() { KeyMapHintEntry hints[] = {{OP_QUIT, _("Quit")}, {OP_PB_DOWNLOAD, _("Download")}, {OP_PB_CANCEL, _("Cancel")}, {OP_PB_DELETE, _("Delete")}, {OP_PB_PURGE, _("Purge Finished")}, {OP_PB_TOGGLE_DLALL, _("Toggle Automatic Download")}, {OP_PB_PLAY, _("Play")}, {OP_PB_MARK_FINISHED, _("Mark as Finished")}, {OP_HELP, _("Help")}, {OP_NIL, nullptr} }; std::string keymap_hint = prepare_keymaphint(hints); dllist_form.set("help", keymap_hint); } std::string PbView::format_line(const std::string& podlist_format, const Download& dl, unsigned int pos, unsigned int width) { FmtStrFormatter fmt; const double speed_kbps = dl.kbps(); const auto speed = get_speed_human_readable(speed_kbps); fmt.register_fmt('i', strprintf::fmt("%u", pos + 1)); fmt.register_fmt('d', strprintf::fmt("%.1f", dl.current_size() / (1024 * 1024))); fmt.register_fmt( 't', strprintf::fmt("%.1f", dl.total_size() / (1024 * 1024))); fmt.register_fmt('p', strprintf::fmt("%.1f", dl.percents_finished())); fmt.register_fmt('k', strprintf::fmt("%.2f", speed_kbps)); fmt.register_fmt('K', strprintf::fmt("%.2f %s", speed.first, speed.second)); fmt.register_fmt('S', strprintf::fmt("%s", dl.status_text())); fmt.register_fmt('u', strprintf::fmt("%s", dl.url())); fmt.register_fmt('F', strprintf::fmt("%s", dl.filename())); fmt.register_fmt('b', strprintf::fmt("%s", dl.basename())); auto formattedLine = fmt.do_format(podlist_format, width); return formattedLine; } } // namespace podboat <|endoftext|>
<commit_before>// Copyright (C) 2012, Chris J. Foster and the other authors and contributors // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of the software's owners nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // (This is the BSD 3-clause license) #include "pointarray.h" #include <QtGui/QMessageBox> #include <QtOpenGL/QGLShaderProgram> #include <unordered_map> #include "tinyformat.h" #ifdef _MSC_VER # pragma warning(push) # pragma warning(disable : 4996) # pragma warning(disable : 4267) #elif __GNUC__ # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wstrict-aliasing" # pragma GCC diagnostic ignored "-Wunused-but-set-variable" #endif // Note... laslib generates a small horde of warnings #include <lasreader.hpp> #ifdef _MSC_VER # pragma warning(push) #elif __GNUC__ # pragma GCC diagnostic pop // Hack: kill gcc unused variable warning class MonkeyChops { MonkeyChops() { (void)LAS_TOOLS_FORMAT_NAMES; } }; #endif //------------------------------------------------------------------------------ // Hashing of std::pair, copied from stack overflow template <class T> inline void hash_combine(std::size_t & seed, const T & v) { std::hash<T> hasher; seed ^= hasher(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2); } namespace std { template<typename S, typename T> struct hash<pair<S, T>> { inline size_t operator()(const pair<S, T> & v) const { size_t seed = 0; ::hash_combine(seed, v.first); ::hash_combine(seed, v.second); return seed; } }; } //------------------------------------------------------------------------------ // PointArray implementation PointArray::PointArray() : m_fileName(), m_npoints(0), m_bucketWidth(100), m_offset(0), m_bbox(), m_centroid(0), m_buckets() { } PointArray::~PointArray() { } struct PointArray::Bucket { V3f centroid; size_t beginIndex; size_t endIndex; Bucket(V3f centroid, size_t beginIndex, size_t endIndex) : centroid(centroid), beginIndex(beginIndex), endIndex(endIndex) { } }; template<typename T> void reorderArray(std::unique_ptr<T[]>& data, const size_t* inds, size_t size) { if (!data) return; std::unique_ptr<T[]> tmpData(new T[size]); for (size_t i = 0; i < size; ++i) tmpData[i] = data[inds[i]]; data.swap(tmpData); } bool PointArray::loadPointFile(QString fileName, size_t maxPointCount) { m_fileName = fileName; LASreadOpener lasReadOpener; #ifdef _WIN32 // Hack: liblas doesn't like forward slashes as path separators on windows fileName = fileName.replace('/', '\\'); #endif lasReadOpener.set_file_name(fileName.toAscii().constData()); std::unique_ptr<LASreader> lasReader(lasReadOpener.open()); if(!lasReader) { QMessageBox::critical(0, tr("Error"), tr("Couldn't open file \"%1\"").arg(fileName)); return false; } emit loadStepStarted("Reading file"); // Figure out how much to decimate the point cloud. size_t totPoints = lasReader->header.number_of_point_records; size_t decimate = (totPoints + maxPointCount - 1) / maxPointCount; if(decimate > 1) tfm::printf("Decimating \"%s\" by factor of %d\n", fileName.toStdString(), decimate); m_npoints = (totPoints + decimate - 1) / decimate; m_offset = V3d(lasReader->header.min_x, lasReader->header.min_y, lasReader->header.min_z); m_P.reset(new V3f[m_npoints]); m_intensity.reset(new float[m_npoints]); m_returnIndex.reset(new unsigned char[m_npoints]); m_numberOfReturns.reset(new unsigned char[m_npoints]); m_pointSourceId.reset(new unsigned char[m_npoints]); m_bbox.makeEmpty(); // Iterate over all points & pull in the data. V3f* outP = m_P.get(); float* outIntens = m_intensity.get(); unsigned char* returnIndex = m_returnIndex.get(); unsigned char* numReturns = m_numberOfReturns.get(); unsigned char* pointSourceId = m_pointSourceId.get(); size_t readCount = 0; size_t nextBlock = 1; size_t nextStore = 1; V3d Psum(0); if (!lasReader->read_point()) return false; const LASpoint& point = lasReader->point; if (point.have_rgb) m_color.reset(new C3f[m_npoints]); V3f* outCol = m_color.get(); do { // Read a point from the las file ++readCount; if(readCount % 10000 == 0) emit pointsLoaded(100*readCount/totPoints); V3d P = V3d(point.get_x(), point.get_y(), point.get_z()); m_bbox.extendBy(P); Psum += P; if(readCount < nextStore) continue; // Store the point *outP++ = P - m_offset; // float intens = float(point.scan_angle_rank) / 40; *outIntens++ = point.intensity; *returnIndex++ = point.return_number; *numReturns++ = point.number_of_returns_of_given_pulse; *pointSourceId++ = point.point_source_ID; // Extract point RGB if (outCol) *outCol++ = (1.0f/USHRT_MAX) * C3f(point.rgb[0], point.rgb[1], point.rgb[2]); // Figure out which point will be the next stored point. nextBlock += decimate; nextStore = nextBlock; if(decimate > 1) { // Randomize selected point within block to avoid repeated patterns nextStore += (qrand() % decimate); if(nextBlock <= totPoints && nextStore > totPoints) nextStore = totPoints; } } while(lasReader->read_point()); emit pointsLoaded(100); m_centroid = (1.0/totPoints) * Psum; lasReader->close(); tfm::printf("Displaying %d of %d points from file %s\n", m_npoints, totPoints, fileName.toStdString()); emit loadStepStarted("Bucketing points"); typedef std::unordered_map<std::pair<int,int>, std::vector<size_t> > IndexMap; float invBucketSize = 1/m_bucketWidth; IndexMap buckets; for (size_t i = 0; i < m_npoints; ++i) { int x = (int)floor(m_P[i].x*invBucketSize); int y = (int)floor(m_P[i].y*invBucketSize); buckets[std::make_pair(x,y)].push_back(i); if(i % 100000 == 0) emit pointsLoaded(100*i/m_npoints); } //emit loadStepStarted("Shuffling buckets"); std::unique_ptr<size_t[]> inds(new size_t[m_npoints]); size_t idx = 0; m_buckets.clear(); m_buckets.reserve(buckets.size() + 1); for (IndexMap::iterator b = buckets.begin(); b != buckets.end(); ++b) { size_t startIdx = idx; std::vector<size_t>& bucketInds = b->second; V3f centroid(0); // Random shuffle so that choosing an initial sequence will correspond // to a stochastic simplification of the bucket. TODO: Use a // quasirandom shuffling method for better visual properties. std::random_shuffle(bucketInds.begin(), bucketInds.end()); for (size_t i = 0, iend = bucketInds.size(); i < iend; ++i, ++idx) { inds[idx] = bucketInds[i]; centroid += m_P[inds[idx]]; } centroid *= 1.0f/(idx - startIdx); m_buckets.push_back(Bucket(centroid, startIdx, idx)); } reorderArray(m_P, inds.get(), m_npoints); reorderArray(m_color, inds.get(), m_npoints); reorderArray(m_intensity, inds.get(), m_npoints); reorderArray(m_returnIndex, inds.get(), m_npoints); reorderArray(m_numberOfReturns, inds.get(), m_npoints); reorderArray(m_pointSourceId, inds.get(), m_npoints); return true; } size_t PointArray::closestPoint(V3d pos, V3f N, double normalDirectionScale, double* distance) const { pos -= m_offset; N.normalize(); const V3f* P = m_P.get(); size_t nearestIdx = -1; double nearestDist2 = DBL_MAX; double f = normalDirectionScale*normalDirectionScale; for(size_t i = 0; i < m_npoints; ++i, ++P) { V3f v = pos - *P; float distN = N.dot(v); float distNperp = (v - distN*N).length2(); float d = f*distN*distN + distNperp; //float d = (pos - *P).length2(); if(d < nearestDist2) { nearestDist2 = d; nearestIdx = i; } } if(distance) *distance = sqrt(nearestDist2); return nearestIdx; } void PointArray::draw(QGLShaderProgram& prog, const V3d& cameraPos, double quality) const { prog.enableAttributeArray("position"); prog.enableAttributeArray("intensity"); prog.enableAttributeArray("returnIndex"); prog.enableAttributeArray("numberOfReturns"); prog.enableAttributeArray("pointSourceId"); if (m_color) prog.enableAttributeArray("color"); // Draw points in each bucket, with total number drawn depending on how far // away the bucket is. Since the points are shuffled, this corresponds to // a stochastic simplification of the full point cloud. size_t totDraw = 0; for (size_t bucketIdx = 0; bucketIdx < m_buckets.size(); ++bucketIdx) { const Bucket& bucket = m_buckets[bucketIdx]; size_t b = bucket.beginIndex; prog.setAttributeArray("position", (const GLfloat*)(m_P.get() + b), 3); prog.setAttributeArray("intensity", m_intensity.get() + b, 1); prog.setAttributeArray("returnIndex", GL_UNSIGNED_BYTE, m_returnIndex.get() + b, 1); prog.setAttributeArray("numberOfReturns", GL_UNSIGNED_BYTE, m_numberOfReturns.get() + b, 1); prog.setAttributeArray("pointSourceId", GL_UNSIGNED_BYTE, m_pointSourceId.get() + b, 1); if (m_color) prog.setAttributeArray("color", (const GLfloat*)(m_color.get() + b), 3); // Compute the desired fraction of points for this bucket. // // The desired fraction is chosen to keep linear density constant - // this looks better than keeping the density per area constant. float dist = (bucket.centroid + m_offset - cameraPos).length(); double desiredFraction = quality <= 0 ? 1 : quality * (m_bucketWidth) / (dist); size_t ndraw = bucket.endIndex - bucket.beginIndex; float lodMultiplier = 1; if (desiredFraction < 1) { ndraw = (size_t) (ndraw*desiredFraction); lodMultiplier = (float)(1/desiredFraction); } prog.setUniformValue("pointSizeLodMultiplier", lodMultiplier); glDrawArrays(GL_POINTS, 0, ndraw); totDraw += ndraw; } //tfm::printf("Drew %.2f%% of total points\n", double(totDraw)/m_npoints); } <commit_msg>Bugfix: Set color to something sensible if not present<commit_after>// Copyright (C) 2012, Chris J. Foster and the other authors and contributors // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of the software's owners nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // (This is the BSD 3-clause license) #include "pointarray.h" #include <QtGui/QMessageBox> #include <QtOpenGL/QGLShaderProgram> #include <unordered_map> #include "tinyformat.h" #ifdef _MSC_VER # pragma warning(push) # pragma warning(disable : 4996) # pragma warning(disable : 4267) #elif __GNUC__ # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wstrict-aliasing" # pragma GCC diagnostic ignored "-Wunused-but-set-variable" #endif // Note... laslib generates a small horde of warnings #include <lasreader.hpp> #ifdef _MSC_VER # pragma warning(push) #elif __GNUC__ # pragma GCC diagnostic pop // Hack: kill gcc unused variable warning class MonkeyChops { MonkeyChops() { (void)LAS_TOOLS_FORMAT_NAMES; } }; #endif //------------------------------------------------------------------------------ // Hashing of std::pair, copied from stack overflow template <class T> inline void hash_combine(std::size_t & seed, const T & v) { std::hash<T> hasher; seed ^= hasher(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2); } namespace std { template<typename S, typename T> struct hash<pair<S, T>> { inline size_t operator()(const pair<S, T> & v) const { size_t seed = 0; ::hash_combine(seed, v.first); ::hash_combine(seed, v.second); return seed; } }; } //------------------------------------------------------------------------------ // PointArray implementation PointArray::PointArray() : m_fileName(), m_npoints(0), m_bucketWidth(100), m_offset(0), m_bbox(), m_centroid(0), m_buckets() { } PointArray::~PointArray() { } struct PointArray::Bucket { V3f centroid; size_t beginIndex; size_t endIndex; Bucket(V3f centroid, size_t beginIndex, size_t endIndex) : centroid(centroid), beginIndex(beginIndex), endIndex(endIndex) { } }; template<typename T> void reorderArray(std::unique_ptr<T[]>& data, const size_t* inds, size_t size) { if (!data) return; std::unique_ptr<T[]> tmpData(new T[size]); for (size_t i = 0; i < size; ++i) tmpData[i] = data[inds[i]]; data.swap(tmpData); } bool PointArray::loadPointFile(QString fileName, size_t maxPointCount) { m_fileName = fileName; LASreadOpener lasReadOpener; #ifdef _WIN32 // Hack: liblas doesn't like forward slashes as path separators on windows fileName = fileName.replace('/', '\\'); #endif lasReadOpener.set_file_name(fileName.toAscii().constData()); std::unique_ptr<LASreader> lasReader(lasReadOpener.open()); if(!lasReader) { QMessageBox::critical(0, tr("Error"), tr("Couldn't open file \"%1\"").arg(fileName)); return false; } emit loadStepStarted("Reading file"); // Figure out how much to decimate the point cloud. size_t totPoints = lasReader->header.number_of_point_records; size_t decimate = (totPoints + maxPointCount - 1) / maxPointCount; if(decimate > 1) tfm::printf("Decimating \"%s\" by factor of %d\n", fileName.toStdString(), decimate); m_npoints = (totPoints + decimate - 1) / decimate; m_offset = V3d(lasReader->header.min_x, lasReader->header.min_y, lasReader->header.min_z); m_P.reset(new V3f[m_npoints]); m_intensity.reset(new float[m_npoints]); m_returnIndex.reset(new unsigned char[m_npoints]); m_numberOfReturns.reset(new unsigned char[m_npoints]); m_pointSourceId.reset(new unsigned char[m_npoints]); m_bbox.makeEmpty(); // Iterate over all points & pull in the data. V3f* outP = m_P.get(); float* outIntens = m_intensity.get(); unsigned char* returnIndex = m_returnIndex.get(); unsigned char* numReturns = m_numberOfReturns.get(); unsigned char* pointSourceId = m_pointSourceId.get(); size_t readCount = 0; size_t nextBlock = 1; size_t nextStore = 1; V3d Psum(0); if (!lasReader->read_point()) return false; const LASpoint& point = lasReader->point; if (point.have_rgb) m_color.reset(new C3f[m_npoints]); V3f* outCol = m_color.get(); do { // Read a point from the las file ++readCount; if(readCount % 10000 == 0) emit pointsLoaded(100*readCount/totPoints); V3d P = V3d(point.get_x(), point.get_y(), point.get_z()); m_bbox.extendBy(P); Psum += P; if(readCount < nextStore) continue; // Store the point *outP++ = P - m_offset; // float intens = float(point.scan_angle_rank) / 40; *outIntens++ = point.intensity; *returnIndex++ = point.return_number; *numReturns++ = point.number_of_returns_of_given_pulse; *pointSourceId++ = point.point_source_ID; // Extract point RGB if (outCol) *outCol++ = (1.0f/USHRT_MAX) * C3f(point.rgb[0], point.rgb[1], point.rgb[2]); // Figure out which point will be the next stored point. nextBlock += decimate; nextStore = nextBlock; if(decimate > 1) { // Randomize selected point within block to avoid repeated patterns nextStore += (qrand() % decimate); if(nextBlock <= totPoints && nextStore > totPoints) nextStore = totPoints; } } while(lasReader->read_point()); emit pointsLoaded(100); m_centroid = (1.0/totPoints) * Psum; lasReader->close(); tfm::printf("Displaying %d of %d points from file %s\n", m_npoints, totPoints, fileName.toStdString()); emit loadStepStarted("Bucketing points"); typedef std::unordered_map<std::pair<int,int>, std::vector<size_t> > IndexMap; float invBucketSize = 1/m_bucketWidth; IndexMap buckets; for (size_t i = 0; i < m_npoints; ++i) { int x = (int)floor(m_P[i].x*invBucketSize); int y = (int)floor(m_P[i].y*invBucketSize); buckets[std::make_pair(x,y)].push_back(i); if(i % 100000 == 0) emit pointsLoaded(100*i/m_npoints); } //emit loadStepStarted("Shuffling buckets"); std::unique_ptr<size_t[]> inds(new size_t[m_npoints]); size_t idx = 0; m_buckets.clear(); m_buckets.reserve(buckets.size() + 1); for (IndexMap::iterator b = buckets.begin(); b != buckets.end(); ++b) { size_t startIdx = idx; std::vector<size_t>& bucketInds = b->second; V3f centroid(0); // Random shuffle so that choosing an initial sequence will correspond // to a stochastic simplification of the bucket. TODO: Use a // quasirandom shuffling method for better visual properties. std::random_shuffle(bucketInds.begin(), bucketInds.end()); for (size_t i = 0, iend = bucketInds.size(); i < iend; ++i, ++idx) { inds[idx] = bucketInds[i]; centroid += m_P[inds[idx]]; } centroid *= 1.0f/(idx - startIdx); m_buckets.push_back(Bucket(centroid, startIdx, idx)); } reorderArray(m_P, inds.get(), m_npoints); reorderArray(m_color, inds.get(), m_npoints); reorderArray(m_intensity, inds.get(), m_npoints); reorderArray(m_returnIndex, inds.get(), m_npoints); reorderArray(m_numberOfReturns, inds.get(), m_npoints); reorderArray(m_pointSourceId, inds.get(), m_npoints); return true; } size_t PointArray::closestPoint(V3d pos, V3f N, double normalDirectionScale, double* distance) const { pos -= m_offset; N.normalize(); const V3f* P = m_P.get(); size_t nearestIdx = -1; double nearestDist2 = DBL_MAX; double f = normalDirectionScale*normalDirectionScale; for(size_t i = 0; i < m_npoints; ++i, ++P) { V3f v = pos - *P; float distN = N.dot(v); float distNperp = (v - distN*N).length2(); float d = f*distN*distN + distNperp; //float d = (pos - *P).length2(); if(d < nearestDist2) { nearestDist2 = d; nearestIdx = i; } } if(distance) *distance = sqrt(nearestDist2); return nearestIdx; } void PointArray::draw(QGLShaderProgram& prog, const V3d& cameraPos, double quality) const { prog.enableAttributeArray("position"); prog.enableAttributeArray("intensity"); prog.enableAttributeArray("returnIndex"); prog.enableAttributeArray("numberOfReturns"); prog.enableAttributeArray("pointSourceId"); if (m_color) prog.enableAttributeArray("color"); else { prog.disableAttributeArray("color"); prog.setAttributeValue("color", 0.0f, 0.0f, 0.0f); } // Draw points in each bucket, with total number drawn depending on how far // away the bucket is. Since the points are shuffled, this corresponds to // a stochastic simplification of the full point cloud. size_t totDraw = 0; for (size_t bucketIdx = 0; bucketIdx < m_buckets.size(); ++bucketIdx) { const Bucket& bucket = m_buckets[bucketIdx]; size_t b = bucket.beginIndex; prog.setAttributeArray("position", (const GLfloat*)(m_P.get() + b), 3); prog.setAttributeArray("intensity", m_intensity.get() + b, 1); prog.setAttributeArray("returnIndex", GL_UNSIGNED_BYTE, m_returnIndex.get() + b, 1); prog.setAttributeArray("numberOfReturns", GL_UNSIGNED_BYTE, m_numberOfReturns.get() + b, 1); prog.setAttributeArray("pointSourceId", GL_UNSIGNED_BYTE, m_pointSourceId.get() + b, 1); if (m_color) prog.setAttributeArray("color", (const GLfloat*)(m_color.get() + b), 3); // Compute the desired fraction of points for this bucket. // // The desired fraction is chosen to keep linear density constant - // this looks better than keeping the density per area constant. float dist = (bucket.centroid + m_offset - cameraPos).length(); double desiredFraction = quality <= 0 ? 1 : quality * (m_bucketWidth) / (dist); size_t ndraw = bucket.endIndex - bucket.beginIndex; float lodMultiplier = 1; if (desiredFraction < 1) { ndraw = (size_t) (ndraw*desiredFraction); lodMultiplier = (float)(1/desiredFraction); } prog.setUniformValue("pointSizeLodMultiplier", lodMultiplier); glDrawArrays(GL_POINTS, 0, ndraw); totDraw += ndraw; } //tfm::printf("Drew %.2f%% of total points\n", double(totDraw)/m_npoints); } <|endoftext|>
<commit_before>#ifndef SIGNALPID_HPP_INCLUDED #define SIGNALPID_HPP_INCLUDED #include <iostream> #include "ComponentEssentials.h" #include "ComponentUtilities.h" #include "math.h" //! //! @file \ C:\HopsanTrunk\HOPSAN++\componentLibraries\defaultLibrary\Signal\Control\Sign\ alPID.hpp //! @author Petter Krus <petter.krus@liu.se> //! @date Wed 23 Oct 2013 10:31:05 //! @brief Differential PID controller //! @ingroup SignalComponents //! //==This code has been autogenerated using Compgen== //from /*{, C:, HopsanTrunk, HOPSAN++, CompgenModels}/SignalControlComponents.nb*/ using namespace hopsan; class SignalPID : public ComponentSignal { private: double umin; double umax; double delayParts1[9]; double delayParts2[9]; double delayParts3[9]; double delayParts4[9]; Matrix jacobianMatrix; Vec systemEquations; Matrix delayedPart; int i; int iter; int mNoiter; double jsyseqnweight[4]; int order[3]; int mNstep; //==This code has been autogenerated using Compgen== //inputVariables double yref; double y; double dy; double Kp; double KI; double Kd; //outputVariables double u; double Ierr; double uI; //Delay declarations //==This code has been autogenerated using Compgen== //inputVariables pointers double *mpyref; double *mpy; double *mpdy; double *mpKp; double *mpKI; double *mpKd; //outputVariables pointers double *mpu; double *mpIerr; double *mpuI; Delay mDelayedPart10; Delay mDelayedPart20; Delay mDelayedPart30; Delay mDelayedPart31; EquationSystemSolver *mpSolver; public: static Component *Creator() { return new SignalPID(); } void configure() { //==This code has been autogenerated using Compgen== mNstep=9; jacobianMatrix.create(3,3); systemEquations.create(3); delayedPart.create(4,6); mNoiter=2; jsyseqnweight[0]=1; jsyseqnweight[1]=0.67; jsyseqnweight[2]=0.5; jsyseqnweight[3]=0.5; //Add ports to the component //Add inputVariables to the component addInputVariable("yref","Reference value","",0.,&mpyref); addInputVariable("y","Actual value","",0.,&mpy); addInputVariable("dy","Differential of actual \ value","",0.,&mpdy); addInputVariable("Kp","Proportional gain","",1.,&mpKp); addInputVariable("KI","Integral gain","",1.,&mpKI); addInputVariable("Kd","Differential gain","",1.,&mpKd); //Add outputVariables to the component addOutputVariable("u","control signal","",0.,&mpu); addOutputVariable("Ierr","limited error","",0.,&mpIerr); addOutputVariable("uI","control signal from integral \ part","",0.,&mpuI); //==This code has been autogenerated using Compgen== //Add constants/parameters addConstant("umin", "Minium output signal", "", -1.,umin); addConstant("umax", "Maximum output signal", "", 1.,umax); mpSolver = new EquationSystemSolver(this,3); } void initialize() { //Read port variable pointers from nodes //Read variables from nodes //Read inputVariables from nodes yref = (*mpyref); y = (*mpy); dy = (*mpdy); Kp = (*mpKp); KI = (*mpKI); Kd = (*mpKd); //Read outputVariables from nodes u = (*mpu); Ierr = (*mpIerr); uI = (*mpuI); //==This code has been autogenerated using Compgen== //Initialize delays delayParts3[1] = (-(Ierr*KI*mTimestep) - 2*uI)/2.; mDelayedPart31.initialize(mNstep,delayParts3[1]); delayedPart[1][1] = delayParts1[1]; delayedPart[2][1] = delayParts2[1]; delayedPart[3][1] = delayParts3[1]; } void simulateOneTimestep() { Vec stateVar(3); Vec stateVark(3); Vec deltaStateVar(3); //Read variables from nodes //Read inputVariables from nodes yref = (*mpyref); y = (*mpy); dy = (*mpdy); Kp = (*mpKp); KI = (*mpKI); Kd = (*mpKd); //LocalExpressions //Initializing variable vector for Newton-Raphson stateVark[0] = u; stateVark[1] = Ierr; stateVark[2] = uI; //Iterative solution using Newton-Rapshson for(iter=1;iter<=mNoiter;iter++) { //PID //Differential-algebraic system of equation parts //Assemble differential-algebraic equations systemEquations[0] =u - limit(-(dy*Kd) + uI + Kp*(-y + \ yref),umin,umax); systemEquations[1] =Ierr - (-y + yref)*dxLimit(limit(-(dy*Kd) + uI \ + Kp*(-y + yref),umin,umax),umin,umax); systemEquations[2] =-(Ierr*KI*mTimestep)/2. + uI + \ delayedPart[3][1]; //Jacobian matrix jacobianMatrix[0][0] = 1; jacobianMatrix[0][1] = 0; jacobianMatrix[0][2] = -dxLimit(-(dy*Kd) + uI + Kp*(-y + \ yref),umin,umax); jacobianMatrix[1][0] = 0; jacobianMatrix[1][1] = 1; jacobianMatrix[1][2] = 0; jacobianMatrix[2][0] = 0; jacobianMatrix[2][1] = -(KI*mTimestep)/2.; jacobianMatrix[2][2] = 1; //==This code has been autogenerated using Compgen== //Solving equation using LU-faktorisation mpSolver->solve(jacobianMatrix, systemEquations, stateVark, iter); u=stateVark[0]; Ierr=stateVark[1]; uI=stateVark[2]; } //Calculate the delayed parts delayParts3[1] = (-(Ierr*KI*mTimestep) - 2*uI)/2.; delayedPart[1][1] = delayParts1[1]; delayedPart[2][1] = delayParts2[1]; delayedPart[3][1] = delayParts3[1]; //Write new values to nodes //outputVariables (*mpu)=u; (*mpIerr)=Ierr; (*mpuI)=uI; //Update the delayed variabels mDelayedPart31.update(delayParts3[1]); } void deconfigure() { delete mpSolver; } }; #endif // SIGNALPID_HPP_INCLUDED <commit_msg>limits to variables<commit_after>#ifndef SIGNALPID_HPP_INCLUDED #define SIGNALPID_HPP_INCLUDED #include <iostream> #include "ComponentEssentials.h" #include "ComponentUtilities.h" #include "math.h" //! //! @file \ C:\HopsanTrunk\HOPSAN++\componentLibraries\defaultLibrary\Signal\Control\Sign\ alPID.hpp //! @author Petter Krus <petter.krus@liu.se> //! @date Wed 23 Oct 2013 11:03:10 //! @brief PID controller //! @ingroup SignalComponents //! //==This code has been autogenerated using Compgen== //from /*{, C:, HopsanTrunk, HOPSAN++, CompgenModels}/SignalControlComponents.nb*/ using namespace hopsan; class SignalPID : public ComponentSignal { private: double delayParts1[9]; double delayParts2[9]; double delayParts3[9]; double delayParts4[9]; Matrix jacobianMatrix; Vec systemEquations; Matrix delayedPart; int i; int iter; int mNoiter; double jsyseqnweight[4]; int order[3]; int mNstep; //==This code has been autogenerated using Compgen== //inputVariables double yref; double y; double dy; double Kp; double KI; double Kd; double umin; double umax; //outputVariables double u; double Ierr; double uI; //Delay declarations //==This code has been autogenerated using Compgen== //inputVariables pointers double *mpyref; double *mpy; double *mpdy; double *mpKp; double *mpKI; double *mpKd; double *mpumin; double *mpumax; //outputVariables pointers double *mpu; double *mpIerr; double *mpuI; Delay mDelayedPart10; Delay mDelayedPart20; Delay mDelayedPart30; Delay mDelayedPart31; EquationSystemSolver *mpSolver; public: static Component *Creator() { return new SignalPID(); } void configure() { //==This code has been autogenerated using Compgen== mNstep=9; jacobianMatrix.create(3,3); systemEquations.create(3); delayedPart.create(4,6); mNoiter=2; jsyseqnweight[0]=1; jsyseqnweight[1]=0.67; jsyseqnweight[2]=0.5; jsyseqnweight[3]=0.5; //Add ports to the component //Add inputVariables to the component addInputVariable("yref","Reference value","",0.,&mpyref); addInputVariable("y","Actual value","",0.,&mpy); addInputVariable("dy","Differential of actual \ value","",0.,&mpdy); addInputVariable("Kp","Proportional gain","",1.,&mpKp); addInputVariable("KI","Integral gain","",1.,&mpKI); addInputVariable("Kd","Differential gain","",1.,&mpKd); addInputVariable("umin","Minium output signal","",-1.,&mpumin); addInputVariable("umax","Maximum output signal","",1.,&mpumax); //Add outputVariables to the component addOutputVariable("u","control signal","",0.,&mpu); addOutputVariable("Ierr","limited error","",0.,&mpIerr); addOutputVariable("uI","control signal from integral \ part","",0.,&mpuI); //==This code has been autogenerated using Compgen== //Add constants/parameters mpSolver = new EquationSystemSolver(this,3); } void initialize() { //Read port variable pointers from nodes //Read variables from nodes //Read inputVariables from nodes yref = (*mpyref); y = (*mpy); dy = (*mpdy); Kp = (*mpKp); KI = (*mpKI); Kd = (*mpKd); umin = (*mpumin); umax = (*mpumax); //Read outputVariables from nodes u = (*mpu); Ierr = (*mpIerr); uI = (*mpuI); //==This code has been autogenerated using Compgen== //Initialize delays delayParts3[1] = (-(Ierr*KI*mTimestep) - 2*uI)/2.; mDelayedPart31.initialize(mNstep,delayParts3[1]); delayedPart[1][1] = delayParts1[1]; delayedPart[2][1] = delayParts2[1]; delayedPart[3][1] = delayParts3[1]; } void simulateOneTimestep() { Vec stateVar(3); Vec stateVark(3); Vec deltaStateVar(3); //Read variables from nodes //Read inputVariables from nodes yref = (*mpyref); y = (*mpy); dy = (*mpdy); Kp = (*mpKp); KI = (*mpKI); Kd = (*mpKd); umin = (*mpumin); umax = (*mpumax); //LocalExpressions //Initializing variable vector for Newton-Raphson stateVark[0] = u; stateVark[1] = Ierr; stateVark[2] = uI; //Iterative solution using Newton-Rapshson for(iter=1;iter<=mNoiter;iter++) { //PID //Differential-algebraic system of equation parts //Assemble differential-algebraic equations systemEquations[0] =u - limit(-(dy*Kd) + uI + Kp*(-y + \ yref),umin,umax); systemEquations[1] =Ierr - (-y + yref)*dxLimit(limit(-(dy*Kd) + uI \ + Kp*(-y + yref),umin,umax),umin,umax); systemEquations[2] =-(Ierr*KI*mTimestep)/2. + uI + \ delayedPart[3][1]; //Jacobian matrix jacobianMatrix[0][0] = 1; jacobianMatrix[0][1] = 0; jacobianMatrix[0][2] = -dxLimit(-(dy*Kd) + uI + Kp*(-y + \ yref),umin,umax); jacobianMatrix[1][0] = 0; jacobianMatrix[1][1] = 1; jacobianMatrix[1][2] = 0; jacobianMatrix[2][0] = 0; jacobianMatrix[2][1] = -(KI*mTimestep)/2.; jacobianMatrix[2][2] = 1; //==This code has been autogenerated using Compgen== //Solving equation using LU-faktorisation mpSolver->solve(jacobianMatrix, systemEquations, stateVark, iter); u=stateVark[0]; Ierr=stateVark[1]; uI=stateVark[2]; } //Calculate the delayed parts delayParts3[1] = (-(Ierr*KI*mTimestep) - 2*uI)/2.; delayedPart[1][1] = delayParts1[1]; delayedPart[2][1] = delayParts2[1]; delayedPart[3][1] = delayParts3[1]; //Write new values to nodes //outputVariables (*mpu)=u; (*mpIerr)=Ierr; (*mpuI)=uI; //Update the delayed variabels mDelayedPart31.update(delayParts3[1]); } void deconfigure() { delete mpSolver; } }; #endif // SIGNALPID_HPP_INCLUDED <|endoftext|>
<commit_before>#include <cassert> #include <ostream> #include "cons.hh" #include "cons_util.hh" #include "eval.hh" #include "lisp_ptr.hh" #include "printer.hh" #include "procedure.hh" #include "rational.hh" #include "symbol.hh" #include "s_closure.hh" #include "token.hh" #include "vm.hh" #include "zs_error.hh" using namespace std; namespace { void print_binary(ostream& f, int i){ std::string tmp; while(i > 0){ auto b = i % 2; tmp.push_back(b ? '1' : '0'); i /= 2; } std::copy(tmp.rbegin(), tmp.rend(), ostreambuf_iterator<char>(f)); } void print_integer(ostream& f, int i, int radix){ if(radix == 10){ f << i; }else{ auto is_minus = (i < 0); auto u = std::abs(i); switch(radix){ case 8: f << "#o"; if(is_minus) f << '-'; f << oct << u << dec; break; case 16: f << "#x"; if(is_minus) f << '-'; f << hex << u << dec; break; case 2: f << "#b"; if(is_minus) f << '-'; print_binary(f, u); break; default: UNEXP_DEFAULT(); } } } void print_vector(ostream& f, const Vector* v, PrintReadable flag){ auto i = v->begin(); const auto e = v->end(); f.write("#(", 2); while(i != e){ print(f, *i, flag); ++i; if(i != e) f.put(' '); } f.put(')'); } void print_list(ostream& f, Lisp_ptr l, PrintReadable flag){ assert(l.tag() == Ptr_tag::cons); f.put('('); auto i = begin(l); for(; i; ++i){ print(f, *i, flag); if(next(i)) f.put(' '); } if(!nullp(i.base())){ f.write(" . ", 3); print(f, i.base(), flag); } f.put(')'); } void print_char(ostream& f, char c, PrintReadable flag){ if(flag == PrintReadable::t){ f.put(c); }else{ switch(c){ case ' ': f << "#\\space"; break; case '\n': f << "#\\newline"; break; default: f.write("#\\", 2); f.put(c); } } } void print_string(ostream& f, const char* str, PrintReadable flag){ if(flag == PrintReadable::t){ f << str; }else{ f.put('\"'); for(auto s = str; *s; ++s){ switch(*s){ case '"': f.write("\\\"", 2); break; case '\\': f.write("\\\\", 2); break; default: f.put(*s); } } f.put('\"'); } } } // namespace void print(ostream& f, Lisp_ptr p, PrintReadable flag, int radix){ switch(p.tag()){ case Ptr_tag::undefined: f << "#<undefined>"; break; case Ptr_tag::boolean: f << ((p.get<bool>()) ? "#t" : "#f"); break; case Ptr_tag::character: print_char(f, p.get<char>(), flag); break; case Ptr_tag::cons: print_list(f, p, flag); break; case Ptr_tag::symbol: { auto sym = p.get<Symbol*>(); if(vm.symtable->find(sym->name()) != vm.symtable->end()){ f << sym->name(); }else{ f << "#<uninterned '" << sym->name() << "' " << reinterpret_cast<void*>(sym) << ">"; } break; } case Ptr_tag::integer: print_integer(f, p.get<int>(), radix); break; case Ptr_tag::rational: { auto r = p.get<Rational*>(); f << r->numerator() << '/' << r->denominator(); break; } case Ptr_tag::real: f << *p.get<double*>(); break; case Ptr_tag::complex: { auto z = p.get<Complex*>(); f << z->real() << showpos << z->imag() << noshowpos; } break; case Ptr_tag::string: print_string(f, p.get<String*>()->c_str(), flag); break; case Ptr_tag::vector: print_vector(f, p.get<Vector*>(), flag); break; case Ptr_tag::syntactic_closure: { auto sc = p.get<SyntacticClosure*>(); if(flag == PrintReadable::t){ f << "#<sc ["; } print(f, sc->expr(), flag); if(flag == PrintReadable::t){ f << "]>"; } break; } case Ptr_tag::vm_argcount: f << "#<argcount " << p.get<int>() << ">"; break; case Ptr_tag::vm_op: f << "#<VMop " << stringify(p.get<VMop>()) << ">"; break; case Ptr_tag::n_procedure: case Ptr_tag::i_procedure: case Ptr_tag::continuation: case Ptr_tag::syntax_rules: f << "#<procedure [" << get_procname(p) << "]>"; break; case Ptr_tag::input_port: case Ptr_tag::output_port: case Ptr_tag::env: f << "#<" << stringify(p.tag()) << " " << p.get<void*>() << ">"; break; case Ptr_tag::notation: f << "#<" << stringify(p.tag()) << " " << stringify(p.get<Notation>()) << ">"; default: f << "#<UNKNOWN TYPE " << static_cast<int>(p.tag()) << " " << p.get<void*>() << ">"; break; } } std::ostream& operator<<(std::ostream& o, Lisp_ptr p){ print(o, p, PrintReadable::t); return o; } <commit_msg>refactoring printer<commit_after>#include <cassert> #include <ostream> #include "cons.hh" #include "cons_util.hh" #include "eval.hh" #include "lisp_ptr.hh" #include "printer.hh" #include "procedure.hh" #include "rational.hh" #include "symbol.hh" #include "s_closure.hh" #include "token.hh" #include "vm.hh" #include "zs_error.hh" using namespace std; namespace { void print_binary(ostream& f, int i){ std::string tmp; while(i > 0){ auto b = i % 2; tmp.push_back(b ? '1' : '0'); i /= 2; } std::copy(tmp.rbegin(), tmp.rend(), ostreambuf_iterator<char>(f)); } void print_integer(ostream& f, int i, int radix){ if(radix == 10){ f << i; }else{ auto is_minus = (i < 0); auto u = std::abs(i); switch(radix){ case 8: f << "#o"; if(is_minus) f << '-'; f << oct << u << dec; break; case 16: f << "#x"; if(is_minus) f << '-'; f << hex << u << dec; break; case 2: f << "#b"; if(is_minus) f << '-'; print_binary(f, u); break; default: UNEXP_DEFAULT(); } } } void print_vector(ostream& f, const Vector* v, PrintReadable flag){ auto i = v->begin(); const auto e = v->end(); f.write("#(", 2); while(i != e){ print(f, *i, flag); ++i; if(i != e) f.put(' '); } f.put(')'); } void print_list(ostream& f, Lisp_ptr l, PrintReadable flag){ assert(l.tag() == Ptr_tag::cons); f.put('('); auto i = begin(l); for(; i; ++i){ print(f, *i, flag); if(next(i)) f.put(' '); } if(!nullp(i.base())){ f.write(" . ", 3); print(f, i.base(), flag); } f.put(')'); } void print_char(ostream& f, char c, PrintReadable flag){ if(flag == PrintReadable::t){ f.put(c); }else{ switch(c){ case ' ': f << "#\\space"; break; case '\n': f << "#\\newline"; break; default: f.write("#\\", 2); f.put(c); } } } void print_string(ostream& f, const char* str, PrintReadable flag){ if(flag == PrintReadable::t){ f << str; }else{ f.put('\"'); for(auto s = str; *s; ++s){ switch(*s){ case '"': f.write("\\\"", 2); break; case '\\': f.write("\\\\", 2); break; default: f.put(*s); } } f.put('\"'); } } } // namespace void print(ostream& f, Lisp_ptr p, PrintReadable flag, int radix){ switch(p.tag()){ case Ptr_tag::undefined: f << "#<undefined>"; break; case Ptr_tag::boolean: f << ((p.get<bool>()) ? "#t" : "#f"); break; case Ptr_tag::character: print_char(f, p.get<char>(), flag); break; case Ptr_tag::cons: print_list(f, p, flag); break; case Ptr_tag::symbol: { auto sym = p.get<Symbol*>(); auto interned = vm.symtable->find(sym->name()) != vm.symtable->end(); if(!interned){ f << "#<uninterned '"; } f << sym->name(); if(!interned){ f << "' " << reinterpret_cast<void*>(sym) << ">"; } break; } case Ptr_tag::integer: print_integer(f, p.get<int>(), radix); break; case Ptr_tag::rational: { auto r = p.get<Rational*>(); f << r->numerator() << '/' << r->denominator(); break; } case Ptr_tag::real: f << *p.get<double*>(); break; case Ptr_tag::complex: { auto z = p.get<Complex*>(); f << z->real() << showpos << z->imag() << noshowpos; } break; case Ptr_tag::string: print_string(f, p.get<String*>()->c_str(), flag); break; case Ptr_tag::vector: print_vector(f, p.get<Vector*>(), flag); break; case Ptr_tag::syntactic_closure: { auto sc = p.get<SyntacticClosure*>(); if(flag == PrintReadable::t){ f << "#<sc ["; } print(f, sc->expr(), flag); if(flag == PrintReadable::t){ f << "]>"; } break; } case Ptr_tag::vm_argcount: f << "#<argcount " << p.get<int>() << ">"; break; case Ptr_tag::vm_op: f << "#<VMop " << stringify(p.get<VMop>()) << ">"; break; case Ptr_tag::n_procedure: case Ptr_tag::i_procedure: case Ptr_tag::continuation: case Ptr_tag::syntax_rules: f << "#<procedure [" << get_procname(p) << "]>"; break; case Ptr_tag::input_port: case Ptr_tag::output_port: case Ptr_tag::env: f << "#<" << stringify(p.tag()) << " " << p.get<void*>() << ">"; break; case Ptr_tag::notation: f << "#<" << stringify(p.tag()) << " " << stringify(p.get<Notation>()) << ">"; default: f << "#<UNKNOWN TYPE " << static_cast<int>(p.tag()) << " " << p.get<void*>() << ">"; break; } } std::ostream& operator<<(std::ostream& o, Lisp_ptr p){ print(o, p, PrintReadable::t); return o; } <|endoftext|>
<commit_before>// Copyright 2015 MongoDB Inc. // // 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. #pragma once #include <mongocxx/options/ssl.hpp> #include <mongocxx/private/libmongoc.hpp> #include <mongocxx/config/private/prelude.hpp> namespace mongocxx { MONGOCXX_INLINE_NAMESPACE_BEGIN namespace options { #if defined(MONGOC_HAVE_SSL) inline ::mongoc_ssl_opt_t make_ssl_opts(const ssl& ssl_opts) { ::mongoc_ssl_opt_t out; if (ssl_opts.pem_file()) { out.pem_file = ssl_opts.pem_file()->c_str(); } if (ssl_opts.pem_password()) { out.pem_pwd = ssl_opts.pem_password()->c_str(); } if (ssl_opts.ca_file()) { out.ca_file = ssl_opts.ca_file()->c_str(); } if (ssl_opts.ca_dir()) { out.ca_dir = ssl_opts.ca_dir()->c_str(); } if (ssl_opts.crl_file()) { out.crl_file = ssl_opts.crl_file()->c_str(); } if (ssl_opts.allow_invalid_certificates()) { out.weak_cert_validation = *(ssl_opts.allow_invalid_certificates()); } return out; } #endif } // namespace options MONGOCXX_INLINE_NAMESPACE_END } // namespace mongocxx #include <mongocxx/config/private/postlude.hpp> <commit_msg>CXX-863 Fix c_str() -> terminated().data() in make_ssl_opts<commit_after>// Copyright 2015 MongoDB Inc. // // 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. #pragma once #include <mongocxx/options/ssl.hpp> #include <mongocxx/private/libmongoc.hpp> #include <mongocxx/config/private/prelude.hpp> namespace mongocxx { MONGOCXX_INLINE_NAMESPACE_BEGIN namespace options { #if defined(MONGOC_HAVE_SSL) inline ::mongoc_ssl_opt_t make_ssl_opts(const ssl& ssl_opts) { ::mongoc_ssl_opt_t out{}; if (ssl_opts.pem_file()) { out.pem_file = ssl_opts.pem_file()->terminated().data(); } if (ssl_opts.pem_password()) { out.pem_pwd = ssl_opts.pem_password()->terminated().data(); } if (ssl_opts.ca_file()) { out.ca_file = ssl_opts.ca_file()->terminated().data(); } if (ssl_opts.ca_dir()) { out.ca_dir = ssl_opts.ca_dir()->terminated().data(); } if (ssl_opts.crl_file()) { out.crl_file = ssl_opts.crl_file()->terminated().data(); } if (ssl_opts.allow_invalid_certificates()) { out.weak_cert_validation = *(ssl_opts.allow_invalid_certificates()); } return out; } #endif } // namespace options MONGOCXX_INLINE_NAMESPACE_END } // namespace mongocxx #include <mongocxx/config/private/postlude.hpp> <|endoftext|>
<commit_before>#include "../Morda.hpp" #include "../util/util.hpp" #include "widget.hpp" #include "container.hpp" using namespace morda; widget::widget(const puu::forest& desc){ for(const auto& p : desc){ if(!is_property(p)){ continue; } if(p.value == "layout"){ this->layout_desc = p.children; }else if(p.value == "x"){ this->rectangle.p.x = parse_dimension_value(get_property_value(p)); }else if(p.value == "y"){ this->rectangle.p.y = parse_dimension_value(get_property_value(p)); }else if(p.value == "dx"){ this->rectangle.d.x = parse_dimension_value(get_property_value(p)); }else if(p.value == "dy"){ this->rectangle.d.y = parse_dimension_value(get_property_value(p)); }else if(p.value == "id"){ this->id = get_property_value(p).to_string(); }else if(p.value == "name"){ //TODO: remove deprecated stuff. this->id = get_property_value(p).to_string(); TRACE_ALWAYS(<< "DEPRECATED!!! the 'name' attribute is deprecated (used by '" << this->id << "'), use 'id' instead" << std::endl) }else if(p.value == "clip"){ this->clip_v = get_property_value(p).to_bool(); }else if(p.value == "cache"){ this->cache = get_property_value(p).to_bool(); }else if(p.value == "visible"){ this->isVisible_v = get_property_value(p).to_bool(); }else if(p.value == "enabled"){ this->isEnabled_v = get_property_value(p).to_bool(); } } } widget::widget(const stob::Node* chain) : widget(stob_to_puu(chain)) {} widget::layout_params::layout_params(const puu::forest& desc){ for(const auto& p : desc){ if(!is_property(p)){ continue; } if(p.value == "dx"){ this->dims.x = parse_layout_dimension_value(get_property_value(p)); }else if(p.value == "dy"){ this->dims.y = parse_layout_dimension_value(get_property_value(p)); } } } std::shared_ptr<Widget> widget::try_get_widget(const std::string& id)noexcept{ if(this->id == id){ return this->sharedFromThis(this); } return nullptr; } void widget::resize(const morda::Vec2r& newDims){ if(this->rectangle.d == newDims){ if(this->relayoutNeeded){ this->clearCache(); this->relayoutNeeded = false; this->lay_out(); } return; } this->clearCache(); this->rectangle.d = newDims; utki::clampBottom(this->rectangle.d.x, real(0.0f)); utki::clampBottom(this->rectangle.d.y, real(0.0f)); this->relayoutNeeded = false; this->on_resize(); // call virtual method } std::shared_ptr<Widget> widget::remove_from_parent(){ if(!this->parent_v){ throw morda::exception("widget::RemoveFromParent(): widget is not added to the parent"); } auto ret = this->sharedFromThis(this); this->parent_v->erase(this->parent_v->find(this)); return ret; } std::shared_ptr<Widget> widget::replace_by(std::shared_ptr<Widget> w) { if(!this->parent()){ throw morda::Exc("this widget is not added to any parent"); } this->parent()->insert(w, this->parent()->find(this)); if(w && w->layout_desc.empty()){ w->layout_desc = std::move(this->layout_desc); } return this->remove_from_parent(); } void widget::invalidate_layout()noexcept{ if(this->relayoutNeeded){ return; } this->relayoutNeeded = true; if(this->parent_v){ this->parent_v->invalidate_layout(); } this->cacheTex.reset(); } void widget::renderInternal(const morda::Matr4r& matrix)const{ if(!this->rect().d.isPositive()){ return; } if(this->cache){ if(this->cacheDirty){ bool scissorTestWasEnabled = morda::inst().renderer().isScissorEnabled(); morda::inst().renderer().setScissorEnabled(false); //check if can re-use old texture if(!this->cacheTex || this->cacheTex->dims() != this->rect().d){ this->cacheTex = this->render_to_texture(); }else{ ASSERT(this->cacheTex->dim() == this->rect().d) this->cacheTex = this->render_to_texture(std::move(this->cacheTex)); } morda::inst().renderer().setScissorEnabled(scissorTestWasEnabled); this->cacheDirty = false; } //After rendering to texture it is most likely there will be transparent areas, so enable simple blending applySimpleAlphaBlending(); this->renderFromCache(matrix); }else{ if(this->clip_v){ // TRACE(<< "widget::RenderInternal(): oldScissorBox = " << Rect2i(oldcissorBox[0], oldcissorBox[1], oldcissorBox[2], oldcissorBox[3]) << std::endl) //set scissor test r4::recti scissor = this->compute_viewport_rect(matrix); r4::recti oldScissor; bool scissorTestWasEnabled = morda::inst().renderer().isScissorEnabled(); if(scissorTestWasEnabled){ oldScissor = morda::inst().renderer().getScissorRect(); scissor.intersect(oldScissor); }else{ morda::inst().renderer().setScissorEnabled(true); } morda::inst().renderer().setScissorRect(scissor); this->render(matrix); if(scissorTestWasEnabled){ morda::inst().renderer().setScissorRect(oldScissor); }else{ morda::inst().renderer().setScissorEnabled(false); } }else{ this->render(matrix); } } //render border #ifdef M_MORDA_RENDER_WIDGET_BORDERS morda::ColorPosShader& s = App::inst().shaders.colorPosShader; s.Bind(); morda::Matr4r matr(matrix); matr.scale(this->rect().d); s.SetMatrix(matr); if(this->is_hovered()){ s.SetColor(r4::vec3f(0, 1, 0)); }else{ s.SetColor(r4::vec3f(1, 0, 1)); } s.render(s.quad01Fan, Shader::EMode::LINE_LOOP); #endif } std::shared_ptr<Texture2D> widget::render_to_texture(std::shared_ptr<Texture2D> reuse) const { std::shared_ptr<Texture2D> tex; if(reuse && reuse->dims() == this->rect().d){ tex = std::move(reuse); }else{ tex = morda::inst().renderer().factory->createTexture2D( morda::Texture2D::TexType_e::RGBA, this->rect().d.to<unsigned>(), nullptr ); } auto& r = morda::inst().renderer(); ASSERT(tex) r.setFramebuffer(r.factory->createFramebuffer(tex)); // ASSERT_INFO(Render::isBoundFrameBufferComplete(), "tex.dim() = " << tex.dim()) auto oldViewport = morda::inst().renderer().getViewport(); utki::ScopeExit scopeExit([&oldViewport](){ morda::inst().renderer().setViewport(oldViewport); }); morda::inst().renderer().setViewport(r4::recti(r4::vec2i(0), this->rect().d.to<int>())); morda::inst().renderer().clearFramebuffer(); Matr4r matrix = morda::inst().renderer().initialMatrix; matrix.translate(-1, 1); matrix.scale(Vec2r(2.0f, -2.0f).compDivBy(this->rect().d)); this->render(matrix); r.setFramebuffer(nullptr); return tex; } void widget::renderFromCache(const r4::mat4f& matrix) const { morda::Matr4r matr(matrix); matr.scale(this->rect().d); auto& r = morda::inst().renderer(); ASSERT(this->cacheTex) r.shader->posTex->render(matr, *r.posTexQuad01VAO, *this->cacheTex); } void widget::clearCache(){ this->cacheDirty = true; if(this->parent_v){ this->parent_v->clearCache(); } } void widget::onKeyInternal(bool isDown, key keyCode){ if(this->is_interactive()){ if(this->on_key(isDown, keyCode)){ return; } } if(this->parent()){ this->parent()->onKeyInternal(isDown, keyCode); } } void widget::focus()noexcept{ // ASSERT(App::inst().thisIsUIThread()) if(this->is_focused()){ return; } Morda::inst().setFocusedWidget(this->sharedFromThis(this)); } void widget::unfocus()noexcept{ // ASSERT(App::inst().thisIsUIThread()) if(!this->is_focused()){ return; } ASSERT(Morda::inst().focusedWidget.lock() && Morda::inst().focusedWidget.lock().operator->() == this) Morda::inst().setFocusedWidget(nullptr); } r4::recti widget::compute_viewport_rect(const Matr4r& matrix) const noexcept{ r4::recti ret( ((matrix * Vec2r(0, 0) + Vec2r(1, 1)) / 2).compMulBy(morda::inst().renderer().getViewport().d.to<real>()).rounded().to<int>(), this->rect().d.to<int>() ); ret.p.y -= ret.d.y; return ret; } Vec2r widget::measure(const morda::Vec2r& quotum) const{ Vec2r ret(quotum); for(unsigned i = 0; i != ret.size(); ++i){ if(ret[i] < 0){ ret[i] = 0; } } return ret; } vector2 widget::pos_in_ancestor(vector2 pos, const widget* ancestor) { if(ancestor == this || !this->parent()){ return pos; } ASSERT(this->parent()) return this->parent()->pos_in_ancestor(this->rect().p + pos, ancestor); } widget::LayoutParams& widget::get_layout_params() { if(!this->parent()){ throw morda::Exc("widget::get_layout_params(): widget is not added to any container, cannot get layout params. In order to get layout params the widget should be added to some container."); } return this->parent()->get_layout_params(*this); } const widget::LayoutParams& widget::get_layout_params()const { if(!this->parent()){ throw morda::Exc("widget::get_layout_params(): widget is not added to any container, cannot get layout params. In order to get layout params the widget should be added to some container."); } return this->parent()->get_layout_params(*this); } Widget& widget::get_widget(const std::string& id) { auto w = this->try_get_widget(id); if(!w){ std::stringstream ss; ss << "Widget '" << id << "' not found in '" << this->id << "'"; throw utki::not_found(ss.str()); } return *w; } void widget::set_enabled(bool enable) { // TRACE(<< "widget::set_enabled(): enable = " << enable << " this->name() = " << this->name()<< std::endl) if(this->isEnabled_v == enable){ return; } this->isEnabled_v = enable; //Un-hover this widget if it becomes disabled because it is not supposed to receive mouse input. if(!this->is_enabled()){ this->set_unhovered(); } this->on_enabled_changed(); } void widget::set_visible(bool visible) { this->isVisible_v = visible; if (!this->isVisible_v) { this->set_unhovered(); } } void widget::set_unhovered() { auto hoverSet = std::move(this->hovered); ASSERT(this->hovered.size() == 0) for(auto h : hoverSet){ this->on_hover_changed(h); } } void widget::set_hovered(bool isHovered, unsigned pointerID) { if(isHovered == this->is_hovered(pointerID)){ return; } // TRACE(<< "widget::setHovered(): isHovered = " << isHovered << " this->name() = " << this->name() << std::endl) if (isHovered) { ASSERT(!this->is_hovered(pointerID)) this->hovered.insert(pointerID); } else { ASSERT(this->is_hovered(pointerID)) this->hovered.erase(pointerID); } this->on_hover_changed(pointerID); } <commit_msg>stuff<commit_after>#include "../Morda.hpp" #include "../util/util.hpp" #include "widget.hpp" #include "container.hpp" using namespace morda; widget::widget(const puu::forest& desc){ for(const auto& p : desc){ if(!is_property(p)){ continue; } if(p.value == "layout"){ this->layout_desc = p.children; }else if(p.value == "x"){ this->rectangle.p.x = parse_dimension_value(get_property_value(p)); }else if(p.value == "y"){ this->rectangle.p.y = parse_dimension_value(get_property_value(p)); }else if(p.value == "dx"){ this->rectangle.d.x = parse_dimension_value(get_property_value(p)); }else if(p.value == "dy"){ this->rectangle.d.y = parse_dimension_value(get_property_value(p)); }else if(p.value == "id"){ this->id = get_property_value(p).to_string(); }else if(p.value == "name"){ //TODO: remove deprecated stuff. this->id = get_property_value(p).to_string(); TRACE_ALWAYS(<< "DEPRECATED!!! the 'name' attribute is deprecated (used by '" << this->id << "'), use 'id' instead" << std::endl) }else if(p.value == "clip"){ this->clip_v = get_property_value(p).to_bool(); }else if(p.value == "cache"){ this->cache = get_property_value(p).to_bool(); }else if(p.value == "visible"){ this->isVisible_v = get_property_value(p).to_bool(); }else if(p.value == "enabled"){ this->isEnabled_v = get_property_value(p).to_bool(); } } } widget::widget(const stob::Node* chain) : widget(stob_to_puu(chain)) {} widget::layout_params::layout_params(const puu::forest& desc){ for(const auto& p : desc){ if(!is_property(p)){ continue; } if(p.value == "dx"){ this->dims.x = parse_layout_dimension_value(get_property_value(p)); }else if(p.value == "dy"){ this->dims.y = parse_layout_dimension_value(get_property_value(p)); } } } std::shared_ptr<Widget> widget::try_get_widget(const std::string& id)noexcept{ if(this->id == id){ return this->sharedFromThis(this); } return nullptr; } void widget::resize(const morda::Vec2r& newDims){ if(this->rectangle.d == newDims){ if(this->relayoutNeeded){ this->clearCache(); this->relayoutNeeded = false; this->lay_out(); } return; } this->clearCache(); this->rectangle.d = newDims; utki::clampBottom(this->rectangle.d.x, real(0.0f)); utki::clampBottom(this->rectangle.d.y, real(0.0f)); this->relayoutNeeded = false; this->on_resize(); // call virtual method } std::shared_ptr<Widget> widget::remove_from_parent(){ if(!this->parent_v){ throw morda::exception("widget::RemoveFromParent(): widget is not added to the parent"); } auto ret = this->sharedFromThis(this); this->parent_v->erase(this->parent_v->find(this)); return ret; } std::shared_ptr<Widget> widget::replace_by(std::shared_ptr<Widget> w) { if(!this->parent()){ throw morda::Exc("this widget is not added to any parent"); } this->parent()->insert(w, this->parent()->find(this)); if(w && w->layout_desc.empty()){ w->layout_desc = std::move(this->layout_desc); } return this->remove_from_parent(); } void widget::invalidate_layout()noexcept{ if(this->relayoutNeeded){ return; } this->relayoutNeeded = true; if(this->parent_v){ this->parent_v->invalidate_layout(); } this->cacheTex.reset(); } void widget::renderInternal(const morda::Matr4r& matrix)const{ if(!this->rect().d.isPositive()){ return; } if(this->cache){ if(this->cacheDirty){ bool scissorTestWasEnabled = morda::inst().renderer().isScissorEnabled(); morda::inst().renderer().setScissorEnabled(false); //check if can re-use old texture if(!this->cacheTex || this->cacheTex->dims() != this->rect().d){ this->cacheTex = this->render_to_texture(); }else{ ASSERT(this->cacheTex->dims() == this->rect().d) this->cacheTex = this->render_to_texture(std::move(this->cacheTex)); } morda::inst().renderer().setScissorEnabled(scissorTestWasEnabled); this->cacheDirty = false; } //After rendering to texture it is most likely there will be transparent areas, so enable simple blending applySimpleAlphaBlending(); this->renderFromCache(matrix); }else{ if(this->clip_v){ // TRACE(<< "widget::RenderInternal(): oldScissorBox = " << Rect2i(oldcissorBox[0], oldcissorBox[1], oldcissorBox[2], oldcissorBox[3]) << std::endl) //set scissor test r4::recti scissor = this->compute_viewport_rect(matrix); r4::recti oldScissor; bool scissorTestWasEnabled = morda::inst().renderer().isScissorEnabled(); if(scissorTestWasEnabled){ oldScissor = morda::inst().renderer().getScissorRect(); scissor.intersect(oldScissor); }else{ morda::inst().renderer().setScissorEnabled(true); } morda::inst().renderer().setScissorRect(scissor); this->render(matrix); if(scissorTestWasEnabled){ morda::inst().renderer().setScissorRect(oldScissor); }else{ morda::inst().renderer().setScissorEnabled(false); } }else{ this->render(matrix); } } //render border #ifdef M_MORDA_RENDER_WIDGET_BORDERS morda::ColorPosShader& s = App::inst().shaders.colorPosShader; s.Bind(); morda::Matr4r matr(matrix); matr.scale(this->rect().d); s.SetMatrix(matr); if(this->is_hovered()){ s.SetColor(r4::vec3f(0, 1, 0)); }else{ s.SetColor(r4::vec3f(1, 0, 1)); } s.render(s.quad01Fan, Shader::EMode::LINE_LOOP); #endif } std::shared_ptr<Texture2D> widget::render_to_texture(std::shared_ptr<Texture2D> reuse) const { std::shared_ptr<Texture2D> tex; if(reuse && reuse->dims() == this->rect().d){ tex = std::move(reuse); }else{ tex = morda::inst().renderer().factory->createTexture2D( morda::Texture2D::TexType_e::RGBA, this->rect().d.to<unsigned>(), nullptr ); } auto& r = morda::inst().renderer(); ASSERT(tex) r.setFramebuffer(r.factory->createFramebuffer(tex)); // ASSERT_INFO(Render::isBoundFrameBufferComplete(), "tex.dims() = " << tex.dims()) auto oldViewport = morda::inst().renderer().getViewport(); utki::ScopeExit scopeExit([&oldViewport](){ morda::inst().renderer().setViewport(oldViewport); }); morda::inst().renderer().setViewport(r4::recti(r4::vec2i(0), this->rect().d.to<int>())); morda::inst().renderer().clearFramebuffer(); Matr4r matrix = morda::inst().renderer().initialMatrix; matrix.translate(-1, 1); matrix.scale(Vec2r(2.0f, -2.0f).compDivBy(this->rect().d)); this->render(matrix); r.setFramebuffer(nullptr); return tex; } void widget::renderFromCache(const r4::mat4f& matrix) const { morda::Matr4r matr(matrix); matr.scale(this->rect().d); auto& r = morda::inst().renderer(); ASSERT(this->cacheTex) r.shader->posTex->render(matr, *r.posTexQuad01VAO, *this->cacheTex); } void widget::clearCache(){ this->cacheDirty = true; if(this->parent_v){ this->parent_v->clearCache(); } } void widget::onKeyInternal(bool isDown, key keyCode){ if(this->is_interactive()){ if(this->on_key(isDown, keyCode)){ return; } } if(this->parent()){ this->parent()->onKeyInternal(isDown, keyCode); } } void widget::focus()noexcept{ // ASSERT(App::inst().thisIsUIThread()) if(this->is_focused()){ return; } Morda::inst().setFocusedWidget(this->sharedFromThis(this)); } void widget::unfocus()noexcept{ // ASSERT(App::inst().thisIsUIThread()) if(!this->is_focused()){ return; } ASSERT(Morda::inst().focusedWidget.lock() && Morda::inst().focusedWidget.lock().operator->() == this) Morda::inst().setFocusedWidget(nullptr); } r4::recti widget::compute_viewport_rect(const Matr4r& matrix) const noexcept{ r4::recti ret( ((matrix * Vec2r(0, 0) + Vec2r(1, 1)) / 2).compMulBy(morda::inst().renderer().getViewport().d.to<real>()).rounded().to<int>(), this->rect().d.to<int>() ); ret.p.y -= ret.d.y; return ret; } Vec2r widget::measure(const morda::Vec2r& quotum) const{ Vec2r ret(quotum); for(unsigned i = 0; i != ret.size(); ++i){ if(ret[i] < 0){ ret[i] = 0; } } return ret; } vector2 widget::pos_in_ancestor(vector2 pos, const widget* ancestor) { if(ancestor == this || !this->parent()){ return pos; } ASSERT(this->parent()) return this->parent()->pos_in_ancestor(this->rect().p + pos, ancestor); } widget::LayoutParams& widget::get_layout_params() { if(!this->parent()){ throw morda::Exc("widget::get_layout_params(): widget is not added to any container, cannot get layout params. In order to get layout params the widget should be added to some container."); } return this->parent()->get_layout_params(*this); } const widget::LayoutParams& widget::get_layout_params()const { if(!this->parent()){ throw morda::Exc("widget::get_layout_params(): widget is not added to any container, cannot get layout params. In order to get layout params the widget should be added to some container."); } return this->parent()->get_layout_params(*this); } Widget& widget::get_widget(const std::string& id) { auto w = this->try_get_widget(id); if(!w){ std::stringstream ss; ss << "Widget '" << id << "' not found in '" << this->id << "'"; throw utki::not_found(ss.str()); } return *w; } void widget::set_enabled(bool enable) { // TRACE(<< "widget::set_enabled(): enable = " << enable << " this->name() = " << this->name()<< std::endl) if(this->isEnabled_v == enable){ return; } this->isEnabled_v = enable; //Un-hover this widget if it becomes disabled because it is not supposed to receive mouse input. if(!this->is_enabled()){ this->set_unhovered(); } this->on_enabled_changed(); } void widget::set_visible(bool visible) { this->isVisible_v = visible; if (!this->isVisible_v) { this->set_unhovered(); } } void widget::set_unhovered() { auto hoverSet = std::move(this->hovered); ASSERT(this->hovered.size() == 0) for(auto h : hoverSet){ this->on_hover_changed(h); } } void widget::set_hovered(bool isHovered, unsigned pointerID) { if(isHovered == this->is_hovered(pointerID)){ return; } // TRACE(<< "widget::setHovered(): isHovered = " << isHovered << " this->name() = " << this->name() << std::endl) if (isHovered) { ASSERT(!this->is_hovered(pointerID)) this->hovered.insert(pointerID); } else { ASSERT(this->is_hovered(pointerID)) this->hovered.erase(pointerID); } this->on_hover_changed(pointerID); } <|endoftext|>
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "random.h" #ifdef WIN32 #include "compat.h" // for Windows API #endif #include "util.h" // for LogPrint() #ifndef WIN32 #include <sys/time.h> #endif #include <cstring> // for memset() #include <openssl/crypto.h> #include <openssl/err.h> #include <openssl/rand.h> static inline int64_t GetPerformanceCounter() { int64_t nCounter = 0; #ifdef WIN32 QueryPerformanceCounter((LARGE_INTEGER*)&nCounter); #else timeval t; gettimeofday(&t, NULL); nCounter = (int64_t)(t.tv_sec * 1000000 + t.tv_usec); #endif return nCounter; } void RandAddSeed() { // Seed with CPU performance counter int64_t nCounter = GetPerformanceCounter(); RAND_add(&nCounter, sizeof(nCounter), 1.5); memset(&nCounter, 0, sizeof(nCounter)); } void RandAddSeedPerfmon() { RandAddSeed(); // This can take up to 2 seconds, so only do it every 10 minutes static int64_t nLastPerfmon; if (GetTime() < nLastPerfmon + 10 * 60) return; nLastPerfmon = GetTime(); #ifdef WIN32 // Don't need this on Linux, OpenSSL automatically uses /dev/urandom // Seed with the entire set of perfmon data std::vector <unsigned char> vData(250000,0); long ret = 0; unsigned long nSize = 0; const size_t nMaxSize = 10000000; // Bail out at more than 10MB of performance data while (true) { nSize = vData.size(); ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, begin_ptr(vData), &nSize); if (ret != ERROR_MORE_DATA || vData.size() >= nMaxSize) break; vData.resize(std::max((vData.size()*3)/2, nMaxSize)); // Grow size of buffer exponentially } RegCloseKey(HKEY_PERFORMANCE_DATA); if (ret == ERROR_SUCCESS) { RAND_add(begin_ptr(vData), nSize, nSize/100.0); OPENSSL_cleanse(begin_ptr(vData), nSize); LogPrint("rand", "%s: %lu bytes\n", __func__, nSize); } else { static bool warned = false; // Warn only once if (!warned) { LogPrintf("%s: Warning: RegQueryValueExA(HKEY_PERFORMANCE_DATA) failed with code %i\n", __func__, ret); warned = true; } } #endif } bool GetRandBytes(unsigned char *buf, int num) { if (RAND_bytes(buf, num) != 1) { LogPrintf("%s: OpenSSL RAND_bytes() failed with error: %s\n", __func__, ERR_error_string(ERR_get_error(), NULL)); return false; } return true; } uint64_t GetRand(uint64_t nMax) { if (nMax == 0) return 0; // The range of the random source must be a multiple of the modulus // to give every possible output value an equal possibility uint64_t nRange = (std::numeric_limits<uint64_t>::max() / nMax) * nMax; uint64_t nRand = 0; do { GetRandBytes((unsigned char*)&nRand, sizeof(nRand)); } while (nRand >= nRange); return (nRand % nMax); } int GetRandInt(int nMax) { return GetRand(nMax); } uint256 GetRandHash() { uint256 hash; GetRandBytes((unsigned char*)&hash, sizeof(hash)); return hash; } uint32_t insecure_rand_Rz = 11; uint32_t insecure_rand_Rw = 11; void seed_insecure_rand(bool fDeterministic) { // The seed values have some unlikely fixed points which we avoid. if(fDeterministic) { insecure_rand_Rz = insecure_rand_Rw = 11; } else { uint32_t tmp; do { GetRandBytes((unsigned char*)&tmp, 4); } while(tmp == 0 || tmp == 0x9068ffffU); insecure_rand_Rz = tmp; do { GetRandBytes((unsigned char*)&tmp, 4); } while(tmp == 0 || tmp == 0x464fffffU); insecure_rand_Rw = tmp; } } <commit_msg>make RandAddSeed() use OPENSSL_cleanse()<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "random.h" #ifdef WIN32 #include "compat.h" // for Windows API #endif #include "util.h" // for LogPrint() #ifndef WIN32 #include <sys/time.h> #endif #include <openssl/crypto.h> #include <openssl/err.h> #include <openssl/rand.h> static inline int64_t GetPerformanceCounter() { int64_t nCounter = 0; #ifdef WIN32 QueryPerformanceCounter((LARGE_INTEGER*)&nCounter); #else timeval t; gettimeofday(&t, NULL); nCounter = (int64_t)(t.tv_sec * 1000000 + t.tv_usec); #endif return nCounter; } void RandAddSeed() { // Seed with CPU performance counter int64_t nCounter = GetPerformanceCounter(); RAND_add(&nCounter, sizeof(nCounter), 1.5); OPENSSL_cleanse((void*)&nCounter, sizeof(nCounter)); } void RandAddSeedPerfmon() { RandAddSeed(); // This can take up to 2 seconds, so only do it every 10 minutes static int64_t nLastPerfmon; if (GetTime() < nLastPerfmon + 10 * 60) return; nLastPerfmon = GetTime(); #ifdef WIN32 // Don't need this on Linux, OpenSSL automatically uses /dev/urandom // Seed with the entire set of perfmon data std::vector <unsigned char> vData(250000,0); long ret = 0; unsigned long nSize = 0; const size_t nMaxSize = 10000000; // Bail out at more than 10MB of performance data while (true) { nSize = vData.size(); ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, begin_ptr(vData), &nSize); if (ret != ERROR_MORE_DATA || vData.size() >= nMaxSize) break; vData.resize(std::max((vData.size()*3)/2, nMaxSize)); // Grow size of buffer exponentially } RegCloseKey(HKEY_PERFORMANCE_DATA); if (ret == ERROR_SUCCESS) { RAND_add(begin_ptr(vData), nSize, nSize/100.0); OPENSSL_cleanse(begin_ptr(vData), nSize); LogPrint("rand", "%s: %lu bytes\n", __func__, nSize); } else { static bool warned = false; // Warn only once if (!warned) { LogPrintf("%s: Warning: RegQueryValueExA(HKEY_PERFORMANCE_DATA) failed with code %i\n", __func__, ret); warned = true; } } #endif } bool GetRandBytes(unsigned char *buf, int num) { if (RAND_bytes(buf, num) != 1) { LogPrintf("%s: OpenSSL RAND_bytes() failed with error: %s\n", __func__, ERR_error_string(ERR_get_error(), NULL)); return false; } return true; } uint64_t GetRand(uint64_t nMax) { if (nMax == 0) return 0; // The range of the random source must be a multiple of the modulus // to give every possible output value an equal possibility uint64_t nRange = (std::numeric_limits<uint64_t>::max() / nMax) * nMax; uint64_t nRand = 0; do { GetRandBytes((unsigned char*)&nRand, sizeof(nRand)); } while (nRand >= nRange); return (nRand % nMax); } int GetRandInt(int nMax) { return GetRand(nMax); } uint256 GetRandHash() { uint256 hash; GetRandBytes((unsigned char*)&hash, sizeof(hash)); return hash; } uint32_t insecure_rand_Rz = 11; uint32_t insecure_rand_Rw = 11; void seed_insecure_rand(bool fDeterministic) { // The seed values have some unlikely fixed points which we avoid. if(fDeterministic) { insecure_rand_Rz = insecure_rand_Rw = 11; } else { uint32_t tmp; do { GetRandBytes((unsigned char*)&tmp, 4); } while(tmp == 0 || tmp == 0x9068ffffU); insecure_rand_Rz = tmp; do { GetRandBytes((unsigned char*)&tmp, 4); } while(tmp == 0 || tmp == 0x464fffffU); insecure_rand_Rw = tmp; } } <|endoftext|>
<commit_before>/* * Copyright (c) 2015, 2016, 2017, 2018, 2019, 2020, Intel Corporation * * 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 Intel Corporation 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 LOG OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "record.hpp" #include <map> #include "Exception.hpp" #include "geopm.h" namespace geopm { std::string event_name(int event_type) { static const std::map<int, std::string> event_names { {EVENT_REGION_ENTRY, "REGION_ENTRY"}, {EVENT_REGION_EXIT, "REGION_EXIT"}, {EVENT_EPOCH_COUNT, "EPOCH_COUNT"}, {EVENT_HINT, "HINT"} }; auto it = event_names.find(event_type); if (it == event_names.end()) { throw geopm::Exception("unsupported event type: " + std::to_string(event_type), GEOPM_ERROR_INVALID, __FILE__, __LINE__); } return it->second; } int event_type(const std::string &event_name) { static const std::map<std::string, int> event_types { {"REGION_ENTRY", EVENT_REGION_ENTRY}, {"REGION_EXIT", EVENT_REGION_EXIT}, {"EPOCH_COUNT", EVENT_EPOCH_COUNT}, {"HINT", EVENT_HINT} }; auto it = event_types.find(event_name); if (it == event_types.end()) { throw geopm::Exception("invalid event type string: " + event_name, GEOPM_ERROR_INVALID, __FILE__, __LINE__); } return it->second; } std::string hint_name(uint64_t hint) { static const std::map<uint64_t, std::string> result_map { {GEOPM_REGION_HINT_UNKNOWN, "UNKNOWN"}, {GEOPM_REGION_HINT_COMPUTE, "COMPUTE"}, {GEOPM_REGION_HINT_MEMORY, "MEMORY"}, {GEOPM_REGION_HINT_NETWORK, "NETWORK"}, {GEOPM_REGION_HINT_IO, "IO"}, {GEOPM_REGION_HINT_SERIAL, "SERIAL"}, {GEOPM_REGION_HINT_PARALLEL, "PARALLEL"}, {GEOPM_REGION_HINT_IGNORE, "IGNORE"}, }; auto it = result_map.find(hint); if (it == result_map.end()) { throw Exception("Profile::hint_hame(): Invalid hint", GEOPM_ERROR_INVALID, __FILE__, __LINE__); } return it->second; } uint64_t hint_type(const std::string &hint_name) { static const std::map<std::string, uint64_t> result_map { {"UNKNOWN", GEOPM_REGION_HINT_UNKNOWN}, {"COMPUTE", GEOPM_REGION_HINT_COMPUTE}, {"MEMORY", GEOPM_REGION_HINT_MEMORY}, {"NETWORK", GEOPM_REGION_HINT_NETWORK}, {"IO", GEOPM_REGION_HINT_IO}, {"SERIAL", GEOPM_REGION_HINT_SERIAL}, {"PARALLEL", GEOPM_REGION_HINT_PARALLEL}, {"IGNORE", GEOPM_REGION_HINT_IGNORE}, }; auto it = result_map.find(hint_name); if (it == result_map.end()) { throw Exception("Profile::hint_type(): Unknown hint name: " + hint_name + "\n", GEOPM_ERROR_INVALID, __FILE__, __LINE__); } return it->second; } } <commit_msg>Fixup exception message<commit_after>/* * Copyright (c) 2015, 2016, 2017, 2018, 2019, 2020, Intel Corporation * * 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 Intel Corporation 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 LOG OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "record.hpp" #include <map> #include "Exception.hpp" #include "geopm.h" namespace geopm { std::string event_name(int event_type) { static const std::map<int, std::string> event_names { {EVENT_REGION_ENTRY, "REGION_ENTRY"}, {EVENT_REGION_EXIT, "REGION_EXIT"}, {EVENT_EPOCH_COUNT, "EPOCH_COUNT"}, {EVENT_HINT, "HINT"} }; auto it = event_names.find(event_type); if (it == event_names.end()) { throw geopm::Exception("unsupported event type: " + std::to_string(event_type), GEOPM_ERROR_INVALID, __FILE__, __LINE__); } return it->second; } int event_type(const std::string &event_name) { static const std::map<std::string, int> event_types { {"REGION_ENTRY", EVENT_REGION_ENTRY}, {"REGION_EXIT", EVENT_REGION_EXIT}, {"EPOCH_COUNT", EVENT_EPOCH_COUNT}, {"HINT", EVENT_HINT} }; auto it = event_types.find(event_name); if (it == event_types.end()) { throw geopm::Exception("invalid event type string: " + event_name, GEOPM_ERROR_INVALID, __FILE__, __LINE__); } return it->second; } std::string hint_name(uint64_t hint) { static const std::map<uint64_t, std::string> result_map { {GEOPM_REGION_HINT_UNKNOWN, "UNKNOWN"}, {GEOPM_REGION_HINT_COMPUTE, "COMPUTE"}, {GEOPM_REGION_HINT_MEMORY, "MEMORY"}, {GEOPM_REGION_HINT_NETWORK, "NETWORK"}, {GEOPM_REGION_HINT_IO, "IO"}, {GEOPM_REGION_HINT_SERIAL, "SERIAL"}, {GEOPM_REGION_HINT_PARALLEL, "PARALLEL"}, {GEOPM_REGION_HINT_IGNORE, "IGNORE"}, }; auto it = result_map.find(hint); if (it == result_map.end()) { throw Exception("hint_hame(): Invalid hint", GEOPM_ERROR_INVALID, __FILE__, __LINE__); } return it->second; } uint64_t hint_type(const std::string &hint_name) { static const std::map<std::string, uint64_t> result_map { {"UNKNOWN", GEOPM_REGION_HINT_UNKNOWN}, {"COMPUTE", GEOPM_REGION_HINT_COMPUTE}, {"MEMORY", GEOPM_REGION_HINT_MEMORY}, {"NETWORK", GEOPM_REGION_HINT_NETWORK}, {"IO", GEOPM_REGION_HINT_IO}, {"SERIAL", GEOPM_REGION_HINT_SERIAL}, {"PARALLEL", GEOPM_REGION_HINT_PARALLEL}, {"IGNORE", GEOPM_REGION_HINT_IGNORE}, }; auto it = result_map.find(hint_name); if (it == result_map.end()) { throw Exception("hint_type(): Unknown hint name: " + hint_name + "\n", GEOPM_ERROR_INVALID, __FILE__, __LINE__); } return it->second; } } <|endoftext|>
<commit_before>#include <osg/ApplicationUsage> #include <osg/Math> using namespace osg; ApplicationUsage::ApplicationUsage(const std::string& commandLineUsage): _commandLineUsage(commandLineUsage) { } ApplicationUsage* ApplicationUsage::instance() { static ApplicationUsage s_applicationUsage; return &s_applicationUsage; } void ApplicationUsage::addUsageExplanation(Type type,const std::string& option,const std::string& explanation) { switch(type) { case(COMMAND_LINE_OPTION): addCommandLineOption(option,explanation); break; case(ENVIRONMENTAL_VARIABLE): addEnvironmentalVariable(option,explanation); break; case(KEYBOARD_MOUSE_BINDING): addKeyboardMouseBinding(option,explanation); break; } } void ApplicationUsage::addCommandLineOption(const std::string& option,const std::string& explanation) { _commandLineOptions[option]=explanation; } void ApplicationUsage::addEnvironmentalVariable(const std::string& option,const std::string& explanation) { _environmentalVariables[option]=explanation; } void ApplicationUsage::addKeyboardMouseBinding(const std::string& option,const std::string& explanation) { _keyboardMouse[option]=explanation; } void ApplicationUsage::write(std::ostream& output, const ApplicationUsage::UsageMap& um,unsigned int widthOfOutput) { unsigned int maxNumCharsInOptions = 0; ApplicationUsage::UsageMap::const_iterator citr; for(citr=um.begin(); citr!=um.end(); ++citr) { maxNumCharsInOptions = maximum(maxNumCharsInOptions,(unsigned int)citr->first.length()); } unsigned int fullWidth = widthOfOutput; unsigned int optionPos = 2; unsigned int optionWidth = maxNumCharsInOptions; unsigned int explanationPos = 2+maxNumCharsInOptions+2; unsigned int explanationWidth = fullWidth-explanationPos; std::string line; for(citr=um.begin(); citr!=um.end(); ++citr) { line.assign(fullWidth,' '); line.replace(optionPos,optionWidth,citr->first); const std::string& explanation = citr->second; unsigned int pos = 0; unsigned int offset = 0; bool firstInLine = true; while (pos<explanation.length()) { if (firstInLine) offset = 0; // skip any leading white space. while (pos<explanation.length() && explanation[pos]==' ') { if (firstInLine) ++offset; ++pos; } firstInLine = false; unsigned int width = std::min((unsigned int)explanation.length()-pos,explanationWidth-offset); unsigned int slashn_pos = explanation.find('\n',pos); unsigned int extraSkip = 0; bool concatinated = false; if (slashn_pos!=std::string::npos) { if (slashn_pos<pos+width) { width = slashn_pos-pos; ++extraSkip; firstInLine = true; } else if (slashn_pos==pos+width) { ++extraSkip; firstInLine = true; } } if (pos+width<explanation.length()) { // now reduce width until we get a space or a return // so that we ensure that whole words are printed. while (width>0 && explanation[pos+width]!=' ' && explanation[pos+width]!='\n') --width; if (width==0) { // word must be longer than a whole line so will need // to concatinate it. width = explanationWidth-1; concatinated = true; } } line.replace(explanationPos+offset,explanationWidth, explanation, pos, width); if (concatinated) output << line << '-' << std::endl; else output << line << std::endl; // move to the next line of output. line.assign(fullWidth,' '); pos += width+extraSkip; } } } void ApplicationUsage::write(std::ostream& output,unsigned int widthOfOutput) { output << "Usage: "<<getCommandLineUsage()<<std::endl; bool needspace = false; if (!getCommandLineOptions().empty()) { if (needspace) output << std::endl; output << "Options:"<<std::endl; write(output,getCommandLineOptions(),widthOfOutput); needspace = true; } if (!getEnvironmentalVariables().empty()) { if (needspace) output << std::endl; output << "Environmental Variables:"<<std::endl; write(output,getEnvironmentalVariables(),widthOfOutput); needspace = true; } if (!getKeyboardMouseBindings().empty()) { if (needspace) output << std::endl; output << "Keyboard and Mouse Bindings:"<<std::endl; write(output,getKeyboardMouseBindings(),widthOfOutput); needspace = true; } } <commit_msg>Changed std::min to osg::minimum.<commit_after>#include <osg/ApplicationUsage> #include <osg/Math> using namespace osg; ApplicationUsage::ApplicationUsage(const std::string& commandLineUsage): _commandLineUsage(commandLineUsage) { } ApplicationUsage* ApplicationUsage::instance() { static ApplicationUsage s_applicationUsage; return &s_applicationUsage; } void ApplicationUsage::addUsageExplanation(Type type,const std::string& option,const std::string& explanation) { switch(type) { case(COMMAND_LINE_OPTION): addCommandLineOption(option,explanation); break; case(ENVIRONMENTAL_VARIABLE): addEnvironmentalVariable(option,explanation); break; case(KEYBOARD_MOUSE_BINDING): addKeyboardMouseBinding(option,explanation); break; } } void ApplicationUsage::addCommandLineOption(const std::string& option,const std::string& explanation) { _commandLineOptions[option]=explanation; } void ApplicationUsage::addEnvironmentalVariable(const std::string& option,const std::string& explanation) { _environmentalVariables[option]=explanation; } void ApplicationUsage::addKeyboardMouseBinding(const std::string& option,const std::string& explanation) { _keyboardMouse[option]=explanation; } void ApplicationUsage::write(std::ostream& output, const ApplicationUsage::UsageMap& um,unsigned int widthOfOutput) { unsigned int maxNumCharsInOptions = 0; ApplicationUsage::UsageMap::const_iterator citr; for(citr=um.begin(); citr!=um.end(); ++citr) { maxNumCharsInOptions = maximum(maxNumCharsInOptions,(unsigned int)citr->first.length()); } unsigned int fullWidth = widthOfOutput; unsigned int optionPos = 2; unsigned int optionWidth = maxNumCharsInOptions; unsigned int explanationPos = 2+maxNumCharsInOptions+2; unsigned int explanationWidth = fullWidth-explanationPos; std::string line; for(citr=um.begin(); citr!=um.end(); ++citr) { line.assign(fullWidth,' '); line.replace(optionPos,optionWidth,citr->first); const std::string& explanation = citr->second; unsigned int pos = 0; unsigned int offset = 0; bool firstInLine = true; while (pos<explanation.length()) { if (firstInLine) offset = 0; // skip any leading white space. while (pos<explanation.length() && explanation[pos]==' ') { if (firstInLine) ++offset; ++pos; } firstInLine = false; unsigned int width = minimum((unsigned int)explanation.length()-pos,explanationWidth-offset); unsigned int slashn_pos = explanation.find('\n',pos); unsigned int extraSkip = 0; bool concatinated = false; if (slashn_pos!=std::string::npos) { if (slashn_pos<pos+width) { width = slashn_pos-pos; ++extraSkip; firstInLine = true; } else if (slashn_pos==pos+width) { ++extraSkip; firstInLine = true; } } if (pos+width<explanation.length()) { // now reduce width until we get a space or a return // so that we ensure that whole words are printed. while (width>0 && explanation[pos+width]!=' ' && explanation[pos+width]!='\n') --width; if (width==0) { // word must be longer than a whole line so will need // to concatinate it. width = explanationWidth-1; concatinated = true; } } line.replace(explanationPos+offset,explanationWidth, explanation, pos, width); if (concatinated) output << line << '-' << std::endl; else output << line << std::endl; // move to the next line of output. line.assign(fullWidth,' '); pos += width+extraSkip; } } } void ApplicationUsage::write(std::ostream& output,unsigned int widthOfOutput) { output << "Usage: "<<getCommandLineUsage()<<std::endl; bool needspace = false; if (!getCommandLineOptions().empty()) { if (needspace) output << std::endl; output << "Options:"<<std::endl; write(output,getCommandLineOptions(),widthOfOutput); needspace = true; } if (!getEnvironmentalVariables().empty()) { if (needspace) output << std::endl; output << "Environmental Variables:"<<std::endl; write(output,getEnvironmentalVariables(),widthOfOutput); needspace = true; } if (!getKeyboardMouseBindings().empty()) { if (needspace) output << std::endl; output << "Keyboard and Mouse Bindings:"<<std::endl; write(output,getKeyboardMouseBindings(),widthOfOutput); needspace = true; } } <|endoftext|>
<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * 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 * OpenSceneGraph Public License for more details. */ #include <osgDB/ReentrantMutex> using namespace osgDB; using namespace OpenThreads; ReentrantMutex::ReentrantMutex(): _threadHoldingMutex(0), _lockCount(0) { } ReentrantMutex::~ReentrantMutex() { } int ReentrantMutex::lock() { if (_threadHoldingMutex==OpenThreads::Thread::CurrentThread() && _lockCount>0) { ++_lockCount; return 0; } else { int result = Mutex::lock(); if (result==0) { _threadHoldingMutex = OpenThreads::Thread::CurrentThread(); _lockCount = 1; } return result; } } int ReentrantMutex::unlock() { if (_threadHoldingMutex==OpenThreads::Thread::CurrentThread() && _lockCount>0) { --_lockCount; if (_lockCount<=0) return Mutex::unlock(); } return 0; } int ReentrantMutex::trylock() { if (_threadHoldingMutex==OpenThreads::Thread::CurrentThread() && _lockCount>0) { ++_lockCount; return 0; } else { int result = Mutex::trylock(); if (result==0) { _threadHoldingMutex = OpenThreads::Thread::CurrentThread(); _lockCount = 1; } return result; } } <commit_msg>Added a _threadHoldingMutex = 0; to ReentrantMutex::unlock() to avoid a potential bug with the mutex being aquired by two threads.<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * 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 * OpenSceneGraph Public License for more details. */ #include <osgDB/ReentrantMutex> using namespace osgDB; using namespace OpenThreads; ReentrantMutex::ReentrantMutex(): _threadHoldingMutex(0), _lockCount(0) { } ReentrantMutex::~ReentrantMutex() { } int ReentrantMutex::lock() { if (_threadHoldingMutex==OpenThreads::Thread::CurrentThread() && _lockCount>0) { ++_lockCount; return 0; } else { int result = Mutex::lock(); if (result==0) { _threadHoldingMutex = OpenThreads::Thread::CurrentThread(); _lockCount = 1; } return result; } } int ReentrantMutex::unlock() { if (_threadHoldingMutex==OpenThreads::Thread::CurrentThread() && _lockCount>0) { --_lockCount; if (_lockCount<=0) { _threadHoldingMutex = 0; return Mutex::unlock(); } } return 0; } int ReentrantMutex::trylock() { if (_threadHoldingMutex==OpenThreads::Thread::CurrentThread() && _lockCount>0) { ++_lockCount; return 0; } else { int result = Mutex::trylock(); if (result==0) { _threadHoldingMutex = OpenThreads::Thread::CurrentThread(); _lockCount = 1; } return result; } } <|endoftext|>
<commit_before>/* Copyright (c) 2012 - 2021 Advanced Micro Devices, 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. */ #include "commandqueue.hpp" #include "thread/monitor.hpp" #include "device/device.hpp" #include "platform/context.hpp" /*! * \file commandQueue.cpp * \brief Definitions for HostQueue object. * * \author Laurent Morichetti * \date October 2008 */ namespace amd { HostQueue::HostQueue(Context& context, Device& device, cl_command_queue_properties props, uint queueRTCUs, Priority priority, const std::vector<uint32_t>& cuMask) : CommandQueue(context, device, props, device.info().queueProperties_, queueRTCUs, priority, cuMask), lastEnqueueCommand_(nullptr), head_(nullptr), tail_(nullptr), isActive_(false), markerTsCount_(0) { if (AMD_DIRECT_DISPATCH) { // Initialize the queue thread_.Init(this); } else { if (thread_.state() >= Thread::INITIALIZED) { ScopedLock sl(queueLock_); thread_.start(this); queueLock_.wait(); } } if (GPU_FORCE_QUEUE_PROFILING) { properties().set(CL_QUEUE_PROFILING_ENABLE); } } bool HostQueue::terminate() { if (AMD_DIRECT_DISPATCH) { Command* marker = new Marker(*this, true); if (marker != nullptr) { marker->enqueue(); marker->awaitCompletion(); marker->release(); } thread_.acceptingCommands_ = false; thread_.Release(); } else { if (Os::isThreadAlive(thread_)) { Command* marker = nullptr; // Send a finish if the queue is still accepting commands. { ScopedLock sl(queueLock_); if (thread_.acceptingCommands_) { marker = new Marker(*this, false); if (marker != nullptr) { append(*marker); queueLock_.notify(); } } } if (marker != nullptr) { marker->awaitCompletion(); marker->release(); } // Wake-up the command loop, so it can exit { ScopedLock sl(queueLock_); thread_.acceptingCommands_ = false; queueLock_.notify(); } // FIXME_lmoriche: fix termination handshake while (thread_.state() < Thread::FINISHED) { Os::yield(); } } } if (Agent::shouldPostCommandQueueEvents()) { Agent::postCommandQueueFree(as_cl(this->asCommandQueue())); } return true; } void HostQueue::finish() { Command* command = nullptr; if (IS_HIP) { command = getLastQueuedCommand(true); if (AMD_DIRECT_DISPATCH && command == nullptr) { return; } } if (nullptr == command || vdev()->isHandlerPending()) { if (nullptr != command) { command->release(); } // Send a finish to make sure we finished all commands command = new Marker(*this, false); if (command == NULL) { return; } ClPrint(LOG_DEBUG, LOG_CMD, "Marker queued to ensure finish"); command->enqueue(); } // Check HW status of the ROCcrl event. Note: not all ROCclr modes support HW status static constexpr bool kWaitCompletion = true; if (!device().IsHwEventReady(command->event(), kWaitCompletion)) { ClPrint(LOG_DEBUG, LOG_CMD, "HW Event not ready, awaiting completion instead"); command->awaitCompletion(); } if (IS_HIP) { ScopedLock sl(vdev()->execution()); ScopedLock l(lastCmdLock_); // Runtime can clear the last command only if no other submissions occured during finish() if (command == lastEnqueueCommand_) { lastEnqueueCommand_->release(); lastEnqueueCommand_ = nullptr; } } command->release(); ClPrint(LOG_DEBUG, LOG_CMD, "All commands finished"); } void HostQueue::loop(device::VirtualDevice* virtualDevice) { // Notify the caller that the queue is ready to accept commands. { ScopedLock sl(queueLock_); thread_.acceptingCommands_ = true; queueLock_.notify(); } // Create a command batch with all the commands present in the queue. Command* head = NULL; Command* tail = NULL; while (true) { // Get one command from the queue Command* command = queue_.dequeue(); if (command == NULL) { ScopedLock sl(queueLock_); while ((command = queue_.dequeue()) == NULL) { if (!thread_.acceptingCommands_) { return; } queueLock_.wait(); } } command->retain(); // Process the command's event wait list. const Command::EventWaitList& events = command->eventWaitList(); bool dependencyFailed = false; ClPrint(LOG_DEBUG, LOG_CMD, "Command (%s) processing: %p ,events.size(): %d", getOclCommandKindString(command->type()), command, events.size()); for (const auto& it : events) { // Only wait if the command is enqueued into another queue. if (it->command().queue() != this) { // Runtime has to flush the current batch only if the dependent wait is blocking if (it->command().status() != CL_COMPLETE) { ClPrint(LOG_DEBUG, LOG_CMD, "Command (%s) %p awaiting event: %p", getOclCommandKindString(command->type()), command, it); virtualDevice->flush(head, true); tail = head = NULL; dependencyFailed |= !it->awaitCompletion(); } } } // Insert the command to the linked list. if (NULL == head) { // if the list is empty head = tail = command; } else { tail->setNext(command); tail = command; } if (dependencyFailed) { command->setStatus(CL_EXEC_STATUS_ERROR_FOR_EVENTS_IN_WAIT_LIST); continue; } ClPrint(LOG_DEBUG, LOG_CMD, "Command (%s) submitted: %p", getOclCommandKindString(command->type()), command); command->setStatus(CL_SUBMITTED); // Submit to the device queue. command->submit(*virtualDevice); // if this is a user invisible marker command, then flush if (0 == command->type()) { virtualDevice->flush(head); tail = head = NULL; } } // while (true) { } void HostQueue::append(Command& command) { // We retain the command here. It will be released when its status // changes to CL_COMPLETE if ((command.getWaitBits() & 0x1) != 0) { finish(); } command.retain(); command.setStatus(CL_QUEUED); queue_.enqueue(&command); if (!IS_HIP) { return; } // Set last submitted command Command* prevLastEnqueueCommand; command.retain(); { // lastCmdLock_ ensures that lastEnqueueCommand() can retain the command before it is swapped // out. We want to keep this critical section as short as possible, so the command should be // released outside this section. ScopedLock l(lastCmdLock_); prevLastEnqueueCommand = lastEnqueueCommand_; lastEnqueueCommand_ = &command; } if (prevLastEnqueueCommand != nullptr) { prevLastEnqueueCommand->release(); } } bool HostQueue::isEmpty() { // Get a snapshot of queue size return queue_.empty(); } Command* HostQueue::getLastQueuedCommand(bool retain) { if (AMD_DIRECT_DISPATCH) { // The batch update must be lock protected to avoid a race condition // when multiple threads submit/flush/update the batch at the same time ScopedLock sl(vdev()->execution()); // Since the lastCmdLock_ is acquired, it is safe to read and retain the lastEnqueueCommand. // It is guaranteed that the pointer will not change. if (retain && lastEnqueueCommand_ != nullptr) { lastEnqueueCommand_->retain(); } return lastEnqueueCommand_; } else { // Get last submitted command ScopedLock l(lastCmdLock_); // Since the lastCmdLock_ is acquired, it is safe to read and retain the lastEnqueueCommand. // It is guaranteed that the pointer will not change. if (retain && lastEnqueueCommand_ != nullptr) { lastEnqueueCommand_->retain(); } return lastEnqueueCommand_; } } DeviceQueue::~DeviceQueue() { delete virtualDevice_; ScopedLock lock(context().lock()); context().removeDeviceQueue(device(), this); } bool DeviceQueue::create() { const bool defaultDeviceQueue = properties().test(CL_QUEUE_ON_DEVICE_DEFAULT); bool result = false; virtualDevice_ = device().createVirtualDevice(this); if (virtualDevice_ != NULL) { result = true; context().addDeviceQueue(device(), this, defaultDeviceQueue); } return result; } } // namespace amd <commit_msg>SWDEV-352487 - Don't add notifications as the last command<commit_after>/* Copyright (c) 2012 - 2021 Advanced Micro Devices, 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. */ #include "commandqueue.hpp" #include "thread/monitor.hpp" #include "device/device.hpp" #include "platform/context.hpp" /*! * \file commandQueue.cpp * \brief Definitions for HostQueue object. * * \author Laurent Morichetti * \date October 2008 */ namespace amd { HostQueue::HostQueue(Context& context, Device& device, cl_command_queue_properties props, uint queueRTCUs, Priority priority, const std::vector<uint32_t>& cuMask) : CommandQueue(context, device, props, device.info().queueProperties_, queueRTCUs, priority, cuMask), lastEnqueueCommand_(nullptr), head_(nullptr), tail_(nullptr), isActive_(false), markerTsCount_(0) { if (AMD_DIRECT_DISPATCH) { // Initialize the queue thread_.Init(this); } else { if (thread_.state() >= Thread::INITIALIZED) { ScopedLock sl(queueLock_); thread_.start(this); queueLock_.wait(); } } if (GPU_FORCE_QUEUE_PROFILING) { properties().set(CL_QUEUE_PROFILING_ENABLE); } } bool HostQueue::terminate() { if (AMD_DIRECT_DISPATCH) { Command* marker = new Marker(*this, true); if (marker != nullptr) { marker->enqueue(); marker->awaitCompletion(); marker->release(); } thread_.acceptingCommands_ = false; thread_.Release(); } else { if (Os::isThreadAlive(thread_)) { Command* marker = nullptr; // Send a finish if the queue is still accepting commands. { ScopedLock sl(queueLock_); if (thread_.acceptingCommands_) { marker = new Marker(*this, false); if (marker != nullptr) { append(*marker); queueLock_.notify(); } } } if (marker != nullptr) { marker->awaitCompletion(); marker->release(); } // Wake-up the command loop, so it can exit { ScopedLock sl(queueLock_); thread_.acceptingCommands_ = false; queueLock_.notify(); } // FIXME_lmoriche: fix termination handshake while (thread_.state() < Thread::FINISHED) { Os::yield(); } } } if (Agent::shouldPostCommandQueueEvents()) { Agent::postCommandQueueFree(as_cl(this->asCommandQueue())); } return true; } void HostQueue::finish() { Command* command = nullptr; if (IS_HIP) { command = getLastQueuedCommand(true); if (command == nullptr) { return; } } if (nullptr == command || vdev()->isHandlerPending()) { if (nullptr != command) { command->release(); } // Send a finish to make sure we finished all commands command = new Marker(*this, false); if (command == NULL) { return; } ClPrint(LOG_DEBUG, LOG_CMD, "Marker queued to ensure finish"); command->enqueue(); } // Check HW status of the ROCcrl event. Note: not all ROCclr modes support HW status static constexpr bool kWaitCompletion = true; if (!device().IsHwEventReady(command->event(), kWaitCompletion)) { ClPrint(LOG_DEBUG, LOG_CMD, "HW Event not ready, awaiting completion instead"); command->awaitCompletion(); } if (IS_HIP) { ScopedLock sl(vdev()->execution()); ScopedLock l(lastCmdLock_); // Runtime can clear the last command only if no other submissions occured during finish() if (command == lastEnqueueCommand_) { lastEnqueueCommand_->release(); lastEnqueueCommand_ = nullptr; } } command->release(); ClPrint(LOG_DEBUG, LOG_CMD, "All commands finished"); } void HostQueue::loop(device::VirtualDevice* virtualDevice) { // Notify the caller that the queue is ready to accept commands. { ScopedLock sl(queueLock_); thread_.acceptingCommands_ = true; queueLock_.notify(); } // Create a command batch with all the commands present in the queue. Command* head = NULL; Command* tail = NULL; while (true) { // Get one command from the queue Command* command = queue_.dequeue(); if (command == NULL) { ScopedLock sl(queueLock_); while ((command = queue_.dequeue()) == NULL) { if (!thread_.acceptingCommands_) { return; } queueLock_.wait(); } } command->retain(); // Process the command's event wait list. const Command::EventWaitList& events = command->eventWaitList(); bool dependencyFailed = false; ClPrint(LOG_DEBUG, LOG_CMD, "Command (%s) processing: %p ,events.size(): %d", getOclCommandKindString(command->type()), command, events.size()); for (const auto& it : events) { // Only wait if the command is enqueued into another queue. if (it->command().queue() != this) { // Runtime has to flush the current batch only if the dependent wait is blocking if (it->command().status() != CL_COMPLETE) { ClPrint(LOG_DEBUG, LOG_CMD, "Command (%s) %p awaiting event: %p", getOclCommandKindString(command->type()), command, it); virtualDevice->flush(head, true); tail = head = NULL; dependencyFailed |= !it->awaitCompletion(); } } } // Insert the command to the linked list. if (NULL == head) { // if the list is empty head = tail = command; } else { tail->setNext(command); tail = command; } if (dependencyFailed) { command->setStatus(CL_EXEC_STATUS_ERROR_FOR_EVENTS_IN_WAIT_LIST); continue; } ClPrint(LOG_DEBUG, LOG_CMD, "Command (%s) submitted: %p", getOclCommandKindString(command->type()), command); command->setStatus(CL_SUBMITTED); // Submit to the device queue. command->submit(*virtualDevice); // if this is a user invisible marker command, then flush if (0 == command->type()) { virtualDevice->flush(head); tail = head = NULL; } } // while (true) { } void HostQueue::append(Command& command) { // We retain the command here. It will be released when its status // changes to CL_COMPLETE if ((command.getWaitBits() & 0x1) != 0) { finish(); } command.retain(); command.setStatus(CL_QUEUED); queue_.enqueue(&command); if (!IS_HIP) { return; } // Set last submitted command Command* prevLastEnqueueCommand = nullptr; // Attach only real commands and skip internal notifications for CPU queue if (command.waitingEvent() == nullptr) { command.retain(); // lastCmdLock_ ensures that lastEnqueueCommand() can retain the command before it is swapped // out. We want to keep this critical section as short as possible, so the command should be // released outside this section. ScopedLock l(lastCmdLock_); prevLastEnqueueCommand = lastEnqueueCommand_; lastEnqueueCommand_ = &command; } if (prevLastEnqueueCommand != nullptr) { prevLastEnqueueCommand->release(); } } bool HostQueue::isEmpty() { // Get a snapshot of queue size return queue_.empty(); } Command* HostQueue::getLastQueuedCommand(bool retain) { if (AMD_DIRECT_DISPATCH) { // The batch update must be lock protected to avoid a race condition // when multiple threads submit/flush/update the batch at the same time ScopedLock sl(vdev()->execution()); // Since the lastCmdLock_ is acquired, it is safe to read and retain the lastEnqueueCommand. // It is guaranteed that the pointer will not change. if (retain && lastEnqueueCommand_ != nullptr) { lastEnqueueCommand_->retain(); } return lastEnqueueCommand_; } else { // Get last submitted command ScopedLock l(lastCmdLock_); // Since the lastCmdLock_ is acquired, it is safe to read and retain the lastEnqueueCommand. // It is guaranteed that the pointer will not change. if (retain && lastEnqueueCommand_ != nullptr) { lastEnqueueCommand_->retain(); } return lastEnqueueCommand_; } } DeviceQueue::~DeviceQueue() { delete virtualDevice_; ScopedLock lock(context().lock()); context().removeDeviceQueue(device(), this); } bool DeviceQueue::create() { const bool defaultDeviceQueue = properties().test(CL_QUEUE_ON_DEVICE_DEFAULT); bool result = false; virtualDevice_ = device().createVirtualDevice(this); if (virtualDevice_ != NULL) { result = true; context().addDeviceQueue(device(), this, defaultDeviceQueue); } return result; } } // namespace amd <|endoftext|>
<commit_before>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date$ Version: $Revision: 17495 $ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "QmitkImageNavigatorView.h" #include "mitkNodePredicateDataType.h" #include "QmitkDataStorageComboBox.h" #include "QmitkStdMultiWidget.h" #include "mitkDataStorageEditorInput.h" // berry Includes #include <berryPlatform.h> #include <berryIWorkbenchPage.h> #include <berryConstants.h> #include <QMessageBox> const std::string QmitkImageNavigatorView::VIEW_ID = "org.mitk.views.imagenavigator"; class ImageNavigatorPartListener : public berry::IPartListener { public: ImageNavigatorPartListener(QmitkImageNavigatorView* view) : m_View(view) {} berry::IPartListener::Events::Types GetPartEventTypes() const { return berry::IPartListener::Events::OPENED | berry::IPartListener::Events::CLOSED; } void PartClosed(berry::IWorkbenchPartReference::Pointer partRef) { m_View->SetMultiWidget(0); } void PartOpened(berry::IWorkbenchPartReference::Pointer partRef) { if (partRef->GetId() == QmitkStdMultiWidgetEditor::EDITOR_ID) { if (partRef->GetId() == QmitkStdMultiWidgetEditor::EDITOR_ID) { if (QmitkStdMultiWidgetEditor::Pointer multiWidgetPart = partRef->GetPart(false).Cast<QmitkStdMultiWidgetEditor>()) { m_View->SetMultiWidget(multiWidgetPart->GetStdMultiWidget()); } else { m_View->SetMultiWidget(0); } } } } private: QmitkImageNavigatorView* m_View; }; QmitkImageNavigatorView::QmitkImageNavigatorView() : m_MultiWidget(NULL) { multiWidgetListener = new ImageNavigatorPartListener(this); } QmitkImageNavigatorView::~QmitkImageNavigatorView() { this->GetSite()->GetPage()->RemovePartListener(multiWidgetListener); //delete m_TransversalStepper; //delete m_SagittalStepper; //delete m_FrontalStepper; //delete m_TimeStepper; } void QmitkImageNavigatorView::CreateQtPartControl(QWidget *parent) { // create GUI widgets m_Controls.setupUi(parent); m_MultiWidget = this->GetActiveStdMultiWidget(); m_Controls.m_SliceNavigatorTransversal->SetInverseDirection(true); m_TransversalStepper = new QmitkStepperAdapter(m_Controls.m_SliceNavigatorTransversal, m_MultiWidget->mitkWidget1->GetSliceNavigationController()->GetSlice() , "sliceNavigatorTransversalFromSimpleExample"); m_SagittalStepper = new QmitkStepperAdapter(m_Controls.m_SliceNavigatorSagittal, m_MultiWidget->mitkWidget2->GetSliceNavigationController()->GetSlice(), "sliceNavigatorSagittalFromSimpleExample"); m_FrontalStepper = new QmitkStepperAdapter(m_Controls.m_SliceNavigatorFrontal, m_MultiWidget->mitkWidget3->GetSliceNavigationController()->GetSlice(), "sliceNavigatorFrontalFromSimpleExample"); m_TimeStepper = new QmitkStepperAdapter(m_Controls.m_SliceNavigatorTime, m_MultiWidget->GetTimeNavigationController()->GetTime(), "sliceNavigatorTimeFromSimpleExample"); this->GetSite()->GetPage()->AddPartListener(multiWidgetListener); } void QmitkImageNavigatorView::SetFocus () { } void QmitkImageNavigatorView::SetMultiWidget(QmitkStdMultiWidget* multiWidget) { m_MultiWidget = multiWidget; if (m_MultiWidget) { m_TransversalStepper->SetStepper(m_MultiWidget->mitkWidget1->GetSliceNavigationController()->GetSlice()); m_SagittalStepper->SetStepper(m_MultiWidget->mitkWidget2->GetSliceNavigationController()->GetSlice()); m_FrontalStepper->SetStepper(m_MultiWidget->mitkWidget3->GetSliceNavigationController()->GetSlice()); m_TimeStepper->SetStepper(m_MultiWidget->GetTimeNavigationController()->GetTime()); } else { m_TransversalStepper->SetStepper(0); m_SagittalStepper->SetStepper(0); m_FrontalStepper->SetStepper(0); m_TimeStepper->SetStepper(0); } } QmitkStdMultiWidget* QmitkImageNavigatorView::GetActiveStdMultiWidget() { QmitkStdMultiWidget* activeStdMultiWidget = 0; berry::IEditorPart::Pointer editor = this->GetSite()->GetPage()->GetActiveEditor(); if (editor.Cast<QmitkStdMultiWidgetEditor>().IsNotNull()) { activeStdMultiWidget = editor.Cast<QmitkStdMultiWidgetEditor>()->GetStdMultiWidget(); } else { mitk::DataStorageEditorInput::Pointer editorInput; editorInput = new mitk::DataStorageEditorInput(); berry::IEditorPart::Pointer editor = this->GetSite()->GetPage()->OpenEditor(editorInput, QmitkStdMultiWidgetEditor::EDITOR_ID, false); activeStdMultiWidget = editor.Cast<QmitkStdMultiWidgetEditor>()->GetStdMultiWidget(); } return activeStdMultiWidget; } int QmitkImageNavigatorView::GetSizeFlags(bool width) { if(!width) { return berry::Constants::MIN | berry::Constants::MAX | berry::Constants::FILL; } else { return 0; } } int QmitkImageNavigatorView::ComputePreferredSize(bool width, int /*availableParallel*/, int /*availablePerpendicular*/, int preferredResult) { if(width==false) { return 160; } else { return preferredResult; } } <commit_msg>The image navigator now checks which bundle is closed and only deletes its stdMultiWidget if the navigator itself or the stdMultiWidget tab is closed. Furthermore, new steppers are created in the SetMultiWidget method to reconnect to the view when it is reopened after pressing reinit.<commit_after>/*========================================================================= Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "QmitkImageNavigatorView.h" #include "mitkNodePredicateDataType.h" #include "QmitkDataStorageComboBox.h" #include "QmitkStdMultiWidget.h" #include "mitkDataStorageEditorInput.h" // berry Includes #include <berryPlatform.h> #include <berryIWorkbenchPage.h> #include <berryConstants.h> #include <QMessageBox> const std::string QmitkImageNavigatorView::VIEW_ID = "org.mitk.views.imagenavigator"; class ImageNavigatorPartListener : public berry::IPartListener { public: ImageNavigatorPartListener(QmitkImageNavigatorView* view) : m_View(view) {} berry::IPartListener::Events::Types GetPartEventTypes() const { return berry::IPartListener::Events::OPENED | berry::IPartListener::Events::CLOSED; } void PartClosed(berry::IWorkbenchPartReference::Pointer partRef) { if((partRef->GetId() == QmitkImageNavigatorView::VIEW_ID) || (partRef->GetId() == QmitkStdMultiWidgetEditor::EDITOR_ID)) { m_View->SetMultiWidget(0); } } void PartOpened(berry::IWorkbenchPartReference::Pointer partRef) { if (partRef->GetId() == QmitkStdMultiWidgetEditor::EDITOR_ID) { if (QmitkStdMultiWidgetEditor::Pointer multiWidgetPart = partRef->GetPart(false).Cast<QmitkStdMultiWidgetEditor>()) { m_View->SetMultiWidget(multiWidgetPart->GetStdMultiWidget()); } else { m_View->SetMultiWidget(0); } } } private: QmitkImageNavigatorView* m_View; }; QmitkImageNavigatorView::QmitkImageNavigatorView() : m_MultiWidget(NULL) { multiWidgetListener = new ImageNavigatorPartListener(this); } QmitkImageNavigatorView::~QmitkImageNavigatorView() { this->GetSite()->GetPage()->RemovePartListener(multiWidgetListener); } void QmitkImageNavigatorView::CreateQtPartControl(QWidget *parent) { // create GUI widgets m_Controls.setupUi(parent); m_MultiWidget = this->GetActiveStdMultiWidget(); m_Controls.m_SliceNavigatorTransversal->SetInverseDirection(true); m_TransversalStepper = new QmitkStepperAdapter(m_Controls.m_SliceNavigatorTransversal, m_MultiWidget->mitkWidget1->GetSliceNavigationController()->GetSlice() , "sliceNavigatorTransversalFromSimpleExample"); m_SagittalStepper = new QmitkStepperAdapter(m_Controls.m_SliceNavigatorSagittal, m_MultiWidget->mitkWidget2->GetSliceNavigationController()->GetSlice(), "sliceNavigatorSagittalFromSimpleExample"); m_FrontalStepper = new QmitkStepperAdapter(m_Controls.m_SliceNavigatorFrontal, m_MultiWidget->mitkWidget3->GetSliceNavigationController()->GetSlice(), "sliceNavigatorFrontalFromSimpleExample"); m_TimeStepper = new QmitkStepperAdapter(m_Controls.m_SliceNavigatorTime, m_MultiWidget->GetTimeNavigationController()->GetTime(), "sliceNavigatorTimeFromSimpleExample"); this->GetSite()->GetPage()->AddPartListener(multiWidgetListener); } void QmitkImageNavigatorView::SetFocus () { } void QmitkImageNavigatorView::SetMultiWidget(QmitkStdMultiWidget* multiWidget) { m_MultiWidget = multiWidget; if (m_MultiWidget) { m_TransversalStepper->deleteLater(); m_SagittalStepper->deleteLater(); m_FrontalStepper->deleteLater(); m_TimeStepper->deleteLater(); m_TransversalStepper = new QmitkStepperAdapter(m_Controls.m_SliceNavigatorTransversal, m_MultiWidget->mitkWidget1->GetSliceNavigationController()->GetSlice() , "sliceNavigatorTransversalFromSimpleExample"); m_SagittalStepper = new QmitkStepperAdapter(m_Controls.m_SliceNavigatorSagittal, m_MultiWidget->mitkWidget2->GetSliceNavigationController()->GetSlice(), "sliceNavigatorSagittalFromSimpleExample"); m_FrontalStepper = new QmitkStepperAdapter(m_Controls.m_SliceNavigatorFrontal, m_MultiWidget->mitkWidget3->GetSliceNavigationController()->GetSlice(), "sliceNavigatorFrontalFromSimpleExample"); m_TimeStepper = new QmitkStepperAdapter(m_Controls.m_SliceNavigatorTime, m_MultiWidget->GetTimeNavigationController()->GetTime(), "sliceNavigatorTimeFromSimpleExample"); } else { m_TransversalStepper->SetStepper(0); m_SagittalStepper->SetStepper(0); m_FrontalStepper->SetStepper(0); m_TimeStepper->SetStepper(0); } } QmitkStdMultiWidget* QmitkImageNavigatorView::GetActiveStdMultiWidget() { QmitkStdMultiWidget* activeStdMultiWidget = 0; berry::IEditorPart::Pointer editor = this->GetSite()->GetPage()->GetActiveEditor(); if (editor.Cast<QmitkStdMultiWidgetEditor>().IsNotNull()) { activeStdMultiWidget = editor.Cast<QmitkStdMultiWidgetEditor>()->GetStdMultiWidget(); } else { mitk::DataStorageEditorInput::Pointer editorInput; editorInput = new mitk::DataStorageEditorInput(); berry::IEditorPart::Pointer editor = this->GetSite()->GetPage()->OpenEditor(editorInput, QmitkStdMultiWidgetEditor::EDITOR_ID, false); activeStdMultiWidget = editor.Cast<QmitkStdMultiWidgetEditor>()->GetStdMultiWidget(); } return activeStdMultiWidget; } int QmitkImageNavigatorView::GetSizeFlags(bool width) { if(!width) { return berry::Constants::MIN | berry::Constants::MAX | berry::Constants::FILL; } else { return 0; } } int QmitkImageNavigatorView::ComputePreferredSize(bool width, int /*availableParallel*/, int /*availablePerpendicular*/, int preferredResult) { if(width==false) { return 160; } else { return preferredResult; } } <|endoftext|>
<commit_before>/*************************************************************************** * Copyright (C) 2006 by Ingo Kloecker <kloecker@kde.org> * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU Library General Public License as * * published by the Free Software Foundation; either version 2 of the * * License, or (at your option) any later version. * * * * This 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 Library 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. * ***************************************************************************/ #include "create.h" #include <QtCore/QDebug> #include <QtCore/QStringList> #include "akonadi.h" #include "akonadiconnection.h" #include "storage/datastore.h" #include "storage/entity.h" #include "storage/transaction.h" #include "handlerhelper.h" #include "storage/selectquerybuilder.h" #include "response.h" #include "libs/imapparser_p.h" #include "imapstreamparser.h" using namespace Akonadi; Create::Create( Scope::SelectionScope scope ) : Handler(), m_scope( scope ) { } bool Create::parseStream() { QString name = m_streamParser->readUtf8String(); if ( name.isEmpty() ) { return failureResponse( "Invalid collection name" ); } bool ok = false; Collection parent; if ( m_scope == Scope::Uid || m_scope == Scope::None ) { qint64 parentId = m_streamParser->readNumber( &ok ); if ( !ok ) { // RFC 3501 compat QString parentPath; int index = name.lastIndexOf( QLatin1Char('/') ); if ( index > 0 ) { parentPath = name.left( index ); name = name.mid( index + 1 ); parent = HandlerHelper::collectionFromIdOrName( parentPath.toUtf8() ); } else { parentId = 0; } } else { if ( parentId > 0 ) { parent = Collection::retrieveById( parentId ); } } if ( parentId != 0 && !parent.isValid() ) { return failureResponse( "Parent collection not found" ); } } else if ( m_scope == Scope::Rid ) { const QString rid = m_streamParser->readUtf8String(); if ( rid.isEmpty() ) { throw HandlerException( "Empty parent remote identifier" ); } if ( !connection()->resourceContext().isValid() ) { throw HandlerException( "Invalid resource context" ); } SelectQueryBuilder<Collection> qb; qb.addValueCondition( Collection::remoteIdColumn(), Query::Equals, rid ); qb.addValueCondition( Collection::resourceIdColumn(), Query::Equals, connection()->resourceContext().id() ); if ( !qb.exec() ) { throw HandlerException( "Unable to execute collection query" ); } const Collection::List cols = qb.result(); if ( cols.size() == 0 ) { throw HandlerException( "Parent collection not found" ); } else if ( cols.size() > 1 ) { throw HandlerException( "Parent collection is not unique" ); } parent = cols.first(); } qint64 resourceId = 0; bool forceVirtual = false; MimeType::List parentContentTypes; if ( parent.isValid() ) { // check if parent can contain a sub-folder parentContentTypes = parent.mimeTypes(); bool found = false, foundVirtual = false; Q_FOREACH ( const MimeType &mt, parentContentTypes ) { if ( mt.name() == QLatin1String( "inode/directory" ) ) { found = true; if ( foundVirtual ) { break; } } else if ( mt.name() == QLatin1String( "application/x-vnd.akonadi.collection.virtual" ) ) { foundVirtual = true; if ( found ) { break; } } } if ( !found && !foundVirtual ) { return failureResponse( "Parent collection can not contain sub-collections" ); } // If only virtual collections are supported, force every new collection to // be virtual. Otherwise depend on VIRTUAL attribute in the command if ( foundVirtual && !found ) { forceVirtual = true; } // inherit resource resourceId = parent.resourceId(); } else { // deduce owning resource from current session id QString sessionId = QString::fromUtf8( connection()->sessionId() ); Resource res = Resource::retrieveByName( sessionId ); if ( !res.isValid() ) { return failureResponse( "Cannot create top-level collection" ); } resourceId = res.id(); } Collection collection; if ( parent.isValid() ) { collection.setParentId( parent.id() ); } collection.setName( name ); collection.setResourceId( resourceId ); // attributes QList<QByteArray> attributes; QList<QByteArray> mimeTypes; QVector< QPair<QByteArray, QByteArray> > userDefAttrs; bool mimeTypesSet = false; attributes = m_streamParser->readParenthesizedList(); for ( int i = 0; i < attributes.count() - 1; i += 2 ) { const QByteArray key = attributes.at( i ); const QByteArray value = attributes.at( i + 1 ); if ( key == AKONADI_PARAM_REMOTEID ) { collection.setRemoteId( QString::fromUtf8( value ) ); } else if ( key == AKONADI_PARAM_REMOTEREVISION ) { collection.setRemoteRevision( QString::fromUtf8( value ) ); } else if ( key == AKONADI_PARAM_MIMETYPE ) { ImapParser::parseParenthesizedList( value, mimeTypes ); mimeTypesSet = true; } else if ( key == AKONADI_PARAM_CACHEPOLICY ) { HandlerHelper::parseCachePolicy( value, collection ); } else if ( key == AKONADI_PARAM_VIRTUAL ) { collection.setIsVirtual( value.toUInt() != 0 ); } else { userDefAttrs << qMakePair( key, value ); } } if ( forceVirtual ) { collection.setIsVirtual( true ); } DataStore *db = connection()->storageBackend(); Transaction transaction( db ); if ( !db->appendCollection( collection ) ) { return failureResponse( "Could not create collection " + name.toLocal8Bit() + " resourceId: " + QByteArray::number(resourceId)); } QStringList effectiveMimeTypes; if ( mimeTypesSet ) { Q_FOREACH ( const QByteArray &b, mimeTypes ) effectiveMimeTypes << QString::fromUtf8( b ); } else { Q_FOREACH ( const MimeType &mt, parentContentTypes ) effectiveMimeTypes << mt.name(); } if ( !db->appendMimeTypeForCollection( collection.id(), effectiveMimeTypes ) ) { return failureResponse( "Unable to append mimetype for collection " + name.toLocal8Bit() + " resourceId: " + QByteArray::number(resourceId) ); } // store user defined attributes typedef QPair<QByteArray,QByteArray> QByteArrayPair; Q_FOREACH ( const QByteArrayPair &attr, userDefAttrs ) { if ( !db->addCollectionAttribute( collection, attr.first, attr.second ) ) { return failureResponse( "Unable to add collection attribute." ); } } Response response; response.setUntagged(); // write out collection details db->activeCachePolicy( collection ); const QByteArray b = HandlerHelper::collectionToByteArray( collection ); response.setString( b ); Q_EMIT responseAvailable( response ); if ( !transaction.commit() ) { return failureResponse( "Unable to commit transaction." ); } return successResponse( "CREATE completed" ); } <commit_msg>Fix build<commit_after>/*************************************************************************** * Copyright (C) 2006 by Ingo Kloecker <kloecker@kde.org> * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU Library General Public License as * * published by the Free Software Foundation; either version 2 of the * * License, or (at your option) any later version. * * * * This 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 Library 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. * ***************************************************************************/ #include "create.h" #include <QtCore/QDebug> #include <QtCore/QStringList> #include "akonadi.h" #include "akonadiconnection.h" #include "storage/datastore.h" #include "storage/entity.h" #include "storage/transaction.h" #include "handlerhelper.h" #include "storage/selectquerybuilder.h" #include "libs/protocol_p.h" #include "response.h" #include "libs/imapparser_p.h" #include "imapstreamparser.h" using namespace Akonadi; Create::Create( Scope::SelectionScope scope ) : Handler(), m_scope( scope ) { } bool Create::parseStream() { QString name = m_streamParser->readUtf8String(); if ( name.isEmpty() ) { return failureResponse( "Invalid collection name" ); } bool ok = false; Collection parent; if ( m_scope == Scope::Uid || m_scope == Scope::None ) { qint64 parentId = m_streamParser->readNumber( &ok ); if ( !ok ) { // RFC 3501 compat QString parentPath; int index = name.lastIndexOf( QLatin1Char('/') ); if ( index > 0 ) { parentPath = name.left( index ); name = name.mid( index + 1 ); parent = HandlerHelper::collectionFromIdOrName( parentPath.toUtf8() ); } else { parentId = 0; } } else { if ( parentId > 0 ) { parent = Collection::retrieveById( parentId ); } } if ( parentId != 0 && !parent.isValid() ) { return failureResponse( "Parent collection not found" ); } } else if ( m_scope == Scope::Rid ) { const QString rid = m_streamParser->readUtf8String(); if ( rid.isEmpty() ) { throw HandlerException( "Empty parent remote identifier" ); } if ( !connection()->resourceContext().isValid() ) { throw HandlerException( "Invalid resource context" ); } SelectQueryBuilder<Collection> qb; qb.addValueCondition( Collection::remoteIdColumn(), Query::Equals, rid ); qb.addValueCondition( Collection::resourceIdColumn(), Query::Equals, connection()->resourceContext().id() ); if ( !qb.exec() ) { throw HandlerException( "Unable to execute collection query" ); } const Collection::List cols = qb.result(); if ( cols.size() == 0 ) { throw HandlerException( "Parent collection not found" ); } else if ( cols.size() > 1 ) { throw HandlerException( "Parent collection is not unique" ); } parent = cols.first(); } qint64 resourceId = 0; bool forceVirtual = false; MimeType::List parentContentTypes; if ( parent.isValid() ) { // check if parent can contain a sub-folder parentContentTypes = parent.mimeTypes(); bool found = false, foundVirtual = false; Q_FOREACH ( const MimeType &mt, parentContentTypes ) { if ( mt.name() == QLatin1String( "inode/directory" ) ) { found = true; if ( foundVirtual ) { break; } } else if ( mt.name() == QLatin1String( "application/x-vnd.akonadi.collection.virtual" ) ) { foundVirtual = true; if ( found ) { break; } } } if ( !found && !foundVirtual ) { return failureResponse( "Parent collection can not contain sub-collections" ); } // If only virtual collections are supported, force every new collection to // be virtual. Otherwise depend on VIRTUAL attribute in the command if ( foundVirtual && !found ) { forceVirtual = true; } // inherit resource resourceId = parent.resourceId(); } else { // deduce owning resource from current session id QString sessionId = QString::fromUtf8( connection()->sessionId() ); Resource res = Resource::retrieveByName( sessionId ); if ( !res.isValid() ) { return failureResponse( "Cannot create top-level collection" ); } resourceId = res.id(); } Collection collection; if ( parent.isValid() ) { collection.setParentId( parent.id() ); } collection.setName( name ); collection.setResourceId( resourceId ); // attributes QList<QByteArray> attributes; QList<QByteArray> mimeTypes; QVector< QPair<QByteArray, QByteArray> > userDefAttrs; bool mimeTypesSet = false; attributes = m_streamParser->readParenthesizedList(); for ( int i = 0; i < attributes.count() - 1; i += 2 ) { const QByteArray key = attributes.at( i ); const QByteArray value = attributes.at( i + 1 ); if ( key == AKONADI_PARAM_REMOTEID ) { collection.setRemoteId( QString::fromUtf8( value ) ); } else if ( key == AKONADI_PARAM_REMOTEREVISION ) { collection.setRemoteRevision( QString::fromUtf8( value ) ); } else if ( key == AKONADI_PARAM_MIMETYPE ) { ImapParser::parseParenthesizedList( value, mimeTypes ); mimeTypesSet = true; } else if ( key == AKONADI_PARAM_CACHEPOLICY ) { HandlerHelper::parseCachePolicy( value, collection ); } else if ( key == AKONADI_PARAM_VIRTUAL ) { collection.setIsVirtual( value.toUInt() != 0 ); } else { userDefAttrs << qMakePair( key, value ); } } if ( forceVirtual ) { collection.setIsVirtual( true ); } DataStore *db = connection()->storageBackend(); Transaction transaction( db ); if ( !db->appendCollection( collection ) ) { return failureResponse( "Could not create collection " + name.toLocal8Bit() + " resourceId: " + QByteArray::number(resourceId)); } QStringList effectiveMimeTypes; if ( mimeTypesSet ) { Q_FOREACH ( const QByteArray &b, mimeTypes ) effectiveMimeTypes << QString::fromUtf8( b ); } else { Q_FOREACH ( const MimeType &mt, parentContentTypes ) effectiveMimeTypes << mt.name(); } if ( !db->appendMimeTypeForCollection( collection.id(), effectiveMimeTypes ) ) { return failureResponse( "Unable to append mimetype for collection " + name.toLocal8Bit() + " resourceId: " + QByteArray::number(resourceId) ); } // store user defined attributes typedef QPair<QByteArray,QByteArray> QByteArrayPair; Q_FOREACH ( const QByteArrayPair &attr, userDefAttrs ) { if ( !db->addCollectionAttribute( collection, attr.first, attr.second ) ) { return failureResponse( "Unable to add collection attribute." ); } } Response response; response.setUntagged(); // write out collection details db->activeCachePolicy( collection ); const QByteArray b = HandlerHelper::collectionToByteArray( collection ); response.setString( b ); Q_EMIT responseAvailable( response ); if ( !transaction.commit() ) { return failureResponse( "Unable to commit transaction." ); } return successResponse( "CREATE completed" ); } <|endoftext|>