text
stringlengths
54
60.6k
<commit_before>#include "loci/PopulationLocus.hpp" #include "exception/ValueOutOfRangeException.hpp" #include <boost/any.hpp> #include <sstream> using namespace std; PopulationLocus::PopulationLocus(PopulationNode * node) { this->node = node; } PopulationLocus::~PopulationLocus() {} Genome * PopulationLocus::getIndex(int index) { return this->node->getIndex(index); } int PopulationLocus::topIndex() { return this->node->populationSize() - 1; } int PopulationLocus::randomIndex() { uniform_int_distribution<int> dist(0, this->node->populationSize()); return dist(this->generator); } bool PopulationLocus::isConstructive() { return true; } bool PopulationLocus::outOfRange(int i) { return i < 0 || i >= this->node->populationSize(); } string PopulationLocus::toString() { stringstream ss; for (int i = 0; i < population.size(); i++) { ss << "Locus uses node " << this->node->name(); } ss << "\nRandom Seed: " << seed << "\n"; return ss.str(); } string PopulationLocus::flatten(int index) { if (outOfRange(index)) throw ValueOutOfRangeException(); stringstream ss; ss << this->getIndex(index)->flatten(); return ss.str(); } <commit_msg>[PopulationLocus]: Fixed index-out-of-range error<commit_after>#include "loci/PopulationLocus.hpp" #include "exception/ValueOutOfRangeException.hpp" #include <boost/any.hpp> #include <sstream> using namespace std; PopulationLocus::PopulationLocus(PopulationNode * node) { this->node = node; } PopulationLocus::~PopulationLocus() {} Genome * PopulationLocus::getIndex(int index) { if (this->outOfRange(index)) throw ValueOutOfRangeException(); return this->node->getIndex(index); } int PopulationLocus::topIndex() { return this->node->populationSize() - 1; } int PopulationLocus::randomIndex() { uniform_int_distribution<int> dist(0, this->node->populationSize()-1); return dist(this->generator); } bool PopulationLocus::isConstructive() { return true; } bool PopulationLocus::outOfRange(int i) { return i < 0 || i >= this->node->populationSize(); } string PopulationLocus::toString() { stringstream ss; for (int i = 0; i < population.size(); i++) { ss << "Locus uses node " << this->node->name(); } ss << "\nRandom Seed: " << seed << "\n"; return ss.str(); } string PopulationLocus::flatten(int index) { if (outOfRange(index)) throw ValueOutOfRangeException(); stringstream ss; ss << this->getIndex(index)->flatten(); return ss.str(); } <|endoftext|>
<commit_before>#include <protobuf/LogFrame.pb.h> #include "InterpolatedPath.hpp" #include "Utils.hpp" #include "LogUtils.hpp" #include <stdexcept> #pragma mark InterpolatedPath using namespace std; using namespace Geometry2d; namespace Planning { InterpolatedPath::InterpolatedPath(const Geometry2d::Point &p0) { points.push_back(p0); } InterpolatedPath::InterpolatedPath(const Geometry2d::Point &p0, const Geometry2d::Point &p1) { points.push_back(p0); points.push_back(p1); } float InterpolatedPath::length(unsigned int start) const { if (points.empty() || start >= (points.size() - 1)) { return 0; } float length = 0; for (unsigned int i = start; i < (points.size() - 1); ++i) { length += (points[i + 1] - points[i]).mag(); } return length; } float InterpolatedPath::length(unsigned int start, unsigned int end) const { if (points.empty() || start >= (points.size() - 1)) { return 0; } float length = 0; for (unsigned int i = start; i < end; ++i) { length += (points[i + 1] - points[i]).mag(); } return length; } boost::optional<Geometry2d::Point> InterpolatedPath::start() const { if (points.empty()) return boost::none; else return points.front(); } boost::optional<Geometry2d::Point> InterpolatedPath::destination() const { if (points.empty()) return boost::none; else return points.back(); } // Returns the index of the point in this path nearest to pt. int InterpolatedPath::nearestIndex(const Geometry2d::Point &pt) const { if (points.size() == 0) { return -1; } int index = 0; float dist = pt.distTo(points[0]); for (unsigned int i = 1; i < points.size(); ++i) { float d = pt.distTo(points[i]); if (d < dist) { dist = d; index = i; } } return index; } bool InterpolatedPath::hit(const Geometry2d::CompositeShape &obstacles, float startTime) const { int start = 0; for (float t: times) { start++; if (t > startTime) { start--; break; } } if (start >= points.size()) { // Empty path or starting beyond end of path return false; } //This code disreguards obstacles if which we start in. This the robot to move out a obstacle if it is already in one. // The set of obstacles the starting point was inside of std::set<std::shared_ptr<Geometry2d::Shape>> startHitSet; obstacles.hit(points[start], startHitSet); for (size_t i = 0; i < points.size() - 1; i++) { std::set<std::shared_ptr<Geometry2d::Shape>> newHitSet; if (obstacles.hit(Geometry2d::Segment(points[i], points[i+1]), newHitSet)) { for (std::shared_ptr<Geometry2d::Shape> hit : newHitSet) { //If it hits something, check if the hit was in hte origional hitSet if (startHitSet.find(hit) == startHitSet.end()) { return true; } } } } return false; } float InterpolatedPath::distanceTo(const Geometry2d::Point &pt) const { int i = nearestIndex(pt); if (i < 0) { return 0; } float dist = -1; for (unsigned int i = 0; i < (points.size() - 1); ++i) { Geometry2d::Segment s(points[i], points[i + 1]); const float d = s.distTo(pt); if (dist < 0 || d < dist) { dist = d; } } return dist; } Geometry2d::Segment InterpolatedPath::nearestSegment(const Geometry2d::Point &pt) const { Geometry2d::Segment best; float dist = -1; if (points.empty()) { return best; } for (unsigned int i = 0; i < (points.size() - 1); ++i) { Geometry2d::Segment s(points[i], points[i + 1]); const float d = s.distTo(pt); if (dist < 0 || d < dist) { best = s; dist = d; } } return best; } void InterpolatedPath::startFrom(const Geometry2d::Point &pt, InterpolatedPath &result) const { // path will start at the current robot pose result.clear(); result.points.push_back(pt); if (points.empty()) return; // handle simple paths if (points.size() == 1) { result.points.push_back(points.front()); return; } // find where to start the path Geometry2d::Segment close_segment; float dist = -1; unsigned int i = (points.front().nearPoint(pt, 0.02)) ? 1 : 0; vector<Geometry2d::Point>::const_iterator path_start = ++points.begin(); for (; i < (points.size() - 1); ++i) { Geometry2d::Segment s(points[i], points[i + 1]); const float d = s.distTo(pt); if (dist < 0 || d < dist) { close_segment = s; dist = d; } } // slice path // new path will be pt, [closest point on nearest segment], [i+1 to end] if (dist > 0.0 && dist < 0.02) { Geometry2d::Point intersection_pt = close_segment.nearestPoint(pt); result.points.push_back(intersection_pt); } result.points.insert(result.points.end(), path_start, points.end()); } float InterpolatedPath::length(const Geometry2d::Point &pt) const { float dist = -1; float length = 0; if (points.empty()) { return 0; } for (unsigned int i = 0; i < (points.size() - 1); ++i) { Geometry2d::Segment s(points[i], points[i + 1]); //add the segment length length += s.length(); const float d = s.distTo(pt); //if point closer to this segment if (dist < 0 || d < dist) { //closest point on segment Geometry2d::Point p = s.nearestPoint(pt); //new best distance dist = d; //reset running length count length = 0; length += p.distTo(s.pt[1]); } } return length; } bool InterpolatedPath::getPoint(float distance, Geometry2d::Point &position, Geometry2d::Point &direction) const { if (distance <= 0) { position = points.front(); return false; } if (points.empty()) { return false; } for (unsigned int i = 0; i < (points.size() - 1); ++i) { Geometry2d::Point vector(points[i + 1] - points[i]); float vectorLength = vector.mag(); distance -= vectorLength; if (distance <= 0) { distance += vectorLength; position = points[i] + (vector * (distance / vectorLength)); direction = vector.normalized(); return true; } } position = points.back(); return false; } void InterpolatedPath::draw(SystemState *const state, const QColor &col = Qt::black, const QString &layer = "Motion") const { Packet::DebugPath *dbg = state->logFrame->add_debug_paths(); dbg->set_layer(state->findDebugLayer(layer)); for (Geometry2d::Point pt : points) { *dbg->add_points() = pt; } dbg->set_color(color(col)); return; } bool InterpolatedPath::evaluate(float t, Geometry2d::Point &targetPosOut, Geometry2d::Point &targetVelOut) const { /* float linearPos; float linearSpeed; bool pathIsValid = TrapezoidalMotion( length(), maxSpeed, maxAcceleration, t, startSpeed, endSpeed, linearPos, // these are set by reference since C++ can't return multiple values linearSpeed); // Geometry2d::Point direction; if(!getPoint(linearPos, targetPosOut, direction)) { return false; } targetVelOut = direction * linearSpeed; */ if (times.size() == 0) { targetPosOut = Geometry2d::Point(0, 0); targetVelOut = Geometry2d::Point(0, 0); return false; } if (times.size() == 1) { targetPosOut = points[0]; targetVelOut = Geometry2d::Point(0, 0); return false; } if (t < times[0]) { targetPosOut = points[0]; targetVelOut = vels[0]; return false; } int i = 0; while (times[i] <= t) { if (times[i] == t) { targetPosOut = points[i]; targetVelOut = vels[i]; return true; } i++; if (i == size()) { targetPosOut = points[i - 1]; targetVelOut = vels[i - 1]; return false; } } float deltaT = (times[i] - times[i - 1]); if (deltaT == 0) { targetPosOut = points[i]; targetVelOut = vels[i]; return true; } float constant = (t - times[i - 1]) / deltaT; targetPosOut = points[i - 1] * (1 - constant) + points[i] * (constant); targetVelOut = vels[i - 1] * (1 - constant) + vels[i] * (constant); return true; } size_t InterpolatedPath::size() const { return points.size(); } bool InterpolatedPath::valid() const { return !points.empty(); } float InterpolatedPath::getTime(int index) const { return times[index]; } float InterpolatedPath::getDuration() const { if (times.size() > 0) { return times.back(); } else { return 0; } } unique_ptr<Path> InterpolatedPath::subPath(float startTime, float endTime) const { //Check for valid arguments if (startTime < 0) { throw invalid_argument("InterpolatedPath::subPath(): startTime(" + to_string(startTime) + ") can't be less than zero"); } if (endTime < 0) { throw invalid_argument("InterpolatedPath::subPath(): endTime(" + to_string(endTime) + ") can't be less than zero"); } if (startTime > endTime) { throw invalid_argument("InterpolatedPath::subPath(): startTime(" + to_string(startTime) + ") can't be after endTime(" + to_string(endTime) + ")"); } if (startTime >= getDuration()) { debugThrow(invalid_argument("InterpolatedPath::subPath(): startTime(" + to_string(startTime) + ") can't be greater than the duration(" + to_string(getDuration()) + ") of the path")); return unique_ptr<Path>(new InterpolatedPath()); } if (startTime == 0 && endTime >= getDuration()) { return this->clone(); } InterpolatedPath *path = new InterpolatedPath(); //Bound the endTime to a reasonable time. endTime = min(endTime, getDuration()); //Find the first point in the vector of points which will be included in the subPath size_t start = 0; while (times[start] <= startTime) { start++; } start--; //Add the first points to the InterpolatedPath path->times.push_back(0); if (times[start] == startTime) { path->points.push_back(points[start]); path->vels.push_back(vels[start]); } else { float deltaT = (times[start + 1] - times[start]); float constant = (times[start + 1] - startTime) / deltaT; Point startPos = points[start + 1] * (1 - constant) + points[start] * (constant); Point vi = vels[start + 1] * (1 - constant) + vels[start] * (constant); path->points.push_back(startPos); path->vels.push_back(vi); } //Find the last point in the InterpolatedPath Point vf; Point endPos; size_t end; if (endTime >= getDuration()) { end = size() - 1; vf = vels[end]; endPos = points[end]; } else { end = start + 1; while (times[end] < endTime) { end++; } float deltaT = (times[end] - times[end - 1]); float constant = (times[end] - endTime) / deltaT; //endTime = times[end]; vf = vels[end] * (1 - constant) + vels[end - 1] * (constant); endPos = points[end] * (1 - constant) + points[end - 1] * (constant); } //Add all the points in the middle size_t i = start + 1; while (i < end) { path->points.push_back(points[i]); path->vels.push_back(vels[i]); path->times.push_back(times[i] - startTime); i++; } //Add the last point path->points.push_back(endPos); path->vels.push_back(vf); path->times.push_back(endTime - startTime); return unique_ptr<Path>(path); } unique_ptr<Path> InterpolatedPath::clone() const { return unique_ptr<Path>(new InterpolatedPath(*this)); } }<commit_msg>InterpolatedPath.hit() starts from @start, not zero<commit_after>#include <protobuf/LogFrame.pb.h> #include "InterpolatedPath.hpp" #include "Utils.hpp" #include "LogUtils.hpp" #include <stdexcept> #pragma mark InterpolatedPath using namespace std; using namespace Geometry2d; namespace Planning { InterpolatedPath::InterpolatedPath(const Geometry2d::Point &p0) { points.push_back(p0); } InterpolatedPath::InterpolatedPath(const Geometry2d::Point &p0, const Geometry2d::Point &p1) { points.push_back(p0); points.push_back(p1); } float InterpolatedPath::length(unsigned int start) const { if (points.empty() || start >= (points.size() - 1)) { return 0; } float length = 0; for (unsigned int i = start; i < (points.size() - 1); ++i) { length += (points[i + 1] - points[i]).mag(); } return length; } float InterpolatedPath::length(unsigned int start, unsigned int end) const { if (points.empty() || start >= (points.size() - 1)) { return 0; } float length = 0; for (unsigned int i = start; i < end; ++i) { length += (points[i + 1] - points[i]).mag(); } return length; } boost::optional<Geometry2d::Point> InterpolatedPath::start() const { if (points.empty()) return boost::none; else return points.front(); } boost::optional<Geometry2d::Point> InterpolatedPath::destination() const { if (points.empty()) return boost::none; else return points.back(); } // Returns the index of the point in this path nearest to pt. int InterpolatedPath::nearestIndex(const Geometry2d::Point &pt) const { if (points.size() == 0) { return -1; } int index = 0; float dist = pt.distTo(points[0]); for (unsigned int i = 1; i < points.size(); ++i) { float d = pt.distTo(points[i]); if (d < dist) { dist = d; index = i; } } return index; } bool InterpolatedPath::hit(const Geometry2d::CompositeShape &obstacles, float startTime) const { int start = 0; for (float t: times) { start++; if (t > startTime) { start--; break; } } if (start >= points.size()) { // Empty path or starting beyond end of path return false; } //This code disreguards obstacles if which we start in. This the robot to move out a obstacle if it is already in one. // The set of obstacles the starting point was inside of std::set<std::shared_ptr<Geometry2d::Shape>> startHitSet; obstacles.hit(points[start], startHitSet); for (size_t i = start; i < points.size() - 1; i++) { std::set<std::shared_ptr<Geometry2d::Shape>> newHitSet; if (obstacles.hit(Geometry2d::Segment(points[i], points[i+1]), newHitSet)) { for (std::shared_ptr<Geometry2d::Shape> hit : newHitSet) { //If it hits something, check if the hit was in hte origional hitSet if (startHitSet.find(hit) == startHitSet.end()) { return true; } } } } return false; } float InterpolatedPath::distanceTo(const Geometry2d::Point &pt) const { int i = nearestIndex(pt); if (i < 0) { return 0; } float dist = -1; for (unsigned int i = 0; i < (points.size() - 1); ++i) { Geometry2d::Segment s(points[i], points[i + 1]); const float d = s.distTo(pt); if (dist < 0 || d < dist) { dist = d; } } return dist; } Geometry2d::Segment InterpolatedPath::nearestSegment(const Geometry2d::Point &pt) const { Geometry2d::Segment best; float dist = -1; if (points.empty()) { return best; } for (unsigned int i = 0; i < (points.size() - 1); ++i) { Geometry2d::Segment s(points[i], points[i + 1]); const float d = s.distTo(pt); if (dist < 0 || d < dist) { best = s; dist = d; } } return best; } void InterpolatedPath::startFrom(const Geometry2d::Point &pt, InterpolatedPath &result) const { // path will start at the current robot pose result.clear(); result.points.push_back(pt); if (points.empty()) return; // handle simple paths if (points.size() == 1) { result.points.push_back(points.front()); return; } // find where to start the path Geometry2d::Segment close_segment; float dist = -1; unsigned int i = (points.front().nearPoint(pt, 0.02)) ? 1 : 0; vector<Geometry2d::Point>::const_iterator path_start = ++points.begin(); for (; i < (points.size() - 1); ++i) { Geometry2d::Segment s(points[i], points[i + 1]); const float d = s.distTo(pt); if (dist < 0 || d < dist) { close_segment = s; dist = d; } } // slice path // new path will be pt, [closest point on nearest segment], [i+1 to end] if (dist > 0.0 && dist < 0.02) { Geometry2d::Point intersection_pt = close_segment.nearestPoint(pt); result.points.push_back(intersection_pt); } result.points.insert(result.points.end(), path_start, points.end()); } float InterpolatedPath::length(const Geometry2d::Point &pt) const { float dist = -1; float length = 0; if (points.empty()) { return 0; } for (unsigned int i = 0; i < (points.size() - 1); ++i) { Geometry2d::Segment s(points[i], points[i + 1]); //add the segment length length += s.length(); const float d = s.distTo(pt); //if point closer to this segment if (dist < 0 || d < dist) { //closest point on segment Geometry2d::Point p = s.nearestPoint(pt); //new best distance dist = d; //reset running length count length = 0; length += p.distTo(s.pt[1]); } } return length; } bool InterpolatedPath::getPoint(float distance, Geometry2d::Point &position, Geometry2d::Point &direction) const { if (distance <= 0) { position = points.front(); return false; } if (points.empty()) { return false; } for (unsigned int i = 0; i < (points.size() - 1); ++i) { Geometry2d::Point vector(points[i + 1] - points[i]); float vectorLength = vector.mag(); distance -= vectorLength; if (distance <= 0) { distance += vectorLength; position = points[i] + (vector * (distance / vectorLength)); direction = vector.normalized(); return true; } } position = points.back(); return false; } void InterpolatedPath::draw(SystemState *const state, const QColor &col = Qt::black, const QString &layer = "Motion") const { Packet::DebugPath *dbg = state->logFrame->add_debug_paths(); dbg->set_layer(state->findDebugLayer(layer)); for (Geometry2d::Point pt : points) { *dbg->add_points() = pt; } dbg->set_color(color(col)); return; } bool InterpolatedPath::evaluate(float t, Geometry2d::Point &targetPosOut, Geometry2d::Point &targetVelOut) const { /* float linearPos; float linearSpeed; bool pathIsValid = TrapezoidalMotion( length(), maxSpeed, maxAcceleration, t, startSpeed, endSpeed, linearPos, // these are set by reference since C++ can't return multiple values linearSpeed); // Geometry2d::Point direction; if(!getPoint(linearPos, targetPosOut, direction)) { return false; } targetVelOut = direction * linearSpeed; */ if (times.size() == 0) { targetPosOut = Geometry2d::Point(0, 0); targetVelOut = Geometry2d::Point(0, 0); return false; } if (times.size() == 1) { targetPosOut = points[0]; targetVelOut = Geometry2d::Point(0, 0); return false; } if (t < times[0]) { targetPosOut = points[0]; targetVelOut = vels[0]; return false; } int i = 0; while (times[i] <= t) { if (times[i] == t) { targetPosOut = points[i]; targetVelOut = vels[i]; return true; } i++; if (i == size()) { targetPosOut = points[i - 1]; targetVelOut = vels[i - 1]; return false; } } float deltaT = (times[i] - times[i - 1]); if (deltaT == 0) { targetPosOut = points[i]; targetVelOut = vels[i]; return true; } float constant = (t - times[i - 1]) / deltaT; targetPosOut = points[i - 1] * (1 - constant) + points[i] * (constant); targetVelOut = vels[i - 1] * (1 - constant) + vels[i] * (constant); return true; } size_t InterpolatedPath::size() const { return points.size(); } bool InterpolatedPath::valid() const { return !points.empty(); } float InterpolatedPath::getTime(int index) const { return times[index]; } float InterpolatedPath::getDuration() const { if (times.size() > 0) { return times.back(); } else { return 0; } } unique_ptr<Path> InterpolatedPath::subPath(float startTime, float endTime) const { //Check for valid arguments if (startTime < 0) { throw invalid_argument("InterpolatedPath::subPath(): startTime(" + to_string(startTime) + ") can't be less than zero"); } if (endTime < 0) { throw invalid_argument("InterpolatedPath::subPath(): endTime(" + to_string(endTime) + ") can't be less than zero"); } if (startTime > endTime) { throw invalid_argument("InterpolatedPath::subPath(): startTime(" + to_string(startTime) + ") can't be after endTime(" + to_string(endTime) + ")"); } if (startTime >= getDuration()) { debugThrow(invalid_argument("InterpolatedPath::subPath(): startTime(" + to_string(startTime) + ") can't be greater than the duration(" + to_string(getDuration()) + ") of the path")); return unique_ptr<Path>(new InterpolatedPath()); } if (startTime == 0 && endTime >= getDuration()) { return this->clone(); } InterpolatedPath *path = new InterpolatedPath(); //Bound the endTime to a reasonable time. endTime = min(endTime, getDuration()); //Find the first point in the vector of points which will be included in the subPath size_t start = 0; while (times[start] <= startTime) { start++; } start--; //Add the first points to the InterpolatedPath path->times.push_back(0); if (times[start] == startTime) { path->points.push_back(points[start]); path->vels.push_back(vels[start]); } else { float deltaT = (times[start + 1] - times[start]); float constant = (times[start + 1] - startTime) / deltaT; Point startPos = points[start + 1] * (1 - constant) + points[start] * (constant); Point vi = vels[start + 1] * (1 - constant) + vels[start] * (constant); path->points.push_back(startPos); path->vels.push_back(vi); } //Find the last point in the InterpolatedPath Point vf; Point endPos; size_t end; if (endTime >= getDuration()) { end = size() - 1; vf = vels[end]; endPos = points[end]; } else { end = start + 1; while (times[end] < endTime) { end++; } float deltaT = (times[end] - times[end - 1]); float constant = (times[end] - endTime) / deltaT; //endTime = times[end]; vf = vels[end] * (1 - constant) + vels[end - 1] * (constant); endPos = points[end] * (1 - constant) + points[end - 1] * (constant); } //Add all the points in the middle size_t i = start + 1; while (i < end) { path->points.push_back(points[i]); path->vels.push_back(vels[i]); path->times.push_back(times[i] - startTime); i++; } //Add the last point path->points.push_back(endPos); path->vels.push_back(vf); path->times.push_back(endTime - startTime); return unique_ptr<Path>(path); } unique_ptr<Path> InterpolatedPath::clone() const { return unique_ptr<Path>(new InterpolatedPath(*this)); } } <|endoftext|>
<commit_before>// Copyright (c) 2006, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "common/linux/guid_creator.h" #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <unistd.h> // // GUIDGenerator // // This class is used to generate random GUID. // Currently use random number to generate a GUID since Linux has // no native GUID generator. This should be OK since we don't expect // crash to happen very offen. // class GUIDGenerator { public: GUIDGenerator() { srandom(time(NULL)); } static u_int32_t BytesToUInt32(const u_int8_t bytes[]) { return ((u_int32_t) bytes[0] | ((u_int32_t) bytes[1] << 8) | ((u_int32_t) bytes[2] << 16) | ((u_int32_t) bytes[3] << 24)); } static void UInt32ToBytes(u_int8_t bytes[], u_int32_t n) { bytes[0] = n & 0xff; bytes[1] = (n >> 8) & 0xff; bytes[2] = (n >> 16) & 0xff; bytes[3] = (n >> 24) & 0xff; } bool CreateGUID(GUID *guid) const { guid->data1 = random(); guid->data2 = (u_int16_t)(random()); guid->data3 = (u_int16_t)(random()); UInt32ToBytes(&guid->data4[0], random()); UInt32ToBytes(&guid->data4[4], random()); return true; } }; // Guid generator. const GUIDGenerator kGuidGenerator; bool CreateGUID(GUID *guid) { return kGuidGenerator.CreateGUID(guid); } // Parse guid to string. bool GUIDToString(const GUID *guid, char *buf, int buf_len) { // Should allow more space the the max length of GUID. assert(buf_len > kGUIDStringLength); int num = snprintf(buf, buf_len, kGUIDFormatString, guid->data1, guid->data2, guid->data3, GUIDGenerator::BytesToUInt32(&(guid->data4[0])), GUIDGenerator::BytesToUInt32(&(guid->data4[4]))); if (num != kGUIDStringLength) return false; buf[num] = '\0'; return true; } <commit_msg> Remove static initializer in linux/guid_creator.cc.<commit_after>// Copyright (c) 2006, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "common/linux/guid_creator.h" #include <assert.h> #include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <unistd.h> // // GUIDGenerator // // This class is used to generate random GUID. // Currently use random number to generate a GUID since Linux has // no native GUID generator. This should be OK since we don't expect // crash to happen very offen. // class GUIDGenerator { public: static u_int32_t BytesToUInt32(const u_int8_t bytes[]) { return ((u_int32_t) bytes[0] | ((u_int32_t) bytes[1] << 8) | ((u_int32_t) bytes[2] << 16) | ((u_int32_t) bytes[3] << 24)); } static void UInt32ToBytes(u_int8_t bytes[], u_int32_t n) { bytes[0] = n & 0xff; bytes[1] = (n >> 8) & 0xff; bytes[2] = (n >> 16) & 0xff; bytes[3] = (n >> 24) & 0xff; } static bool CreateGUID(GUID *guid) { InitOnce(); guid->data1 = random(); guid->data2 = (u_int16_t)(random()); guid->data3 = (u_int16_t)(random()); UInt32ToBytes(&guid->data4[0], random()); UInt32ToBytes(&guid->data4[4], random()); return true; } private: static void InitOnce() { pthread_once(&once_control, &InitOnceImpl); } static void InitOnceImpl() { srandom(time(NULL)); } static pthread_once_t once_control; }; pthread_once_t GUIDGenerator::once_control = PTHREAD_ONCE_INIT; bool CreateGUID(GUID *guid) { return GUIDGenerator::CreateGUID(guid); } // Parse guid to string. bool GUIDToString(const GUID *guid, char *buf, int buf_len) { // Should allow more space the the max length of GUID. assert(buf_len > kGUIDStringLength); int num = snprintf(buf, buf_len, kGUIDFormatString, guid->data1, guid->data2, guid->data3, GUIDGenerator::BytesToUInt32(&(guid->data4[0])), GUIDGenerator::BytesToUInt32(&(guid->data4[4]))); if (num != kGUIDStringLength) return false; buf[num] = '\0'; return true; } <|endoftext|>
<commit_before>/* bzflag * Copyright (c) 1993 - 2005 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #include <string> #include <string.h> #include "common.h" #include "bzfgl.h" #include "TextureManager.h" #include "TextureFont.h" #include "bzfio.h" #include "OpenGLGState.h" TextureFont::TextureFont() { for (int i = 0; i < MAX_TEXTURE_FONT_CHARS; i++) { listIDs[i] = INVALID_GL_LIST_ID; fontMetrics[i].charWidth = -1; } size = -1; textureID = -1; textureXSize = -1; textureYSize = -1; textureZStep = -1; numberOfCharacters = -1; } TextureFont::~TextureFont() { for (int i = 0; i < MAX_TEXTURE_FONT_CHARS; i++) { if (listIDs[i] != INVALID_GL_LIST_ID) { glDeleteLists(listIDs[i], 1); listIDs[i] = INVALID_GL_LIST_ID; } } } int TextureFont::getSize() { return size; } const char* TextureFont::getFaceName() { return faceName.c_str(); } // keep a line counter for debugging static int line; /* read values in Key: Value form from font metrics (.fmt) files */ bool readKeyInt(OSFile &file, std::string expectedLeft, int &retval, bool newfile=false) { if (newfile) line = 0; const int expsize = int(expectedLeft.size()); std::string tmpBuf; // allow for blank lines with native or foreign linebreaks, comment lines while (tmpBuf.size() == 0 || tmpBuf[0] == '#' || tmpBuf[0] == 10 || tmpBuf[0] == 13) { tmpBuf = file.readLine(); line++; } if (tmpBuf.compare(0, expsize, expectedLeft) == 0 && tmpBuf[expsize]==':') { retval = atoi(tmpBuf.c_str()+expsize+1); return true; } else { DEBUG2("Unexpected line in font metrics file %s, line %d (expected %s)\n", file.getFileName().c_str(), line, expectedLeft.c_str()); return false; } } // read Char: "x" entry bool readLetter(OSFile &file, char expected) { const std::string expectedLeft = "Char:"; const int expsize = int(expectedLeft.size()); std::string tmpBuf; // allow for blank lines with native or foreign linebreaks, comment lines while (tmpBuf.size() == 0 || tmpBuf[0] == '#' || tmpBuf[0] == 10 || tmpBuf[0] == 13) { tmpBuf = file.readLine(); // keep a line counter line++; } if (tmpBuf.compare(0, expsize, expectedLeft) == 0) { if (int(tmpBuf.size()) >= expsize+4 && tmpBuf[expsize+1]=='"' && tmpBuf[expsize+3]=='"' && tmpBuf[expsize+2]==expected) { return true; } else { DEBUG2("Unexpected character: %s, in font metrics file %s, line %d (expected \"%c\").\n", tmpBuf.c_str()+expsize, file.getFileName().c_str(), line, expected); return false; } } else { DEBUG2("Unexpected line in font metrics file %s, line %d (expected %s)\n", file.getFileName().c_str(), line, expectedLeft.c_str()); return false; } } bool TextureFont::load(OSFile &file) { std::string extension = file.getExtension(); if (extension=="") return false; texture = file.getFileName(); std::string::size_type underscore = texture.rfind('_'); if (underscore == std::string::npos) { DEBUG1("Unexpected font file name: %s, no _size found\n", file.getStdName().c_str()); return false; } faceName = texture.substr(0, underscore); size = atoi(texture.c_str() + underscore + 1); if (!file.open("rb")) return false; if (!readKeyInt(file, "NumChars", numberOfCharacters, true)) return false; if (!readKeyInt(file, "TextureWidth", textureXSize)) return false; if (!readKeyInt(file, "TextureHeight", textureYSize)) return false; if (!readKeyInt(file, "TextZStep", textureZStep)) return false; // clamp the maximum char count if (numberOfCharacters > MAX_TEXTURE_FONT_CHARS) { DEBUG1("Too many characters (%i) in %s.\n", numberOfCharacters, file.getFileName().c_str()); numberOfCharacters = MAX_TEXTURE_FONT_CHARS; } int i; for (i = 0; i < numberOfCharacters; i++) { // check character if (!readLetter(file, i + 32)) return false; // read metrics if (!readKeyInt(file, "InitialDist", fontMetrics[i].initialDist)) return false; if (!readKeyInt(file, "Width", fontMetrics[i].charWidth)) return false; if (!readKeyInt(file, "Whitespace", fontMetrics[i].whiteSpaceDist)) return false; if (!readKeyInt(file, "StartX", fontMetrics[i].startX)) return false; if (!readKeyInt(file, "EndX", fontMetrics[i].endX)) return false; if (!readKeyInt(file, "StartY", fontMetrics[i].startY)) return false; if (!readKeyInt(file, "EndY", fontMetrics[i].endY)) return false; } file.close(); return (numberOfCharacters > 0); } void TextureFont::build(void) { preLoadLists(); } void TextureFont::preLoadLists(void) { if (texture.size() < 1) { DEBUG2("Font %s does not have an associated texture name, not loading\n", texture.c_str()); return; } // load up the texture TextureManager &tm = TextureManager::instance(); std::string textureAndDir = "fonts/" + texture; textureID = tm.getTextureID(textureAndDir.c_str()); DEBUG4("Font %s (face %s) has texture ID %d\n", texture.c_str(), faceName.c_str(), textureID); if (textureID == -1) { DEBUG2("Font texture %s has invalid ID\n", texture.c_str()); return; } for (int i = 0; i < numberOfCharacters; i++) { if (listIDs[i] != INVALID_GL_LIST_ID) { glDeleteLists(listIDs[i], 1); listIDs[i] = INVALID_GL_LIST_ID; // make it a habit } listIDs[i] = glGenLists(1); glNewList(listIDs[i], GL_COMPILE); { glTranslatef((float)fontMetrics[i].initialDist, 0, 0); float fFontY = (float)fontMetrics[i].endY - fontMetrics[i].startY; float fFontX = (float)fontMetrics[i].endX - fontMetrics[i].startX; glBegin(GL_QUADS); glNormal3f(0.0f, 0.0f, 1.0f); glTexCoord2f((float)fontMetrics[i].startX / (float)textureXSize, 1.0f - (float)fontMetrics[i].startY / (float)textureYSize); glVertex3f(0.0f, fFontY, 0.0f); glTexCoord2f((float)fontMetrics[i].startX / (float)textureXSize, 1.0f - (float)fontMetrics[i].endY / (float)textureYSize); glVertex3f(0.0f, 0.0f, 0.0f); glTexCoord2f((float)fontMetrics[i].endX / (float)textureXSize, 1.0f - (float)fontMetrics[i].endY / (float)textureYSize); glVertex3f(fFontX, 0.0f, 0.0f); glTexCoord2f((float)fontMetrics[i].endX / (float)textureXSize, 1.0f - (float)fontMetrics[i].startY / (float)textureYSize); glVertex3f(fFontX, fFontY, 0.0f); glEnd(); glTranslatef(fFontX, 0.0f, 0.0f); } glEndList(); } // create GState OpenGLGStateBuilder builder(gstate); builder.setTexture(textureID); builder.setBlending(); builder.setAlphaFunc(); builder.enableTextureReplace(false); gstate = builder.getState(); } float TextureFont::getStrLength(float scale, const char *str, int len) { int charToUse = 0; int lastCharacter = 0; float totalLen = 0; for (int i = 0; i < len; i++) { lastCharacter = charToUse; if (str[i] < 32) charToUse = 32; else if (str[i] > numberOfCharacters + 32) charToUse = 32; else charToUse = str[i]; charToUse -= 32; if (charToUse == 0) { totalLen += fontMetrics[charToUse].initialDist + fontMetrics[charToUse].charWidth + fontMetrics[charToUse].whiteSpaceDist; } else { totalLen += fontMetrics[charToUse].endX - fontMetrics[charToUse].startX + fontMetrics[charToUse].initialDist; } } return totalLen * scale; } void TextureFont::free(void) { textureID = -1; } void TextureFont::drawString(float scale, GLfloat color[3], const char *str, int len) { if (!str) return; if (textureID == -1) preLoadLists(); if (textureID == -1) return; gstate.setState(); TextureManager &tm = TextureManager::instance(); if (!tm.bind(textureID)) return; if (color[0] >= 0) glColor3fv(color); glPushMatrix(); glScalef(scale, scale, 1); glPushMatrix(); int charToUse = 0; int lastCharacter = 0; for (int i = 0; i < len; i++) { lastCharacter = charToUse; const char space = ' '; // decimal 32 if (str[i] < space) { charToUse = space; } else if (str[i] > (numberOfCharacters + space)) { charToUse = space; } else { charToUse = str[i]; } charToUse -= space; if (charToUse == 0) { glTranslatef((float)fontMetrics[charToUse].initialDist + (float)fontMetrics[charToUse].charWidth + (float)fontMetrics[charToUse].whiteSpaceDist, 0.0f, 0.0f); } else { glCallList(listIDs[charToUse]); } } glPopMatrix(); if (color[0] >= 0) glColor4f(1, 1, 1, 1); glPopMatrix(); } // Local Variables: *** // mode: C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <commit_msg>g++ 2.95 has no substring compare function, so use less efficient way that should work for everybody<commit_after>/* bzflag * Copyright (c) 1993 - 2005 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #include <string> #include <string.h> #include "common.h" #include "bzfgl.h" #include "TextureManager.h" #include "TextureFont.h" #include "bzfio.h" #include "OpenGLGState.h" TextureFont::TextureFont() { for (int i = 0; i < MAX_TEXTURE_FONT_CHARS; i++) { listIDs[i] = INVALID_GL_LIST_ID; fontMetrics[i].charWidth = -1; } size = -1; textureID = -1; textureXSize = -1; textureYSize = -1; textureZStep = -1; numberOfCharacters = -1; } TextureFont::~TextureFont() { for (int i = 0; i < MAX_TEXTURE_FONT_CHARS; i++) { if (listIDs[i] != INVALID_GL_LIST_ID) { glDeleteLists(listIDs[i], 1); listIDs[i] = INVALID_GL_LIST_ID; } } } int TextureFont::getSize() { return size; } const char* TextureFont::getFaceName() { return faceName.c_str(); } // keep a line counter for debugging static int line; /* read values in Key: Value form from font metrics (.fmt) files */ bool readKeyInt(OSFile &file, std::string expectedLeft, int &retval, bool newfile=false) { if (newfile) line = 0; const int expsize = int(expectedLeft.size()); std::string tmpBuf; // allow for blank lines with native or foreign linebreaks, comment lines while (tmpBuf.size() == 0 || tmpBuf[0] == '#' || tmpBuf[0] == 10 || tmpBuf[0] == 13) { tmpBuf = file.readLine(); line++; } if (tmpBuf.substr(0, expsize) == expectedLeft && tmpBuf[expsize]==':') { retval = atoi(tmpBuf.c_str()+expsize+1); return true; } else { DEBUG2("Unexpected line in font metrics file %s, line %d (expected %s)\n", file.getFileName().c_str(), line, expectedLeft.c_str()); return false; } } // read Char: "x" entry bool readLetter(OSFile &file, char expected) { const std::string expectedLeft = "Char:"; const int expsize = int(expectedLeft.size()); std::string tmpBuf; // allow for blank lines with native or foreign linebreaks, comment lines while (tmpBuf.size() == 0 || tmpBuf[0] == '#' || tmpBuf[0] == 10 || tmpBuf[0] == 13) { tmpBuf = file.readLine(); // keep a line counter line++; } if (tmpBuf.substr(0, expsize) == expectedLeft) { if (int(tmpBuf.size()) >= expsize+4 && tmpBuf[expsize+1]=='"' && tmpBuf[expsize+3]=='"' && tmpBuf[expsize+2]==expected) { return true; } else { DEBUG2("Unexpected character: %s, in font metrics file %s, line %d (expected \"%c\").\n", tmpBuf.c_str()+expsize, file.getFileName().c_str(), line, expected); return false; } } else { DEBUG2("Unexpected line in font metrics file %s, line %d (expected %s)\n", file.getFileName().c_str(), line, expectedLeft.c_str()); return false; } } bool TextureFont::load(OSFile &file) { std::string extension = file.getExtension(); if (extension=="") return false; texture = file.getFileName(); std::string::size_type underscore = texture.rfind('_'); if (underscore == std::string::npos) { DEBUG1("Unexpected font file name: %s, no _size found\n", file.getStdName().c_str()); return false; } faceName = texture.substr(0, underscore); size = atoi(texture.c_str() + underscore + 1); if (!file.open("rb")) return false; if (!readKeyInt(file, "NumChars", numberOfCharacters, true)) return false; if (!readKeyInt(file, "TextureWidth", textureXSize)) return false; if (!readKeyInt(file, "TextureHeight", textureYSize)) return false; if (!readKeyInt(file, "TextZStep", textureZStep)) return false; // clamp the maximum char count if (numberOfCharacters > MAX_TEXTURE_FONT_CHARS) { DEBUG1("Too many characters (%i) in %s.\n", numberOfCharacters, file.getFileName().c_str()); numberOfCharacters = MAX_TEXTURE_FONT_CHARS; } int i; for (i = 0; i < numberOfCharacters; i++) { // check character if (!readLetter(file, i + 32)) return false; // read metrics if (!readKeyInt(file, "InitialDist", fontMetrics[i].initialDist)) return false; if (!readKeyInt(file, "Width", fontMetrics[i].charWidth)) return false; if (!readKeyInt(file, "Whitespace", fontMetrics[i].whiteSpaceDist)) return false; if (!readKeyInt(file, "StartX", fontMetrics[i].startX)) return false; if (!readKeyInt(file, "EndX", fontMetrics[i].endX)) return false; if (!readKeyInt(file, "StartY", fontMetrics[i].startY)) return false; if (!readKeyInt(file, "EndY", fontMetrics[i].endY)) return false; } file.close(); return (numberOfCharacters > 0); } void TextureFont::build(void) { preLoadLists(); } void TextureFont::preLoadLists(void) { if (texture.size() < 1) { DEBUG2("Font %s does not have an associated texture name, not loading\n", texture.c_str()); return; } // load up the texture TextureManager &tm = TextureManager::instance(); std::string textureAndDir = "fonts/" + texture; textureID = tm.getTextureID(textureAndDir.c_str()); DEBUG4("Font %s (face %s) has texture ID %d\n", texture.c_str(), faceName.c_str(), textureID); if (textureID == -1) { DEBUG2("Font texture %s has invalid ID\n", texture.c_str()); return; } for (int i = 0; i < numberOfCharacters; i++) { if (listIDs[i] != INVALID_GL_LIST_ID) { glDeleteLists(listIDs[i], 1); listIDs[i] = INVALID_GL_LIST_ID; // make it a habit } listIDs[i] = glGenLists(1); glNewList(listIDs[i], GL_COMPILE); { glTranslatef((float)fontMetrics[i].initialDist, 0, 0); float fFontY = (float)fontMetrics[i].endY - fontMetrics[i].startY; float fFontX = (float)fontMetrics[i].endX - fontMetrics[i].startX; glBegin(GL_QUADS); glNormal3f(0.0f, 0.0f, 1.0f); glTexCoord2f((float)fontMetrics[i].startX / (float)textureXSize, 1.0f - (float)fontMetrics[i].startY / (float)textureYSize); glVertex3f(0.0f, fFontY, 0.0f); glTexCoord2f((float)fontMetrics[i].startX / (float)textureXSize, 1.0f - (float)fontMetrics[i].endY / (float)textureYSize); glVertex3f(0.0f, 0.0f, 0.0f); glTexCoord2f((float)fontMetrics[i].endX / (float)textureXSize, 1.0f - (float)fontMetrics[i].endY / (float)textureYSize); glVertex3f(fFontX, 0.0f, 0.0f); glTexCoord2f((float)fontMetrics[i].endX / (float)textureXSize, 1.0f - (float)fontMetrics[i].startY / (float)textureYSize); glVertex3f(fFontX, fFontY, 0.0f); glEnd(); glTranslatef(fFontX, 0.0f, 0.0f); } glEndList(); } // create GState OpenGLGStateBuilder builder(gstate); builder.setTexture(textureID); builder.setBlending(); builder.setAlphaFunc(); builder.enableTextureReplace(false); gstate = builder.getState(); } float TextureFont::getStrLength(float scale, const char *str, int len) { int charToUse = 0; int lastCharacter = 0; float totalLen = 0; for (int i = 0; i < len; i++) { lastCharacter = charToUse; if (str[i] < 32) charToUse = 32; else if (str[i] > numberOfCharacters + 32) charToUse = 32; else charToUse = str[i]; charToUse -= 32; if (charToUse == 0) { totalLen += fontMetrics[charToUse].initialDist + fontMetrics[charToUse].charWidth + fontMetrics[charToUse].whiteSpaceDist; } else { totalLen += fontMetrics[charToUse].endX - fontMetrics[charToUse].startX + fontMetrics[charToUse].initialDist; } } return totalLen * scale; } void TextureFont::free(void) { textureID = -1; } void TextureFont::drawString(float scale, GLfloat color[3], const char *str, int len) { if (!str) return; if (textureID == -1) preLoadLists(); if (textureID == -1) return; gstate.setState(); TextureManager &tm = TextureManager::instance(); if (!tm.bind(textureID)) return; if (color[0] >= 0) glColor3fv(color); glPushMatrix(); glScalef(scale, scale, 1); glPushMatrix(); int charToUse = 0; int lastCharacter = 0; for (int i = 0; i < len; i++) { lastCharacter = charToUse; const char space = ' '; // decimal 32 if (str[i] < space) { charToUse = space; } else if (str[i] > (numberOfCharacters + space)) { charToUse = space; } else { charToUse = str[i]; } charToUse -= space; if (charToUse == 0) { glTranslatef((float)fontMetrics[charToUse].initialDist + (float)fontMetrics[charToUse].charWidth + (float)fontMetrics[charToUse].whiteSpaceDist, 0.0f, 0.0f); } else { glCallList(listIDs[charToUse]); } } glPopMatrix(); if (color[0] >= 0) glColor4f(1, 1, 1, 1); glPopMatrix(); } // Local Variables: *** // mode: C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <|endoftext|>
<commit_before>/* * #%L * %% * Copyright (C) 2011 - 2016 BMW Car IT GmbH * %% * 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. * #L% */ #include <cassert> #include <cstdint> #include <cstdlib> #include <algorithm> #include <boost/lexical_cast.hpp> #include "cluster-controller/http-communication-manager/LongPollingMessageReceiver.h" #include "cluster-controller/httpnetworking/HttpNetworking.h" #include "joynr/Util.h" #include "joynr/DispatcherUtils.h" #include "cluster-controller/httpnetworking/HttpResult.h" #include "joynr/Future.h" #include "joynr/JoynrMessage.h" #include "joynr/system/RoutingTypes/ChannelAddress.h" #include "joynr/MessageRouter.h" #include "joynr/JoynrMessage.h" namespace joynr { INIT_LOGGER(LongPollingMessageReceiver); LongPollingMessageReceiver::LongPollingMessageReceiver( const BrokerUrl& brokerUrl, const std::string& channelId, const std::string& receiverId, const LongPollingMessageReceiverSettings& settings, std::shared_ptr<Semaphore> channelCreatedSemaphore, std::function<void(const std::string&)> onTextMessageReceived) : Thread("LongPollRecv"), brokerUrl(brokerUrl), channelId(channelId), receiverId(receiverId), settings(settings), interrupted(false), interruptedMutex(), interruptedWait(), channelCreatedSemaphore(channelCreatedSemaphore), onTextMessageReceived(onTextMessageReceived) { } LongPollingMessageReceiver::~LongPollingMessageReceiver() { stop(); } void LongPollingMessageReceiver::interrupt() { interrupted = true; interruptedWait.notify_all(); } bool LongPollingMessageReceiver::isInterrupted() { return interrupted; } void LongPollingMessageReceiver::stop() { interrupt(); Thread::stop(); } void LongPollingMessageReceiver::run() { checkServerTime(); std::string createChannelUrl = brokerUrl.getCreateChannelUrl(channelId).toString(); JOYNR_LOG_INFO(logger, "Running lpmr with channelId {}", channelId); std::shared_ptr<IHttpPostBuilder> createChannelRequestBuilder( HttpNetworking::getInstance()->createHttpPostBuilder(createChannelUrl)); std::shared_ptr<HttpRequest> createChannelRequest( createChannelRequestBuilder->addHeader("X-Atmosphere-tracking-id", receiverId) ->withContentType("application/json") ->withTimeout(settings.brokerTimeout) ->build()); std::string channelUrl; while (channelUrl.empty() && !isInterrupted()) { JOYNR_LOG_DEBUG(logger, "sending create channel request"); HttpResult createChannelResult = createChannelRequest->execute(); if (createChannelResult.getStatusCode() == 201) { const std::unordered_multimap<std::string, std::string>& headers = createChannelResult.getHeaders(); auto it = headers.find("Location"); channelUrl = it->second; JOYNR_LOG_INFO(logger, "channel creation successfull; channel url: {}", channelUrl); channelCreatedSemaphore->notify(); } else { JOYNR_LOG_INFO(logger, "channel creation failed); status code: {}", createChannelResult.getStatusCode()); std::unique_lock<std::mutex> lock(interruptedMutex); interruptedWait.wait_for(lock, settings.createChannelRetryInterval); } } // TODO: The received URL must be forwarded in such a way that ChannelAddress objects use it. while (!isInterrupted()) { std::shared_ptr<IHttpGetBuilder> longPollRequestBuilder( HttpNetworking::getInstance()->createHttpGetBuilder(channelUrl)); std::shared_ptr<HttpRequest> longPollRequest( longPollRequestBuilder->acceptGzip() ->addHeader("Accept", "application/json") ->addHeader("X-Atmosphere-tracking-id", receiverId) ->withTimeout(settings.longPollTimeout) ->build()); JOYNR_LOG_DEBUG(logger, "sending long polling request; url: {}", channelUrl); HttpResult longPollingResult = longPollRequest->execute(); if (!isInterrupted()) { // TODO: remove HttpErrorCodes and use constants. // there is a bug in atmosphere, which currently gives back 503 instead of 200 as a // result to longpolling. // Accepting 503 is a temporary workaround for this bug. As soon as atmosphere is fixed, // this should be removed // 200 does nott refect the state of the message body! It could be empty. if (longPollingResult.getStatusCode() == 200 || longPollingResult.getStatusCode() == 503) { util::logSerializedMessage( logger, "long polling successful; contents: ", longPollingResult.getBody()); processReceivedInput(longPollingResult.getBody()); // Atmosphere currently cannot return 204 when a long poll times out, so this code // is currently never executed (2.2.2012) } else if (longPollingResult.getStatusCode() == 204) { JOYNR_LOG_DEBUG(logger, "long polling successfull);full; no data"); } else { std::string body("NULL"); if (!longPollingResult.getBody().empty()) { body = longPollingResult.getBody(); } JOYNR_LOG_ERROR(logger, "long polling failed; error message: {}; contents: {}", longPollingResult.getErrorMessage(), body); std::unique_lock<std::mutex> lock(interruptedMutex); interruptedWait.wait_for(lock, settings.createChannelRetryInterval); } } } } void LongPollingMessageReceiver::processReceivedInput(const std::string& receivedInput) { std::vector<std::string> jsonObjects = util::splitIntoJsonObjects(receivedInput); for (std::size_t i = 0; i < jsonObjects.size(); i++) { processReceivedJsonObjects(jsonObjects.at(i)); } } void LongPollingMessageReceiver::processReceivedJsonObjects(const std::string& jsonObject) { if (onTextMessageReceived) { onTextMessageReceived(jsonObject); } else { JOYNR_LOG_ERROR( logger, "Discarding received message, since onTextMessageReceived callback is empty."); } } void LongPollingMessageReceiver::checkServerTime() { std::string timeCheckUrl = brokerUrl.getTimeCheckUrl().toString(); IHttpGetBuilder* timeCheckRequestBuilder = HttpNetworking::getInstance()->createHttpGetBuilder(timeCheckUrl); std::shared_ptr<HttpRequest> timeCheckRequest( timeCheckRequestBuilder->addHeader("Accept", "text/plain") ->withTimeout(settings.brokerTimeout) ->build()); delete timeCheckRequestBuilder; timeCheckRequestBuilder = nullptr; JOYNR_LOG_DEBUG(logger, "CheckServerTime: sending request to Bounce Proxy ({})", timeCheckUrl); std::chrono::system_clock::time_point localTimeBeforeRequest = std::chrono::system_clock::now(); HttpResult timeCheckResult = timeCheckRequest->execute(); std::chrono::system_clock::time_point localTimeAfterRequest = std::chrono::system_clock::now(); std::uint64_t localTime = (util::toMilliseconds(localTimeBeforeRequest) + util::toMilliseconds(localTimeAfterRequest)) / 2; if (timeCheckResult.getStatusCode() != 200) { JOYNR_LOG_ERROR(logger, "CheckServerTime: Bounce Proxy not reached [statusCode={}] [body={}]", timeCheckResult.getStatusCode(), timeCheckResult.getBody()); } else { JOYNR_LOG_TRACE(logger, "CheckServerTime: reply received [statusCode={}] [body={}]", timeCheckResult.getStatusCode(), timeCheckResult.getBody()); std::uint64_t serverTime = boost::lexical_cast<std::uint64_t>(timeCheckResult.getBody()); auto minMaxTime = std::minmax(serverTime, localTime); std::uint64_t diff = minMaxTime.second - minMaxTime.first; JOYNR_LOG_INFO(logger, "CheckServerTime [server time={}] [local time={}] [diff={} ms]", util::toDateString(JoynrTimePoint(std::chrono::milliseconds(serverTime))), util::toDateString(JoynrTimePoint(std::chrono::milliseconds(localTime))), diff); if (diff > 500) { JOYNR_LOG_ERROR(logger, "CheckServerTime: time difference to server is {} ms", diff); } } } } // namespace joynr <commit_msg>[C++] added missing mutex lock in LPMR<commit_after>/* * #%L * %% * Copyright (C) 2011 - 2016 BMW Car IT GmbH * %% * 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. * #L% */ #include <cassert> #include <cstdint> #include <cstdlib> #include <algorithm> #include <boost/lexical_cast.hpp> #include "cluster-controller/http-communication-manager/LongPollingMessageReceiver.h" #include "cluster-controller/httpnetworking/HttpNetworking.h" #include "joynr/Util.h" #include "joynr/DispatcherUtils.h" #include "cluster-controller/httpnetworking/HttpResult.h" #include "joynr/Future.h" #include "joynr/JoynrMessage.h" #include "joynr/system/RoutingTypes/ChannelAddress.h" #include "joynr/MessageRouter.h" #include "joynr/JoynrMessage.h" namespace joynr { INIT_LOGGER(LongPollingMessageReceiver); LongPollingMessageReceiver::LongPollingMessageReceiver( const BrokerUrl& brokerUrl, const std::string& channelId, const std::string& receiverId, const LongPollingMessageReceiverSettings& settings, std::shared_ptr<Semaphore> channelCreatedSemaphore, std::function<void(const std::string&)> onTextMessageReceived) : Thread("LongPollRecv"), brokerUrl(brokerUrl), channelId(channelId), receiverId(receiverId), settings(settings), interrupted(false), interruptedMutex(), interruptedWait(), channelCreatedSemaphore(channelCreatedSemaphore), onTextMessageReceived(onTextMessageReceived) { } LongPollingMessageReceiver::~LongPollingMessageReceiver() { stop(); } void LongPollingMessageReceiver::interrupt() { std::unique_lock<std::mutex> lock(interruptedMutex); interrupted = true; interruptedWait.notify_all(); } bool LongPollingMessageReceiver::isInterrupted() { return interrupted; } void LongPollingMessageReceiver::stop() { interrupt(); Thread::stop(); } void LongPollingMessageReceiver::run() { checkServerTime(); std::string createChannelUrl = brokerUrl.getCreateChannelUrl(channelId).toString(); JOYNR_LOG_INFO(logger, "Running lpmr with channelId {}", channelId); std::shared_ptr<IHttpPostBuilder> createChannelRequestBuilder( HttpNetworking::getInstance()->createHttpPostBuilder(createChannelUrl)); std::shared_ptr<HttpRequest> createChannelRequest( createChannelRequestBuilder->addHeader("X-Atmosphere-tracking-id", receiverId) ->withContentType("application/json") ->withTimeout(settings.brokerTimeout) ->build()); std::string channelUrl; while (channelUrl.empty() && !isInterrupted()) { JOYNR_LOG_DEBUG(logger, "sending create channel request"); HttpResult createChannelResult = createChannelRequest->execute(); if (createChannelResult.getStatusCode() == 201) { const std::unordered_multimap<std::string, std::string>& headers = createChannelResult.getHeaders(); auto it = headers.find("Location"); channelUrl = it->second; JOYNR_LOG_INFO(logger, "channel creation successfull; channel url: {}", channelUrl); channelCreatedSemaphore->notify(); } else { JOYNR_LOG_INFO(logger, "channel creation failed); status code: {}", createChannelResult.getStatusCode()); std::unique_lock<std::mutex> lock(interruptedMutex); interruptedWait.wait_for(lock, settings.createChannelRetryInterval); } } // TODO: The received URL must be forwarded in such a way that ChannelAddress objects use it. while (!isInterrupted()) { std::shared_ptr<IHttpGetBuilder> longPollRequestBuilder( HttpNetworking::getInstance()->createHttpGetBuilder(channelUrl)); std::shared_ptr<HttpRequest> longPollRequest( longPollRequestBuilder->acceptGzip() ->addHeader("Accept", "application/json") ->addHeader("X-Atmosphere-tracking-id", receiverId) ->withTimeout(settings.longPollTimeout) ->build()); JOYNR_LOG_DEBUG(logger, "sending long polling request; url: {}", channelUrl); HttpResult longPollingResult = longPollRequest->execute(); if (!isInterrupted()) { // TODO: remove HttpErrorCodes and use constants. // there is a bug in atmosphere, which currently gives back 503 instead of 200 as a // result to longpolling. // Accepting 503 is a temporary workaround for this bug. As soon as atmosphere is fixed, // this should be removed // 200 does nott refect the state of the message body! It could be empty. if (longPollingResult.getStatusCode() == 200 || longPollingResult.getStatusCode() == 503) { util::logSerializedMessage( logger, "long polling successful; contents: ", longPollingResult.getBody()); processReceivedInput(longPollingResult.getBody()); // Atmosphere currently cannot return 204 when a long poll times out, so this code // is currently never executed (2.2.2012) } else if (longPollingResult.getStatusCode() == 204) { JOYNR_LOG_DEBUG(logger, "long polling successfull);full; no data"); } else { std::string body("NULL"); if (!longPollingResult.getBody().empty()) { body = longPollingResult.getBody(); } JOYNR_LOG_ERROR(logger, "long polling failed; error message: {}; contents: {}", longPollingResult.getErrorMessage(), body); std::unique_lock<std::mutex> lock(interruptedMutex); interruptedWait.wait_for(lock, settings.createChannelRetryInterval); } } } } void LongPollingMessageReceiver::processReceivedInput(const std::string& receivedInput) { std::vector<std::string> jsonObjects = util::splitIntoJsonObjects(receivedInput); for (std::size_t i = 0; i < jsonObjects.size(); i++) { processReceivedJsonObjects(jsonObjects.at(i)); } } void LongPollingMessageReceiver::processReceivedJsonObjects(const std::string& jsonObject) { if (onTextMessageReceived) { onTextMessageReceived(jsonObject); } else { JOYNR_LOG_ERROR( logger, "Discarding received message, since onTextMessageReceived callback is empty."); } } void LongPollingMessageReceiver::checkServerTime() { std::string timeCheckUrl = brokerUrl.getTimeCheckUrl().toString(); IHttpGetBuilder* timeCheckRequestBuilder = HttpNetworking::getInstance()->createHttpGetBuilder(timeCheckUrl); std::shared_ptr<HttpRequest> timeCheckRequest( timeCheckRequestBuilder->addHeader("Accept", "text/plain") ->withTimeout(settings.brokerTimeout) ->build()); delete timeCheckRequestBuilder; timeCheckRequestBuilder = nullptr; JOYNR_LOG_DEBUG(logger, "CheckServerTime: sending request to Bounce Proxy ({})", timeCheckUrl); std::chrono::system_clock::time_point localTimeBeforeRequest = std::chrono::system_clock::now(); HttpResult timeCheckResult = timeCheckRequest->execute(); std::chrono::system_clock::time_point localTimeAfterRequest = std::chrono::system_clock::now(); std::uint64_t localTime = (util::toMilliseconds(localTimeBeforeRequest) + util::toMilliseconds(localTimeAfterRequest)) / 2; if (timeCheckResult.getStatusCode() != 200) { JOYNR_LOG_ERROR(logger, "CheckServerTime: Bounce Proxy not reached [statusCode={}] [body={}]", timeCheckResult.getStatusCode(), timeCheckResult.getBody()); } else { JOYNR_LOG_TRACE(logger, "CheckServerTime: reply received [statusCode={}] [body={}]", timeCheckResult.getStatusCode(), timeCheckResult.getBody()); std::uint64_t serverTime = boost::lexical_cast<std::uint64_t>(timeCheckResult.getBody()); auto minMaxTime = std::minmax(serverTime, localTime); std::uint64_t diff = minMaxTime.second - minMaxTime.first; JOYNR_LOG_INFO(logger, "CheckServerTime [server time={}] [local time={}] [diff={} ms]", util::toDateString(JoynrTimePoint(std::chrono::milliseconds(serverTime))), util::toDateString(JoynrTimePoint(std::chrono::milliseconds(localTime))), diff); if (diff > 500) { JOYNR_LOG_ERROR(logger, "CheckServerTime: time difference to server is {} ms", diff); } } } } // namespace joynr <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////// // // Copyright 2016 Realm 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. // //////////////////////////////////////////////////////////////////////////// #ifndef REALM_OS_SYNC_CLIENT_HPP #define REALM_OS_SYNC_CLIENT_HPP #include <realm/sync/client.hpp> #include <thread> #if REALM_PLATFORM_APPLE #include "sync/impl/apple/network_reachability_observer.hpp" #endif namespace realm { namespace _impl { using ReconnectMode = sync::Client::ReconnectMode; struct SyncClient { sync::Client client; SyncClient(std::unique_ptr<util::Logger> logger, ReconnectMode reconnect_mode = ReconnectMode::normal, bool verify_ssl = true) : client(make_client(*logger, reconnect_mode, verify_ssl)) // Throws , m_logger(std::move(logger)) , m_thread([this] { client.run(); }) // Throws #if REALM_PLATFORM_APPLE , m_reachability_observer(none, [=](const NetworkReachabilityStatus status) { if (status != NotReachable) { cancel_reconnect_delay(); } }) { if (!m_reachability_observer.start_observing()) { m_logger->error("Failed to setup network reachability observer"); } } #else { } #endif void cancel_reconnect_delay() { // FIXME: Implement after https://github.com/realm/realm-sync/issues/794 // client.cancel_reconnect_delay(); } void stop() { client.stop(); if (m_thread.joinable()) m_thread.join(); } ~SyncClient() { stop(); } private: static sync::Client make_client(util::Logger& logger, ReconnectMode reconnect_mode, bool verify_ssl) { sync::Client::Config config; config.logger = &logger; config.reconnect_mode = std::move(reconnect_mode); config.verify_servers_ssl_certificate = verify_ssl; return sync::Client(std::move(config)); // Throws } const std::unique_ptr<util::Logger> m_logger; std::thread m_thread; #if REALM_PLATFORM_APPLE NetworkReachabilityObserver m_reachability_observer; #endif }; } } #endif // REALM_OS_SYNC_CLIENT_HPP <commit_msg>enable client.cancel_reconnect_delay()<commit_after>//////////////////////////////////////////////////////////////////////////// // // Copyright 2016 Realm 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. // //////////////////////////////////////////////////////////////////////////// #ifndef REALM_OS_SYNC_CLIENT_HPP #define REALM_OS_SYNC_CLIENT_HPP #include <realm/sync/client.hpp> #include <thread> #if REALM_PLATFORM_APPLE #include "sync/impl/apple/network_reachability_observer.hpp" #endif namespace realm { namespace _impl { using ReconnectMode = sync::Client::ReconnectMode; struct SyncClient { sync::Client client; SyncClient(std::unique_ptr<util::Logger> logger, ReconnectMode reconnect_mode = ReconnectMode::normal, bool verify_ssl = true) : client(make_client(*logger, reconnect_mode, verify_ssl)) // Throws , m_logger(std::move(logger)) , m_thread([this] { client.run(); }) // Throws #if REALM_PLATFORM_APPLE , m_reachability_observer(none, [=](const NetworkReachabilityStatus status) { if (status != NotReachable) { cancel_reconnect_delay(); } }) { if (!m_reachability_observer.start_observing()) { m_logger->error("Failed to setup network reachability observer"); } } #else { } #endif void cancel_reconnect_delay() { client.cancel_reconnect_delay(); } void stop() { client.stop(); if (m_thread.joinable()) m_thread.join(); } ~SyncClient() { stop(); } private: static sync::Client make_client(util::Logger& logger, ReconnectMode reconnect_mode, bool verify_ssl) { sync::Client::Config config; config.logger = &logger; config.reconnect_mode = std::move(reconnect_mode); config.verify_servers_ssl_certificate = verify_ssl; return sync::Client(std::move(config)); // Throws } const std::unique_ptr<util::Logger> m_logger; std::thread m_thread; #if REALM_PLATFORM_APPLE NetworkReachabilityObserver m_reachability_observer; #endif }; } } #endif // REALM_OS_SYNC_CLIENT_HPP <|endoftext|>
<commit_before>/* * Copyright 2018 Google, Inc. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders 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. * * Authors: Gabe Black */ #include "systemc/core/scheduler.hh" #include "base/fiber.hh" #include "base/logging.hh" #include "sim/eventq.hh" #include "systemc/core/kernel.hh" #include "systemc/ext/core/sc_main.hh" namespace sc_gem5 { Scheduler::Scheduler() : eq(nullptr), readyEvent(this, false, ReadyPriority), pauseEvent(this, false, PausePriority), stopEvent(this, false, StopPriority), scMain(nullptr), starvationEvent(this, false, StarvationPriority), _started(false), _paused(false), _stopped(false), maxTickEvent(this, false, MaxTickPriority), _numCycles(0), _current(nullptr), initDone(false), runOnce(false) {} Scheduler::~Scheduler() { // Clear out everything that belongs to us to make sure nobody tries to // clear themselves out after the scheduler goes away. // Delta notifications. for (auto &e: deltas) e->deschedule(); // Timed notifications. for (auto &ts: timeSlots) { for (auto &e: ts.second->events) e->deschedule(); delete ts.second; ts.second = nullptr; } // gem5 events. if (readyEvent.scheduled()) eq->deschedule(&readyEvent); if (pauseEvent.scheduled()) eq->deschedule(&pauseEvent); if (stopEvent.scheduled()) eq->deschedule(&stopEvent); if (starvationEvent.scheduled()) eq->deschedule(&starvationEvent); if (maxTickEvent.scheduled()) eq->deschedule(&maxTickEvent); Process *p; while ((p = toFinalize.getNext())) p->popListNode(); while ((p = initList.getNext())) p->popListNode(); while ((p = readyList.getNext())) p->popListNode(); Channel *c; while ((c = updateList.getNext())) c->popListNode(); } void Scheduler::initPhase() { for (Process *p = toFinalize.getNext(); p; p = toFinalize.getNext()) { p->finalize(); p->popListNode(); } for (Process *p = initList.getNext(); p; p = initList.getNext()) { p->finalize(); p->popListNode(); p->ready(); } update(); for (auto &e: deltas) e->run(); deltas.clear(); for (auto ets: eventsToSchedule) eq->schedule(ets.first, ets.second); eventsToSchedule.clear(); if (_started) { if (starved() && !runToTime) scheduleStarvationEvent(); kernel->status(::sc_core::SC_RUNNING); } initDone = true; } void Scheduler::reg(Process *p) { if (initDone) { // If we're past initialization, finalize static sensitivity. p->finalize(); // Mark the process as ready. p->ready(); } else { // Otherwise, record that this process should be initialized once we // get there. initList.pushLast(p); } } void Scheduler::dontInitialize(Process *p) { if (initDone) { // Pop this process off of the ready list. p->popListNode(); } else { // Push this process onto the list of processes which still need // their static sensitivity to be finalized. That implicitly pops it // off the list of processes to be initialized/marked ready. toFinalize.pushLast(p); } } void Scheduler::yield() { _current = readyList.getNext(); if (!_current) { // There are no more processes, so return control to evaluate. Fiber::primaryFiber()->run(); } else { _current->popListNode(); // Switch to whatever Fiber is supposed to run this process. All // Fibers which aren't running should be parked at this line. _current->fiber()->run(); // If the current process needs to be manually started, start it. if (_current && _current->needsStart()) _current->run(); } if (_current && _current->excWrapper) { // Make sure this isn't a method process. assert(!_current->needsStart()); auto ew = _current->excWrapper; _current->excWrapper = nullptr; ew->throw_it(); } } void Scheduler::ready(Process *p) { // Clump methods together to minimize context switching. if (p->procKind() == ::sc_core::SC_METHOD_PROC_) readyList.pushFirst(p); else readyList.pushLast(p); scheduleReadyEvent(); } void Scheduler::requestUpdate(Channel *c) { updateList.pushLast(c); scheduleReadyEvent(); } void Scheduler::scheduleReadyEvent() { // Schedule the evaluate and update phases. if (!readyEvent.scheduled()) { schedule(&readyEvent); if (starvationEvent.scheduled()) deschedule(&starvationEvent); } } void Scheduler::scheduleStarvationEvent() { if (!starvationEvent.scheduled()) { schedule(&starvationEvent); if (readyEvent.scheduled()) deschedule(&readyEvent); } } void Scheduler::runReady() { bool empty = readyList.empty(); // The evaluation phase. do { yield(); } while (!readyList.empty()); if (!empty) _numCycles++; // The update phase. update(); if (starved() && !runToTime) scheduleStarvationEvent(); // The delta phase. for (auto &e: deltas) e->run(); deltas.clear(); if (runOnce) schedulePause(); } void Scheduler::update() { Channel *channel = updateList.getNext(); while (channel) { channel->popListNode(); channel->update(); channel = updateList.getNext(); } } void Scheduler::pause() { _paused = true; kernel->status(::sc_core::SC_PAUSED); runOnce = false; scMain->run(); } void Scheduler::stop() { _stopped = true; kernel->stop(); runOnce = false; scMain->run(); } void Scheduler::start(Tick max_tick, bool run_to_time) { // We should be running from sc_main. Keep track of that Fiber to return // to later. scMain = Fiber::currentFiber(); _started = true; _paused = false; _stopped = false; runToTime = run_to_time; maxTick = max_tick; if (initDone) { if (starved() && !runToTime) scheduleStarvationEvent(); kernel->status(::sc_core::SC_RUNNING); } schedule(&maxTickEvent, maxTick); // Return to gem5 to let it run events, etc. Fiber::primaryFiber()->run(); if (pauseEvent.scheduled()) eq->deschedule(&pauseEvent); if (stopEvent.scheduled()) eq->deschedule(&stopEvent); if (maxTickEvent.scheduled()) eq->deschedule(&maxTickEvent); if (starvationEvent.scheduled()) eq->deschedule(&starvationEvent); } void Scheduler::oneCycle() { runOnce = true; start(::MaxTick, false); } void Scheduler::schedulePause() { if (pauseEvent.scheduled()) return; eq->schedule(&pauseEvent, eq->getCurTick()); } void Scheduler::scheduleStop(bool finish_delta) { if (stopEvent.scheduled()) return; if (!finish_delta) { // If we're not supposed to finish the delta cycle, flush the list // of ready processes, scheduled updates, and delta notifications. Process *p; while ((p = readyList.getNext())) p->popListNode(); Channel *c; while ((c = updateList.getNext())) c->popListNode(); for (auto &e: deltas) e->deschedule(); deltas.clear(); } eq->schedule(&stopEvent, eq->getCurTick()); } Scheduler scheduler; } // namespace sc_gem5 <commit_msg>systemc: Make sure no delta cycles are scheduled when stopping.<commit_after>/* * Copyright 2018 Google, Inc. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders 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. * * Authors: Gabe Black */ #include "systemc/core/scheduler.hh" #include "base/fiber.hh" #include "base/logging.hh" #include "sim/eventq.hh" #include "systemc/core/kernel.hh" #include "systemc/ext/core/sc_main.hh" namespace sc_gem5 { Scheduler::Scheduler() : eq(nullptr), readyEvent(this, false, ReadyPriority), pauseEvent(this, false, PausePriority), stopEvent(this, false, StopPriority), scMain(nullptr), starvationEvent(this, false, StarvationPriority), _started(false), _paused(false), _stopped(false), maxTickEvent(this, false, MaxTickPriority), _numCycles(0), _current(nullptr), initDone(false), runOnce(false) {} Scheduler::~Scheduler() { // Clear out everything that belongs to us to make sure nobody tries to // clear themselves out after the scheduler goes away. // Delta notifications. for (auto &e: deltas) e->deschedule(); // Timed notifications. for (auto &ts: timeSlots) { for (auto &e: ts.second->events) e->deschedule(); delete ts.second; ts.second = nullptr; } // gem5 events. if (readyEvent.scheduled()) eq->deschedule(&readyEvent); if (pauseEvent.scheduled()) eq->deschedule(&pauseEvent); if (stopEvent.scheduled()) eq->deschedule(&stopEvent); if (starvationEvent.scheduled()) eq->deschedule(&starvationEvent); if (maxTickEvent.scheduled()) eq->deschedule(&maxTickEvent); Process *p; while ((p = toFinalize.getNext())) p->popListNode(); while ((p = initList.getNext())) p->popListNode(); while ((p = readyList.getNext())) p->popListNode(); Channel *c; while ((c = updateList.getNext())) c->popListNode(); } void Scheduler::initPhase() { for (Process *p = toFinalize.getNext(); p; p = toFinalize.getNext()) { p->finalize(); p->popListNode(); } for (Process *p = initList.getNext(); p; p = initList.getNext()) { p->finalize(); p->popListNode(); p->ready(); } update(); for (auto &e: deltas) e->run(); deltas.clear(); for (auto ets: eventsToSchedule) eq->schedule(ets.first, ets.second); eventsToSchedule.clear(); if (_started) { if (starved() && !runToTime) scheduleStarvationEvent(); kernel->status(::sc_core::SC_RUNNING); } initDone = true; } void Scheduler::reg(Process *p) { if (initDone) { // If we're past initialization, finalize static sensitivity. p->finalize(); // Mark the process as ready. p->ready(); } else { // Otherwise, record that this process should be initialized once we // get there. initList.pushLast(p); } } void Scheduler::dontInitialize(Process *p) { if (initDone) { // Pop this process off of the ready list. p->popListNode(); } else { // Push this process onto the list of processes which still need // their static sensitivity to be finalized. That implicitly pops it // off the list of processes to be initialized/marked ready. toFinalize.pushLast(p); } } void Scheduler::yield() { _current = readyList.getNext(); if (!_current) { // There are no more processes, so return control to evaluate. Fiber::primaryFiber()->run(); } else { _current->popListNode(); // Switch to whatever Fiber is supposed to run this process. All // Fibers which aren't running should be parked at this line. _current->fiber()->run(); // If the current process needs to be manually started, start it. if (_current && _current->needsStart()) _current->run(); } if (_current && _current->excWrapper) { // Make sure this isn't a method process. assert(!_current->needsStart()); auto ew = _current->excWrapper; _current->excWrapper = nullptr; ew->throw_it(); } } void Scheduler::ready(Process *p) { // Clump methods together to minimize context switching. if (p->procKind() == ::sc_core::SC_METHOD_PROC_) readyList.pushFirst(p); else readyList.pushLast(p); scheduleReadyEvent(); } void Scheduler::requestUpdate(Channel *c) { updateList.pushLast(c); scheduleReadyEvent(); } void Scheduler::scheduleReadyEvent() { // Schedule the evaluate and update phases. if (!readyEvent.scheduled()) { schedule(&readyEvent); if (starvationEvent.scheduled()) deschedule(&starvationEvent); } } void Scheduler::scheduleStarvationEvent() { if (!starvationEvent.scheduled()) { schedule(&starvationEvent); if (readyEvent.scheduled()) deschedule(&readyEvent); } } void Scheduler::runReady() { bool empty = readyList.empty(); // The evaluation phase. do { yield(); } while (!readyList.empty()); if (!empty) _numCycles++; // The update phase. update(); if (starved() && !runToTime) scheduleStarvationEvent(); // The delta phase. for (auto &e: deltas) e->run(); deltas.clear(); if (runOnce) schedulePause(); } void Scheduler::update() { Channel *channel = updateList.getNext(); while (channel) { channel->popListNode(); channel->update(); channel = updateList.getNext(); } } void Scheduler::pause() { _paused = true; kernel->status(::sc_core::SC_PAUSED); runOnce = false; scMain->run(); } void Scheduler::stop() { _stopped = true; kernel->stop(); if (readyEvent.scheduled()) eq->deschedule(&readyEvent); runOnce = false; scMain->run(); } void Scheduler::start(Tick max_tick, bool run_to_time) { // We should be running from sc_main. Keep track of that Fiber to return // to later. scMain = Fiber::currentFiber(); _started = true; _paused = false; _stopped = false; runToTime = run_to_time; maxTick = max_tick; if (initDone) { if (starved() && !runToTime) scheduleStarvationEvent(); kernel->status(::sc_core::SC_RUNNING); } schedule(&maxTickEvent, maxTick); // Return to gem5 to let it run events, etc. Fiber::primaryFiber()->run(); if (pauseEvent.scheduled()) eq->deschedule(&pauseEvent); if (stopEvent.scheduled()) eq->deschedule(&stopEvent); if (maxTickEvent.scheduled()) eq->deschedule(&maxTickEvent); if (starvationEvent.scheduled()) eq->deschedule(&starvationEvent); } void Scheduler::oneCycle() { runOnce = true; start(::MaxTick, false); } void Scheduler::schedulePause() { if (pauseEvent.scheduled()) return; eq->schedule(&pauseEvent, eq->getCurTick()); } void Scheduler::scheduleStop(bool finish_delta) { if (stopEvent.scheduled()) return; if (!finish_delta) { // If we're not supposed to finish the delta cycle, flush the list // of ready processes, scheduled updates, and delta notifications. Process *p; while ((p = readyList.getNext())) p->popListNode(); Channel *c; while ((c = updateList.getNext())) c->popListNode(); for (auto &e: deltas) e->deschedule(); deltas.clear(); } eq->schedule(&stopEvent, eq->getCurTick()); } Scheduler scheduler; } // namespace sc_gem5 <|endoftext|>
<commit_before>/* * Copyright 2015 eje inc. * Copyright 2015 Samsung Electronics Co., LTD * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "includes.h" /*************************************************************************** * Renders a GL_TEXTURE_EXTERNAL_OES texture. ***************************************************************************/ #include "OESShader.h" #include "Material.h" #include "mesh.h" #include "RenderData.h" namespace mgn { static const char VERTEX_SHADER[] = "attribute vec4 Position;\n" "attribute vec2 TexCoord;\n" "uniform highp mat4 Mvpm;\n" "uniform highp mat4 Texm;\n" "varying highp vec2 oTexCoord;\n" "void main() {\n" " oTexCoord = vec2(Texm * vec4(TexCoord, 0, 1));\n" " gl_Position = Mvpm * Position;\n" "}\n"; static const char FRAGMENT_SHADER[] = "#extension GL_OES_EGL_image_external : require\n" "precision highp float;\n" "uniform samplerExternalOES Texture0;\n" "uniform vec4 UniformColor;\n" "uniform float Opacity;\n" "varying highp vec2 oTexCoord;\n" "void main() {\n" " vec4 texel = texture2D(Texture0, oTexCoord) * UniformColor * Opacity;\n" " if (texel.a < 0.1)\n" " discard;\n" " gl_FragColor = texel;\n" "}\n"; OESShader::OESShader() { program = BuildProgram(VERTEX_SHADER, FRAGMENT_SHADER); opacity = glGetUniformLocation(program.Program, "Opacity"); } OESShader::~OESShader() { DeleteProgram(program); } void OESShader::Render(const Matrix4f & mvpMatrix, const GlGeometry & geometry, const Material * material, const int eye) const { Vector4f color = material->GetColor(); GL(glUseProgram(program.Program)); GL(glUniformMatrix4fv(program.uMvp, 1, GL_TRUE, mvpMatrix.M[0])); GL(glUniformMatrix4fv(program.uTexm, 1, GL_TRUE, TexmForVideo(material->GetStereoMode(), eye).M[ 0 ] )); GL(glActiveTexture (GL_TEXTURE0)); GL(glBindTexture(GL_TEXTURE_EXTERNAL_OES, material->GetTextureId())); GL(glUniform4f(program.uColor, color.x, color.y, color.z, color.w)); GL(glUniform1f(opacity, material->GetOpacity())); geometry.Draw(); GL(glBindTexture( GL_TEXTURE_EXTERNAL_OES, 0 )); } const Matrix4f & OESShader::TexmForVideo(const Material::StereoMode stereoMode, const int eye ) const { switch (stereoMode) { case Material::StereoMode::TOP_BOTTOM: return eye ? bottomM : topM; case Material::StereoMode::BOTTOM_TOP: return eye ? topM : bottomM; case Material::StereoMode::LEFT_RIGHT: return eye ? rightM : leftM; case Material::StereoMode::RIGHT_LEFT: return eye ? leftM : rightM; case Material::StereoMode::TOP_ONLY: return topM; case Material::StereoMode::BOTTOM_ONLY: return bottomM; case Material::StereoMode::LEFT_ONLY: return leftM; case Material::StereoMode::RIGHT_ONLY: return rightM; case Material::StereoMode::NORMAL: default: return normalM; } } } ; <commit_msg>Update to GLES3<commit_after>/* * Copyright 2015 eje inc. * Copyright 2015 Samsung Electronics Co., LTD * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "includes.h" /*************************************************************************** * Renders a GL_TEXTURE_EXTERNAL_OES texture. ***************************************************************************/ #include "OESShader.h" #include "Material.h" #include "mesh.h" #include "RenderData.h" namespace mgn { static const char * ImageExternalDirectives = "#extension GL_OES_EGL_image_external : enable\n" "#extension GL_OES_EGL_image_external_essl3 : enable\n"; static const char VERTEX_SHADER[] = "in vec4 Position;\n" "in vec2 TexCoord;\n" "uniform highp mat4 Mvpm;\n" "uniform highp mat4 Texm;\n" "out highp vec2 oTexCoord;\n" "void main() {\n" " oTexCoord = vec2(Texm * vec4(TexCoord, 0, 1));\n" " gl_Position = Mvpm * Position;\n" "}\n"; static const char FRAGMENT_SHADER[] = "precision highp float;\n" "uniform samplerExternalOES Texture0;\n" "uniform vec4 UniformColor;\n" "uniform float Opacity;\n" "in highp vec2 oTexCoord;\n" "void main() {\n" " vec4 texel = texture2D(Texture0, oTexCoord) * UniformColor * Opacity;\n" " if (texel.a < 0.1)\n" " discard;\n" " gl_FragColor = texel;\n" "}\n"; OESShader::OESShader() { program = BuildProgram(NULL, VERTEX_SHADER, ImageExternalDirectives, FRAGMENT_SHADER); opacity = glGetUniformLocation(program.Program, "Opacity"); } OESShader::~OESShader() { DeleteProgram(program); } void OESShader::Render(const Matrix4f & mvpMatrix, const GlGeometry & geometry, const Material * material, const int eye) const { Vector4f color = material->GetColor(); GL(glUseProgram(program.Program)); GL(glUniformMatrix4fv(program.uMvp, 1, GL_TRUE, mvpMatrix.M[0])); GL(glUniformMatrix4fv(program.uTexm, 1, GL_TRUE, TexmForVideo(material->GetStereoMode(), eye).M[ 0 ] )); GL(glActiveTexture (GL_TEXTURE0)); GL(glBindTexture(GL_TEXTURE_EXTERNAL_OES, material->GetTextureId())); GL(glUniform4f(program.uColor, color.x, color.y, color.z, color.w)); GL(glUniform1f(opacity, material->GetOpacity())); geometry.Draw(); GL(glBindTexture( GL_TEXTURE_EXTERNAL_OES, 0 )); } const Matrix4f & OESShader::TexmForVideo(const Material::StereoMode stereoMode, const int eye ) const { switch (stereoMode) { case Material::StereoMode::TOP_BOTTOM: return eye ? bottomM : topM; case Material::StereoMode::BOTTOM_TOP: return eye ? topM : bottomM; case Material::StereoMode::LEFT_RIGHT: return eye ? rightM : leftM; case Material::StereoMode::RIGHT_LEFT: return eye ? leftM : rightM; case Material::StereoMode::TOP_ONLY: return topM; case Material::StereoMode::BOTTOM_ONLY: return bottomM; case Material::StereoMode::LEFT_ONLY: return leftM; case Material::StereoMode::RIGHT_ONLY: return rightM; case Material::StereoMode::NORMAL: default: return normalM; } } } ; <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/lib/fir/memdiags_fir.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file memdiags_fir.C /// @brief Subroutines for memdiags/prd FIR /// // *HWP HWP Owner: Stephen Glancy <sglancy@us.ibm.com> // *HWP HWP Backup: Marc Gollub <gollub@us.ibm.com> // *HWP Team: Memory // *HWP Level: 3 // *HWP Consumed by: FSP:HB #include <fapi2.H> #include <p9_mc_scom_addresses.H> #include <p9_mc_scom_addresses_fld.H> #include <generic/memory/lib/utils/scom.H> #include <generic/memory/lib/utils/find.H> #include <lib/fir/fir.H> #include <lib/fir/memdiags_fir.H> #include <lib/mc/port.H> #include <lib/workarounds/mcbist_workarounds.H> using fapi2::TARGET_TYPE_MCBIST; using fapi2::TARGET_TYPE_MCA; namespace mss { namespace unmask { /// /// @brief Unmask and setup actions for memdiags related FIR /// @param[in] i_target the fapi2::Target MCBIST /// @return fapi2::ReturnCode FAPI2_RC_SUCCESS iff ok /// template<> fapi2::ReturnCode after_memdiags( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target ) { fapi2::ReturnCode l_rc; fapi2::buffer<uint64_t> dsm0_buffer; fapi2::buffer<uint64_t> l_mnfg_buffer; uint64_t rd_tag_delay = 0; uint64_t wr_done_delay = 0; fapi2::buffer<uint64_t> l_aue_buffer; fapi2::ATTR_CHIP_EC_FEATURE_HW414700_Type l_checkstop_flag; constexpr uint64_t MNFG_THRESHOLDS_ATTR = 63; // Broadcast mode workaround for UEs causing out of sync FAPI_TRY(mss::workarounds::mcbist::broadcast_out_of_sync(i_target, mss::ON)); for (const auto& p : mss::find_targets<TARGET_TYPE_MCA>(i_target)) { fir::reg<MCA_FIR> l_ecc64_fir_reg(p, l_rc); FAPI_TRY(l_rc, "unable to create fir::reg for %d", MCA_FIR); fir::reg<MCA_MBACALFIRQ> l_cal_fir_reg(p, l_rc); FAPI_TRY(l_rc, "unable to create fir::reg for %d", MCA_MBACALFIRQ); // Read out the wr_done and rd_tag delays and find min // and set the RCD Protect Time to this value FAPI_TRY (mss::read_dsm0q_register(p, dsm0_buffer) ); mss::get_wrdone_delay(dsm0_buffer, wr_done_delay); mss::get_rdtag_delay(dsm0_buffer, rd_tag_delay); const auto rcd_protect_time = std::min(wr_done_delay, rd_tag_delay); FAPI_TRY (mss::change_rcd_protect_time(p, rcd_protect_time) ); l_ecc64_fir_reg.checkstop<MCA_FIR_MAINLINE_AUE>() .recoverable_error<MCA_FIR_MAINLINE_UE>() .checkstop<MCA_FIR_MAINLINE_IAUE>() .recoverable_error<MCA_FIR_MAINLINE_IUE>(); // If ATTR_CHIP_EC_FEATURE_HW414700 is enabled set checkstops auto l_chip_target = mss::find_target<fapi2::TARGET_TYPE_PROC_CHIP>(i_target); FAPI_TRY( FAPI_ATTR_GET(fapi2::ATTR_CHIP_EC_FEATURE_HW414700, l_chip_target, l_checkstop_flag) ); if (l_checkstop_flag) { l_ecc64_fir_reg.checkstop<MCA_FIR_MAINLINE_UE>() .checkstop<MCA_FIR_MAINLINE_RCD>(); } // If MNFG FLAG Threshhold is enabled skip IUE unflagging FAPI_TRY ( mss::mnfg_flags(l_mnfg_buffer) ); if ( !(l_mnfg_buffer.getBit<MNFG_THRESHOLDS_ATTR>()) ) { l_ecc64_fir_reg.recoverable_error<MCA_FIR_MAINTENANCE_IUE>(); } l_cal_fir_reg.recoverable_error<MCA_MBACALFIRQ_PORT_FAIL>(); FAPI_TRY(l_ecc64_fir_reg.write(), "unable to write fir::reg %d", MCA_FIR); FAPI_TRY(l_cal_fir_reg.write(), "unable to write fir::reg %d", MCA_MBACALFIRQ); // Change Maint AUE and IAUE to checkstop without unmasking // Normal setup modifies masked bits in addition to setting checkstop // This causes issues if error has occured, manually scoming to avoid this FAPI_TRY( mss::getScom(p, MCA_ACTION1, l_aue_buffer) ); l_aue_buffer.clearBit<MCA_FIR_MAINTENANCE_AUE>(); l_aue_buffer.clearBit<MCA_FIR_MAINTENANCE_IAUE>(); FAPI_TRY( mss::putScom(p, MCA_ACTION1, l_aue_buffer) ); // Note: We also want to include the following setup RCD recovery and port fail FAPI_TRY( mss::change_port_fail_disable(p, mss::LOW) ); FAPI_TRY( mss::change_rcd_recovery_disable(p, mss::LOW) ); } return fapi2::FAPI2_RC_SUCCESS; fapi_try_exit: return fapi2::current_err; } /// /// @brief Unmask and setup actions for scrub related FIR /// @param[in] i_target the fapi2::Target MCBIST /// @return fapi2::ReturnCode FAPI2_RC_SUCCESS iff ok /// template<> fapi2::ReturnCode after_background_scrub( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target ) { for (const auto& p : mss::find_targets<TARGET_TYPE_MCA>(i_target)) { fapi2::ReturnCode l_rc; fir::reg<MCA_FIR> l_ecc64_fir_reg(p, l_rc); FAPI_TRY(l_rc, "unable to create fir::reg for %d", MCA_FIR); l_ecc64_fir_reg.recoverable_error<MCA_FIR_MAINLINE_MPE_RANK_0_TO_7, MCA_FIR_MAINLINE_MPE_RANK_0_TO_7_LEN>() .recoverable_error<MCA_FIR_MAINLINE_NCE>() .recoverable_error<MCA_FIR_MAINLINE_TCE>() .recoverable_error<MCA_FIR_MAINLINE_IMPE>() .recoverable_error<MCA_FIR_MAINTENANCE_IMPE>(); FAPI_TRY(l_ecc64_fir_reg.write(), "unable to write fir::reg %d", MCA_FIR); } return fapi2::FAPI2_RC_SUCCESS; fapi_try_exit: return fapi2::current_err; } } } <commit_msg>Fixed port fail SUE bug for DD2 modules<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/lib/fir/memdiags_fir.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file memdiags_fir.C /// @brief Subroutines for memdiags/prd FIR /// // *HWP HWP Owner: Stephen Glancy <sglancy@us.ibm.com> // *HWP HWP Backup: Marc Gollub <gollub@us.ibm.com> // *HWP Team: Memory // *HWP Level: 3 // *HWP Consumed by: FSP:HB #include <fapi2.H> #include <p9_mc_scom_addresses.H> #include <p9_mc_scom_addresses_fld.H> #include <generic/memory/lib/utils/scom.H> #include <generic/memory/lib/utils/find.H> #include <lib/fir/fir.H> #include <lib/fir/memdiags_fir.H> #include <lib/mc/port.H> #include <lib/workarounds/mcbist_workarounds.H> using fapi2::TARGET_TYPE_MCBIST; using fapi2::TARGET_TYPE_MCA; namespace mss { namespace unmask { /// /// @brief Unmask and setup actions for memdiags related FIR /// @param[in] i_target the fapi2::Target MCBIST /// @return fapi2::ReturnCode FAPI2_RC_SUCCESS iff ok /// template<> fapi2::ReturnCode after_memdiags( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target ) { fapi2::ReturnCode l_rc; fapi2::buffer<uint64_t> dsm0_buffer; fapi2::buffer<uint64_t> l_mnfg_buffer; uint64_t rd_tag_delay = 0; uint64_t wr_done_delay = 0; fapi2::buffer<uint64_t> l_aue_buffer; fapi2::ATTR_CHIP_EC_FEATURE_HW414700_Type l_checkstop_flag; constexpr uint64_t MNFG_THRESHOLDS_ATTR = 63; // Broadcast mode workaround for UEs causing out of sync FAPI_TRY(mss::workarounds::mcbist::broadcast_out_of_sync(i_target, mss::ON)); for (const auto& p : mss::find_targets<TARGET_TYPE_MCA>(i_target)) { fir::reg<MCA_FIR> l_ecc64_fir_reg(p, l_rc); FAPI_TRY(l_rc, "unable to create fir::reg for %d", MCA_FIR); fir::reg<MCA_MBACALFIRQ> l_cal_fir_reg(p, l_rc); FAPI_TRY(l_rc, "unable to create fir::reg for %d", MCA_MBACALFIRQ); // Read out the wr_done and rd_tag delays and find min // and set the RCD Protect Time to this value FAPI_TRY (mss::read_dsm0q_register(p, dsm0_buffer) ); mss::get_wrdone_delay(dsm0_buffer, wr_done_delay); mss::get_rdtag_delay(dsm0_buffer, rd_tag_delay); const auto rcd_protect_time = std::min(wr_done_delay, rd_tag_delay); FAPI_TRY (mss::change_rcd_protect_time(p, rcd_protect_time) ); l_ecc64_fir_reg.checkstop<MCA_FIR_MAINLINE_AUE>() .recoverable_error<MCA_FIR_MAINLINE_UE>() .checkstop<MCA_FIR_MAINLINE_IAUE>() .recoverable_error<MCA_FIR_MAINLINE_IUE>(); l_cal_fir_reg.recoverable_error<MCA_MBACALFIRQ_PORT_FAIL>(); // If ATTR_CHIP_EC_FEATURE_HW414700 is enabled set checkstops auto l_chip_target = mss::find_target<fapi2::TARGET_TYPE_PROC_CHIP>(i_target); FAPI_TRY( FAPI_ATTR_GET(fapi2::ATTR_CHIP_EC_FEATURE_HW414700, l_chip_target, l_checkstop_flag) ); // If the system is running DD2 chips override some recoverable firs with checkstop // Due to a known hardware defect with DD2 certain errors are not handled properly // As a result, these firs are marked as checkstop for DD2 to avoid any mishandling if (l_checkstop_flag) { l_ecc64_fir_reg.checkstop<MCA_FIR_MAINLINE_UE>() .checkstop<MCA_FIR_MAINLINE_RCD>(); l_cal_fir_reg.checkstop<MCA_MBACALFIRQ_PORT_FAIL>(); } // If MNFG FLAG Threshhold is enabled skip IUE unflagging FAPI_TRY ( mss::mnfg_flags(l_mnfg_buffer) ); if ( !(l_mnfg_buffer.getBit<MNFG_THRESHOLDS_ATTR>()) ) { l_ecc64_fir_reg.recoverable_error<MCA_FIR_MAINTENANCE_IUE>(); } FAPI_TRY(l_ecc64_fir_reg.write(), "unable to write fir::reg %d", MCA_FIR); FAPI_TRY(l_cal_fir_reg.write(), "unable to write fir::reg %d", MCA_MBACALFIRQ); // Change Maint AUE and IAUE to checkstop without unmasking // Normal setup modifies masked bits in addition to setting checkstop // This causes issues if error has occured, manually scoming to avoid this FAPI_TRY( mss::getScom(p, MCA_ACTION1, l_aue_buffer) ); l_aue_buffer.clearBit<MCA_FIR_MAINTENANCE_AUE>(); l_aue_buffer.clearBit<MCA_FIR_MAINTENANCE_IAUE>(); FAPI_TRY( mss::putScom(p, MCA_ACTION1, l_aue_buffer) ); // Note: We also want to include the following setup RCD recovery and port fail FAPI_TRY( mss::change_port_fail_disable(p, mss::LOW) ); FAPI_TRY( mss::change_rcd_recovery_disable(p, mss::LOW) ); } return fapi2::FAPI2_RC_SUCCESS; fapi_try_exit: return fapi2::current_err; } /// /// @brief Unmask and setup actions for scrub related FIR /// @param[in] i_target the fapi2::Target MCBIST /// @return fapi2::ReturnCode FAPI2_RC_SUCCESS iff ok /// template<> fapi2::ReturnCode after_background_scrub( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target ) { for (const auto& p : mss::find_targets<TARGET_TYPE_MCA>(i_target)) { fapi2::ReturnCode l_rc; fir::reg<MCA_FIR> l_ecc64_fir_reg(p, l_rc); FAPI_TRY(l_rc, "unable to create fir::reg for %d", MCA_FIR); l_ecc64_fir_reg.recoverable_error<MCA_FIR_MAINLINE_MPE_RANK_0_TO_7, MCA_FIR_MAINLINE_MPE_RANK_0_TO_7_LEN>() .recoverable_error<MCA_FIR_MAINLINE_NCE>() .recoverable_error<MCA_FIR_MAINLINE_TCE>() .recoverable_error<MCA_FIR_MAINLINE_IMPE>() .recoverable_error<MCA_FIR_MAINTENANCE_IMPE>(); FAPI_TRY(l_ecc64_fir_reg.write(), "unable to write fir::reg %d", MCA_FIR); } return fapi2::FAPI2_RC_SUCCESS; fapi_try_exit: return fapi2::current_err; } } } <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/generic/memory/lib/spd/lrdimm/ddr4/lrdimm_raw_cards.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file raw_cards.C /// @brief LRDIMM raw card data structure /// Contains RCW settings per raw card rev /// // *HWP HWP Owner: Andre Marin <aamarin@us.ibm.com> // *HWP HWP Backup: Brian Silver <bsilver@us.ibm.com> // *HWP Team: Memory // *HWP Level: 2 // *HWP Consumed by: FSP:HB // std lib #include <vector> // fapi2 #include <fapi2.H> // mss lib #include <generic/memory/lib/spd/lrdimm/ddr4/lrdimm_raw_cards.H> namespace mss { /// /// @brief raw card B0 settings /// // TODO RTC:160116 Fill in valid RCD data for LRDIMM rcw_settings lrdimm_rc_b0( 0x00, // RC00 0x00, // RC01 (C might be the right answer) 0x00, // RC02 0x1F, // RC06_7 0x00, // RC09 0x0E, // RC0B 0x00, // RC0C 0x00, // RC0F 0x00, // RC1X 0x00, // RC2X 0x00, // RC4X 0x00, // RC5X 0x00, // RC6C 0x00, // RC8X 0x00, // RC9X 0x00); // RCAX namespace lrdimm { // TODO - RTC:160121 Catch all for adding raw card data for DIMMs const std::vector< std::pair< uint8_t , rcw_settings> > RAW_CARDS = { // I expect this to grow as Warren M. expects us to have // settings for every raw card that JEDEC puts out. Openpower // can't break due to a missing raw card... {raw_card_rev::B0, lrdimm_rc_b0}, }; }// lrdimm }// mss <commit_msg>Turn off A17 if not needed<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/generic/memory/lib/spd/lrdimm/ddr4/lrdimm_raw_cards.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file raw_cards.C /// @brief LRDIMM raw card data structure /// Contains RCW settings per raw card rev /// // *HWP HWP Owner: Andre Marin <aamarin@us.ibm.com> // *HWP HWP Backup: Brian Silver <bsilver@us.ibm.com> // *HWP Team: Memory // *HWP Level: 2 // *HWP Consumed by: FSP:HB // std lib #include <vector> // fapi2 #include <fapi2.H> // mss lib #include <generic/memory/lib/spd/lrdimm/ddr4/lrdimm_raw_cards.H> namespace mss { /// /// @brief raw card B0 settings /// // TODO RTC:160116 Fill in valid RCD data for LRDIMM rcw_settings lrdimm_rc_b0( 0x00, // RC00 0x00, // RC01 (C might be the right answer) 0x1F, // RC06_7 0x00, // RC09 0x0E, // RC0B 0x00, // RC0C 0x00, // RC0F 0x00, // RC1X 0x00, // RC2X 0x00, // RC4X 0x00, // RC5X 0x00, // RC6C 0x00, // RC8X 0x00, // RC9X 0x00); // RCAX namespace lrdimm { // TODO - RTC:160121 Catch all for adding raw card data for DIMMs const std::vector< std::pair< uint8_t , rcw_settings> > RAW_CARDS = { // I expect this to grow as Warren M. expects us to have // settings for every raw card that JEDEC puts out. Openpower // can't break due to a missing raw card... {raw_card_rev::B0, lrdimm_rc_b0}, }; }// lrdimm }// mss <|endoftext|>
<commit_before>/* * Copyright (c) 2013 Juniper Networks, Inc. All rights reserved. */ #include <csetjmp> #include <base/os.h> #include <base/test/task_test_util.h> #include <cmn/agent_cmn.h> #include <cmn/agent_factory.h> #include <init/agent_param.h> #include <cfg/cfg_init.h> #include <ovs_tor_agent/ovsdb_client/ovsdb_route_peer.h> #include <oper/operdb_init.h> #include <vrouter/ksync/ksync_init.h> #include <vrouter/ksync/test/ksync_test.h> #include <uve/agent_uve.h> #include <uve/test/agent_uve_test.h> #include "test/test_init.h" #include <test/test_agent_init.h> #include "test_ovs_agent_init.h" #include "test-xml/test_xml_oper.h" #include "test_xml_physical_device.h" #include "test_xml_ovsdb.h" #include <boost/filesystem/operations.hpp> #define OVSDB_SERVER "build/third_party/openvswitch/ovsdb/ovsdb-server" #define DB_FILE_TEMPLATE "controller/src/vnsw/agent/ovs_tor_agent/ovsdb_client/test/vtep.db" using namespace OVSDB; std::string db_file_name; std::string lock_file_name; bool server_inited = false; bool server_stopping = false; int server_pid; jmp_buf env; uint32_t ovsdb_port = 0; void stop_ovsdb_server() { if (server_inited == false || server_stopping == true) { return; } server_stopping = true; kill(server_pid, SIGTERM); int status; while (server_pid != wait(&status)); // after the child process has exited, delete the db file and lock file boost::filesystem::remove(db_file_name); boost::filesystem::remove(lock_file_name); server_inited = false; server_stopping = false; } void signalHandler(int sig_num) { stop_ovsdb_server(); longjmp (env, 1); } static void start_ovsdb_server() { assert(server_inited == false); signal(SIGABRT, signalHandler); signal(SIGSEGV, signalHandler); signal(SIGTERM, signalHandler); atexit(stop_ovsdb_server); server_inited = true; db_file_name = "build/debug/vnsw/agent/ovs_tor_agent/ovsdb_client/test/vtep_" + boost::lexical_cast<std::string>(getpid()) + "_" + boost::lexical_cast<std::string>(UTCTimestampUsec()) + ".db"; lock_file_name = db_file_name; size_t pos = lock_file_name.find("vtep_"); lock_file_name.insert(pos, "."); lock_file_name.append(".~lock~"); // create a new DB for Ovsdb Server from DB Template file boost::filesystem::copy_file(DB_FILE_TEMPLATE, db_file_name); server_pid = fork(); if (server_pid == 0) { execlp(OVSDB_SERVER, OVSDB_SERVER, "--remote=ptcp:0:127.0.0.1", db_file_name.c_str(), static_cast<char *>(NULL)); } std::string port = ""; // Get the TCP server port used by ovsdb-server. int count = 0; do { usleep(1000); assert(count < 10000); count++; std::string cmd("netstat -anp | grep tcp | grep "); cmd += boost::lexical_cast<std::string>(server_pid); cmd += "/ovsdb-server"; FILE* pipe = popen(cmd.c_str(), "r"); if (!pipe) assert(false); char buffer[128]; std::string result; while(!feof(pipe)) { if(fgets(buffer, 128, pipe) != NULL) result += buffer; } pclose(pipe); size_t start = result.find("127.0.0.1:"); // find will fail if the process has not started the listen on socket if (start == string::npos) continue; start += 10; size_t end = result.find_first_of(' ', start); assert(end != string::npos); port = result.substr(start, end - start); } while (port.empty()); ovsdb_port = strtoul(port.c_str(), NULL, 0); } OvsdbClientTcpSessionTest::OvsdbClientTcpSessionTest(Agent *agent, OvsPeerManager *manager, TcpServer *server, Socket *sock, bool async_ready) : OvsdbClientTcpSession(agent, manager, server, sock, async_ready) { } OvsdbClientTcpSessionTest::~OvsdbClientTcpSessionTest() { } OvsdbClientTcpTest::OvsdbClientTcpTest(Agent *agent, IpAddress tor_ip, int tor_port, IpAddress tsn_ip, int keepalive, OvsPeerManager *manager) : OvsdbClientTcp(agent, tor_ip, tor_port, tsn_ip, keepalive, -1, manager), enable_connect_(true) { } OvsdbClientTcpTest::~OvsdbClientTcpTest() { } TcpSession *OvsdbClientTcpTest::AllocSession(Socket *socket) { TcpSession *session = new OvsdbClientTcpSessionTest(agent_, peer_manager_, this, socket); session->set_observer(boost::bind(&OvsdbClientTcp::OnSessionEvent, this, _1, _2)); return session; } void OvsdbClientTcpTest::Connect(TcpSession *session, Endpoint remote) { if (enable_connect_) { OvsdbClientTcp::Connect(session, remote); } } void OvsdbClientTcpTest::set_enable_connect(bool enable) { if (enable_connect_ != enable) { enable_connect_ = enable; if (enable_connect_) { Connect(session_, server_ep_); } } } TestOvsAgentInit::TestOvsAgentInit() : TestAgentInit() { } TestOvsAgentInit::~TestOvsAgentInit() { } /**************************************************************************** * Initialization routines ***************************************************************************/ // Create the basic modules for agent operation. // Optional modules or modules that have different implementation are created // by init module void TestOvsAgentInit::CreateModules() { TestAgentInit::CreateModules(); if (ovs_init_) { start_ovsdb_server(); ovsdb_client_.reset(new OVSDB::OvsdbClientTcpTest(agent(), IpAddress(Ip4Address::from_string("127.0.0.1")), ovsdb_port, IpAddress(Ip4Address::from_string("127.0.0.1")), 0, ovs_peer_manager())); agent()->set_ovsdb_client(ovsdb_client_.get()); } } void TestOvsAgentInit::CreateDBTables() { TestAgentInit::CreateDBTables(); } void TestOvsAgentInit::RegisterDBClients() { TestAgentInit::RegisterDBClients(); if (ovs_init_) ovsdb_client_->RegisterClients(); } void TestOvsAgentInit::CreatePeers() { ovs_peer_manager_.reset(new OvsPeerManager(agent())); } /**************************************************************************** * Access routines ****************************************************************************/ OvsPeerManager *TestOvsAgentInit::ovs_peer_manager() const { return ovs_peer_manager_.get(); } OVSDB::OvsdbClientTcp *TestOvsAgentInit::ovsdb_client() const { return ovsdb_client_.get(); } void TestOvsAgentInit::set_ovs_init(bool ovs_init) { ovs_init_ = ovs_init; } void TestOvsAgentInit::KSyncShutdown() { if (ovsdb_client_.get()) ovsdb_client_->shutdown(); } void LoadAndRun(const std::string &file_name) { AgentUtXmlTest test(file_name); AgentUtXmlOperInit(&test); AgentUtXmlPhysicalDeviceInit(&test); AgentUtXmlOvsdbInit(&test); if (test.Load() == true) { test.ReadXml(); string str; test.ToString(&str); cout << str << endl; test.Run(); } } bool LoadXml(AgentUtXmlTest &test) { AgentUtXmlOperInit(&test); AgentUtXmlPhysicalDeviceInit(&test); AgentUtXmlOvsdbInit(&test); if (test.Load() == true) { test.ReadXml(); string str; test.ToString(&str); cout << str << endl; return true; } return false; } TestClient *OvsTestInit(const char *init_file, bool ovs_init) { TestClient *client = new TestClient(new TestOvsAgentInit()); TestOvsAgentInit *init = static_cast<TestOvsAgentInit *>(client->agent_init()); Agent *agent = client->agent(); AgentParam *param = client->param(); init->set_agent_param(param); // Read agent parameters from config file and arguments init->ProcessOptions(init_file, "test"); param->set_agent_stats_interval(AgentParam::kAgentStatsInterval); param->set_flow_stats_interval(AgentParam::kFlowStatsInterval); param->set_vrouter_stats_interval(AgentParam::kVrouterStatsInterval); // Initialize the agent-init control class int introspect_port = 0; Sandesh::InitGeneratorTest("VNSWAgent", "Agent", "Test", "Test", agent->event_manager(), introspect_port, NULL); init->set_ksync_enable(false); init->set_packet_enable(false); init->set_services_enable(false); init->set_create_vhost(false); init->set_uve_enable(true); init->set_vgw_enable(false); init->set_router_id_dep_enable(false); init->set_ovs_init(ovs_init); param->set_test_mode(true); agent->set_ksync_sync_mode(true); // Initialize agent and kick start initialization init->Start(); WaitForInitDone(agent); client->Init(); client->WaitForIdle(); client->SetFlowFlushExclusionPolicy(); client->SetFlowAgeExclusionPolicy(); AsioRun(); return client; } <commit_msg>Fix OVSDB UT coverage build<commit_after>/* * Copyright (c) 2013 Juniper Networks, Inc. All rights reserved. */ #include <csetjmp> #include <base/os.h> #include <base/test/task_test_util.h> #include <cmn/agent_cmn.h> #include <cmn/agent_factory.h> #include <init/agent_param.h> #include <cfg/cfg_init.h> #include <ovs_tor_agent/ovsdb_client/ovsdb_route_peer.h> #include <oper/operdb_init.h> #include <vrouter/ksync/ksync_init.h> #include <vrouter/ksync/test/ksync_test.h> #include <uve/agent_uve.h> #include <uve/test/agent_uve_test.h> #include "test/test_init.h" #include <test/test_agent_init.h> #include "test_ovs_agent_init.h" #include "test-xml/test_xml_oper.h" #include "test_xml_physical_device.h" #include "test_xml_ovsdb.h" #include <boost/filesystem/operations.hpp> #define OVSDB_SERVER "build/third_party/openvswitch/ovsdb/ovsdb-server" #define DB_FILE_TEMPLATE "controller/src/vnsw/agent/ovs_tor_agent/ovsdb_client/test/vtep.db" using namespace OVSDB; std::string db_file_name; std::string lock_file_name; bool server_inited = false; bool server_stopping = false; int server_pid; jmp_buf env; uint32_t ovsdb_port = 0; void stop_ovsdb_server() { if (server_inited == false || server_stopping == true) { return; } server_stopping = true; kill(server_pid, SIGTERM); int status; while (server_pid != wait(&status)); // after the child process has exited, delete the db file and lock file boost::filesystem::remove(db_file_name); boost::filesystem::remove(lock_file_name); server_inited = false; server_stopping = false; } void signalHandler(int sig_num) { stop_ovsdb_server(); longjmp (env, 1); } static void start_ovsdb_server() { assert(server_inited == false); signal(SIGABRT, signalHandler); signal(SIGSEGV, signalHandler); signal(SIGTERM, signalHandler); atexit(stop_ovsdb_server); server_inited = true; db_file_name = "build/vtep_" + boost::lexical_cast<std::string>(getpid()) + "_" + boost::lexical_cast<std::string>(UTCTimestampUsec()) + ".db"; lock_file_name = db_file_name; size_t pos = lock_file_name.find("vtep_"); lock_file_name.insert(pos, "."); lock_file_name.append(".~lock~"); // create a new DB for Ovsdb Server from DB Template file boost::filesystem::copy_file(DB_FILE_TEMPLATE, db_file_name); server_pid = fork(); if (server_pid == 0) { execlp(OVSDB_SERVER, OVSDB_SERVER, "--remote=ptcp:0:127.0.0.1", db_file_name.c_str(), static_cast<char *>(NULL)); } std::string port = ""; // Get the TCP server port used by ovsdb-server. int count = 0; do { usleep(1000); assert(count < 10000); count++; std::string cmd("netstat -anp | grep tcp | grep "); cmd += boost::lexical_cast<std::string>(server_pid); cmd += "/ovsdb-server"; FILE* pipe = popen(cmd.c_str(), "r"); if (!pipe) assert(false); char buffer[128]; std::string result; while(!feof(pipe)) { if(fgets(buffer, 128, pipe) != NULL) result += buffer; } pclose(pipe); size_t start = result.find("127.0.0.1:"); // find will fail if the process has not started the listen on socket if (start == string::npos) continue; start += 10; size_t end = result.find_first_of(' ', start); assert(end != string::npos); port = result.substr(start, end - start); } while (port.empty()); ovsdb_port = strtoul(port.c_str(), NULL, 0); } OvsdbClientTcpSessionTest::OvsdbClientTcpSessionTest(Agent *agent, OvsPeerManager *manager, TcpServer *server, Socket *sock, bool async_ready) : OvsdbClientTcpSession(agent, manager, server, sock, async_ready) { } OvsdbClientTcpSessionTest::~OvsdbClientTcpSessionTest() { } OvsdbClientTcpTest::OvsdbClientTcpTest(Agent *agent, IpAddress tor_ip, int tor_port, IpAddress tsn_ip, int keepalive, OvsPeerManager *manager) : OvsdbClientTcp(agent, tor_ip, tor_port, tsn_ip, keepalive, -1, manager), enable_connect_(true) { } OvsdbClientTcpTest::~OvsdbClientTcpTest() { } TcpSession *OvsdbClientTcpTest::AllocSession(Socket *socket) { TcpSession *session = new OvsdbClientTcpSessionTest(agent_, peer_manager_, this, socket); session->set_observer(boost::bind(&OvsdbClientTcp::OnSessionEvent, this, _1, _2)); return session; } void OvsdbClientTcpTest::Connect(TcpSession *session, Endpoint remote) { if (enable_connect_) { OvsdbClientTcp::Connect(session, remote); } } void OvsdbClientTcpTest::set_enable_connect(bool enable) { if (enable_connect_ != enable) { enable_connect_ = enable; if (enable_connect_) { Connect(session_, server_ep_); } } } TestOvsAgentInit::TestOvsAgentInit() : TestAgentInit() { } TestOvsAgentInit::~TestOvsAgentInit() { } /**************************************************************************** * Initialization routines ***************************************************************************/ // Create the basic modules for agent operation. // Optional modules or modules that have different implementation are created // by init module void TestOvsAgentInit::CreateModules() { TestAgentInit::CreateModules(); if (ovs_init_) { start_ovsdb_server(); ovsdb_client_.reset(new OVSDB::OvsdbClientTcpTest(agent(), IpAddress(Ip4Address::from_string("127.0.0.1")), ovsdb_port, IpAddress(Ip4Address::from_string("127.0.0.1")), 0, ovs_peer_manager())); agent()->set_ovsdb_client(ovsdb_client_.get()); } } void TestOvsAgentInit::CreateDBTables() { TestAgentInit::CreateDBTables(); } void TestOvsAgentInit::RegisterDBClients() { TestAgentInit::RegisterDBClients(); if (ovs_init_) ovsdb_client_->RegisterClients(); } void TestOvsAgentInit::CreatePeers() { ovs_peer_manager_.reset(new OvsPeerManager(agent())); } /**************************************************************************** * Access routines ****************************************************************************/ OvsPeerManager *TestOvsAgentInit::ovs_peer_manager() const { return ovs_peer_manager_.get(); } OVSDB::OvsdbClientTcp *TestOvsAgentInit::ovsdb_client() const { return ovsdb_client_.get(); } void TestOvsAgentInit::set_ovs_init(bool ovs_init) { ovs_init_ = ovs_init; } void TestOvsAgentInit::KSyncShutdown() { if (ovsdb_client_.get()) ovsdb_client_->shutdown(); } void LoadAndRun(const std::string &file_name) { AgentUtXmlTest test(file_name); AgentUtXmlOperInit(&test); AgentUtXmlPhysicalDeviceInit(&test); AgentUtXmlOvsdbInit(&test); if (test.Load() == true) { test.ReadXml(); string str; test.ToString(&str); cout << str << endl; test.Run(); } } bool LoadXml(AgentUtXmlTest &test) { AgentUtXmlOperInit(&test); AgentUtXmlPhysicalDeviceInit(&test); AgentUtXmlOvsdbInit(&test); if (test.Load() == true) { test.ReadXml(); string str; test.ToString(&str); cout << str << endl; return true; } return false; } TestClient *OvsTestInit(const char *init_file, bool ovs_init) { TestClient *client = new TestClient(new TestOvsAgentInit()); TestOvsAgentInit *init = static_cast<TestOvsAgentInit *>(client->agent_init()); Agent *agent = client->agent(); AgentParam *param = client->param(); init->set_agent_param(param); // Read agent parameters from config file and arguments init->ProcessOptions(init_file, "test"); param->set_agent_stats_interval(AgentParam::kAgentStatsInterval); param->set_flow_stats_interval(AgentParam::kFlowStatsInterval); param->set_vrouter_stats_interval(AgentParam::kVrouterStatsInterval); // Initialize the agent-init control class int introspect_port = 0; Sandesh::InitGeneratorTest("VNSWAgent", "Agent", "Test", "Test", agent->event_manager(), introspect_port, NULL); init->set_ksync_enable(false); init->set_packet_enable(false); init->set_services_enable(false); init->set_create_vhost(false); init->set_uve_enable(true); init->set_vgw_enable(false); init->set_router_id_dep_enable(false); init->set_ovs_init(ovs_init); param->set_test_mode(true); agent->set_ksync_sync_mode(true); // Initialize agent and kick start initialization init->Start(); WaitForInitDone(agent); client->Init(); client->WaitForIdle(); client->SetFlowFlushExclusionPolicy(); client->SetFlowAgeExclusionPolicy(); AsioRun(); return client; } <|endoftext|>
<commit_before>/* * Copyright (C) 2019 The Android Open Source Project * * 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 "tools/trace_to_text/trace_to_json.h" #include <stdio.h> #include "perfetto/base/logging.h" #include "perfetto/ext/base/scoped_file.h" #include "perfetto/ext/base/temp_file.h" #include "perfetto/trace_processor/trace_processor.h" #include "tools/trace_to_text/utils.h" namespace perfetto { namespace trace_to_text { namespace { const char kTraceHeader[] = R"({ "traceEvents": [], )"; const char kTraceFooter[] = R"(, "controllerTraceDataKey": "systraceController" })"; bool ExportUserspaceEvents(trace_processor::TraceProcessor* tp, TraceWriter* writer) { fprintf(stderr, "Converting userspace events%c", kProgressChar); fflush(stderr); // Write userspace trace to a temporary file. // TODO(eseckler): Support streaming the result out of TP directly instead. auto file = base::TempFile::Create(); char query[100]; sprintf(query, "select export_json(\"%s\")", file.path().c_str()); auto it = tp->ExecuteQuery(query); if (!it.Next()) { auto status = it.Status(); PERFETTO_CHECK(!status.ok()); PERFETTO_ELOG("Could not convert userspace events: %s", status.c_message()); return false; } base::ScopedFstream source(fopen(file.path().c_str(), "r")); if (!source) { PERFETTO_ELOG("Could not convert userspace events: Couldn't read file %s", file.path().c_str()); return false; } char buf[BUFSIZ]; size_t size; while ((size = fread(buf, sizeof(char), BUFSIZ, *source)) > 0) { // Skip writing the closing brace since we'll append system trace data. if (feof(*source)) size--; writer->Write(buf, size); } return true; } } // namespace int TraceToJson(std::istream* input, std::ostream* output, bool compress, Keep truncate_keep) { std::unique_ptr<TraceWriter> trace_writer( compress ? new DeflateTraceWriter(output) : new TraceWriter(output)); trace_processor::Config config; std::unique_ptr<trace_processor::TraceProcessor> tp = trace_processor::TraceProcessor::CreateInstance(config); if (!ReadTrace(tp.get(), input)) return 1; tp->NotifyEndOfFile(); // TODO(eseckler): Support truncation of userspace event data. if (ExportUserspaceEvents(tp.get(), trace_writer.get())) { trace_writer->Write(",\n"); } else { trace_writer->Write(kTraceHeader); } int ret = ExtractSystrace(tp.get(), trace_writer.get(), /*wrapped_in_json=*/true, truncate_keep); if (ret) return ret; trace_writer->Write(kTraceFooter); return 0; } } // namespace trace_to_text } // namespace perfetto <commit_msg>traceconv: ignore userspace events for traces with Android data<commit_after>/* * Copyright (C) 2019 The Android Open Source Project * * 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 "tools/trace_to_text/trace_to_json.h" #include <stdio.h> #include "perfetto/base/logging.h" #include "perfetto/ext/base/scoped_file.h" #include "perfetto/ext/base/temp_file.h" #include "perfetto/trace_processor/trace_processor.h" #include "tools/trace_to_text/utils.h" namespace perfetto { namespace trace_to_text { namespace { const char kTraceHeader[] = R"({ "traceEvents": [], )"; const char kTraceFooter[] = R"(, "controllerTraceDataKey": "systraceController" })"; bool ExportUserspaceEvents(trace_processor::TraceProcessor* tp, TraceWriter* writer) { // First check if there are any non-Chrome events. If so then bail out. // TODO(eseckler): support merged Android/Chrome traces. static const char kSystemEventsQuery[] = "select count(1) from raw " "where name not like 'chrome.%' " "and name not like 'track_event.%'"; auto raw_it = tp->ExecuteQuery(kSystemEventsQuery); if (!raw_it.Next()) { auto status = raw_it.Status(); PERFETTO_ELOG("Failed when counting non-Chrome raw events %s.", status.c_message()); return false; } auto count_val = raw_it.Get(0); PERFETTO_CHECK(count_val.type == trace_processor::SqlValue::kLong); PERFETTO_DCHECK(!raw_it.Next()); if (count_val.long_value > 0) return false; fprintf(stderr, "Converting userspace events%c", kProgressChar); fflush(stderr); // Write userspace trace to a temporary file. // TODO(eseckler): Support streaming the result out of TP directly instead. auto file = base::TempFile::Create(); char query[100]; sprintf(query, "select export_json(\"%s\")", file.path().c_str()); auto it = tp->ExecuteQuery(query); if (!it.Next()) { auto status = it.Status(); PERFETTO_CHECK(!status.ok()); PERFETTO_ELOG("Could not convert userspace events: %s", status.c_message()); return false; } base::ScopedFstream source(fopen(file.path().c_str(), "r")); if (!source) { PERFETTO_ELOG("Could not convert userspace events: Couldn't read file %s", file.path().c_str()); return false; } char buf[BUFSIZ]; size_t size; while ((size = fread(buf, sizeof(char), BUFSIZ, *source)) > 0) { // Skip writing the closing brace since we'll append system trace data. if (feof(*source)) size--; writer->Write(buf, size); } return true; } } // namespace int TraceToJson(std::istream* input, std::ostream* output, bool compress, Keep truncate_keep) { std::unique_ptr<TraceWriter> trace_writer( compress ? new DeflateTraceWriter(output) : new TraceWriter(output)); trace_processor::Config config; std::unique_ptr<trace_processor::TraceProcessor> tp = trace_processor::TraceProcessor::CreateInstance(config); if (!ReadTrace(tp.get(), input)) return 1; tp->NotifyEndOfFile(); // TODO(eseckler): Support truncation of userspace event data. if (ExportUserspaceEvents(tp.get(), trace_writer.get())) { trace_writer->Write(",\n"); } else { trace_writer->Write(kTraceHeader); } int ret = ExtractSystrace(tp.get(), trace_writer.get(), /*wrapped_in_json=*/true, truncate_keep); if (ret) return ret; trace_writer->Write(kTraceFooter); return 0; } } // namespace trace_to_text } // namespace perfetto <|endoftext|>
<commit_before>#ifdef _WIN32 #define M_PI 3.14 #endif #include <cmath> #include <iostream> #include <fstream> #include "Body.hpp" #define G 20 // TODO: Get the right number #define DENSITY 100 // kg/m^3 using namespace sf; using namespace std; Body::Body(Vector2f pos, uint64_t m, Vector2f dir) : position(pos), direction(dir), mass(m) { if (mass <= 0) { cout << "FATAL ERROR: MASS <= 0" << endl; } cout << "MASS=" << mass << endl; // Radius float volume = mass / DENSITY; radius = cbrt((3*volume)/(4*M_PI)); if (radius < 1) { radius = 1; } Color color(Color::White); Color clear_yellow(212, 193, 106); Color brown(175, 75, 0); if (mass <= 10000) { color = interpolate(Color::White, clear_yellow, mass / 10000.0f); } else if (mass <= 100000) { color = interpolate(clear_yellow, brown, mass / 100000.0f); } else if (mass >= 1000000) { color = Color::Red; } else { color = interpolate(brown, Color::Red, mass / 1000000.0f); } shape.setRadius(radius); shape.setFillColor(color); } void Body::move(float dt) { position += direction * dt; } void Body::applyGravityOf(const Body &b, float dt) { float r = getDistanceTo(b); if (r <= 0) { cout << "return" << endl; return; } float F = (G*mass*b.mass) / (r*r); // Make the force proportional to the mass F /= mass; // Get the unit vector to the other body Vector2f target(b.position.x+b.radius, b.position.y+b.radius); Vector2f center(position.x+radius, position.y+radius); Vector2f to_Body(target - center); to_Body = to_Body / r; // Apply the force in the direction of the other body direction += (to_Body * F) * dt; } float Body::getDistanceTo(const Body &b) { Vector2f target(b.position.x+b.radius, b.position.y+b.radius); Vector2f center(position.x+radius, position.y+radius); Vector2f c = target - center; return sqrt(c.x*c.x + c.y * c.y); } void Body::draw(RenderWindow &window) { shape.setPosition(position); window.draw(shape); } bool Body::collideWith(const Body &p) { Vector2f a = position; a.x += radius; a.y += radius; Vector2f b = p.position; b.x += p.radius; b.y += p.radius; float d = (a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y); if (d <= (radius+p.radius)*(radius+p.radius)) return true; return false; } bool Body::contains(const Vector2f &point) { Vector2f center(position.x+radius, position.y+radius); return (point.x-center.x)*(point.x-center.x) + (point.y-center.y)*(point.y-center.y) <= radius*radius; } // Handy helper fonctions /* * ratio is a number between 0.0f and 1.0f */ Color interpolate(Color a, Color b, float ratio) { Color c; c.r = (b.r-a.r) * ratio + a.r; c.g = (b.g-a.g) * ratio + a.g; c.b = (b.b-a.b) * ratio + a.b; return c; } <commit_msg>Delete Body.cpp<commit_after><|endoftext|>
<commit_before>// This file is part of the dune-stuff project: // https://users.dune-project.org/projects/dune-stuff // Copyright holders: Rene Milk, Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_STUFF_COMMON_FLOAT_CMP_HH #define DUNE_STUFF_COMMON_FLOAT_CMP_HH #include <dune/stuff/common/disable_warnings.hh> # include <dune/common/float_cmp.hh> #include <dune/stuff/common/reenable_warnings.hh> #include <dune/common/dynvector.hh> #include <dune/common/fvector.hh> #if HAVE_EIGEN # include <dune/stuff/la/container/eigen.hh> #endif #include <type_traits> namespace Dune { namespace Stuff { namespace Common { namespace FloatCmp { #define DUNE_STUFF_GENERATE_VECTOR_COMPARATOR(id) \ template< class T, Dune::FloatCmp::CmpStyle style = Dune::FloatCmp::defaultCmpStyle > \ typename std::enable_if< std::is_arithmetic< T >::value, bool >::type \ id (const T& first, \ const T& second, \ typename Dune::FloatCmp::EpsilonType< T >::Type epsilon = Dune::FloatCmp::DefaultEpsilon< T, style >::value()) \ { \ return Dune::FloatCmp:: id < T, style >(first, second, epsilon); \ } \ \ template< class T, Dune::FloatCmp::CmpStyle style = Dune::FloatCmp::defaultCmpStyle > \ typename std::enable_if< std::is_arithmetic< T >::value, bool >::type \ id (const std::vector< T >& first, \ const std::vector< T >& second, \ typename Dune::FloatCmp::EpsilonType< T >::Type epsilon = Dune::FloatCmp::DefaultEpsilon< T, style >::value()) \ { \ assert(first.size() == second.size()); \ for (size_t ii = 0; ii < first.size(); ++ii) \ if (!Dune::FloatCmp:: id < T, style >(first[ii], second[ii], epsilon)) \ return false; \ return true; \ } \ \ template< class T, Dune::FloatCmp::CmpStyle style = Dune::FloatCmp::defaultCmpStyle > \ bool id (const Dune::DynamicVector< T >& first, \ const Dune::DynamicVector< T >& second, \ typename Dune::FloatCmp::EpsilonType< T >::Type epsilon = Dune::FloatCmp::DefaultEpsilon< T, style >::value()) \ { \ assert(first.size() == second.size()); \ for (size_t ii = 0; ii < first.size(); ++ii) \ if (!Dune::FloatCmp:: id < T, style >(first[ii], second[ii], epsilon)) \ return false; \ return true; \ } \ \ template< class T, int size, Dune::FloatCmp::CmpStyle style = Dune::FloatCmp::defaultCmpStyle > \ bool id (const Dune::FieldVector< T, size >& first, \ const Dune::FieldVector< T, size >& second, \ typename Dune::FloatCmp::EpsilonType< T >::Type epsilon = Dune::FloatCmp::DefaultEpsilon< T, style >::value()) \ { \ for (size_t ii = 0; ii < size; ++ii) \ if (!Dune::FloatCmp:: id < T, style >(first[ii], second[ii], epsilon)) \ return false; \ return true; \ } // DUNE_STUFF_GENERATE_VECTOR_COMPARATOR DUNE_STUFF_GENERATE_VECTOR_COMPARATOR(eq) DUNE_STUFF_GENERATE_VECTOR_COMPARATOR(ne) DUNE_STUFF_GENERATE_VECTOR_COMPARATOR(gt) DUNE_STUFF_GENERATE_VECTOR_COMPARATOR(lt) DUNE_STUFF_GENERATE_VECTOR_COMPARATOR(ge) DUNE_STUFF_GENERATE_VECTOR_COMPARATOR(le) #undef DUNE_STUFF_GENERATE_VECTOR_COMPARATOR #if HAVE_EIGEN #define DUNE_STUFF_GENERATE_VECTOR_COMPARATOR(id) \ template< class T, Dune::FloatCmp::CmpStyle style = Dune::FloatCmp::defaultCmpStyle > \ bool id (const Dune::Stuff::LA::EigenDenseVector< T >& first, \ const Dune::Stuff::LA::EigenDenseVector< T >& second, \ typename Dune::FloatCmp::EpsilonType< T >::Type epsilon = Dune::FloatCmp::DefaultEpsilon< T, style >::value()) \ { \ assert(first.size() == second.size()); \ for (size_t ii = 0; ii < first.size(); ++ii) \ if (!Dune::FloatCmp:: id < T, style >(first.backend()[ii], second.backend()[ii], epsilon)) \ return false; \ return true; \ } \ \ template< class T, Dune::FloatCmp::CmpStyle style = Dune::FloatCmp::defaultCmpStyle > \ bool id (const Dune::DynamicVector< T >& first, \ const Dune::Stuff::LA::EigenDenseVector< T >& second, \ typename Dune::FloatCmp::EpsilonType< T >::Type epsilon = Dune::FloatCmp::DefaultEpsilon< T, style >::value()) \ { \ assert(first.size() == second.size()); \ for (size_t ii = 0; ii < first.size(); ++ii) \ if (!Dune::FloatCmp:: id < T, style >(first[ii], second.backend()[ii], epsilon)) \ return false; \ return true; \ } \ \ template< class T, Dune::FloatCmp::CmpStyle style = Dune::FloatCmp::defaultCmpStyle > \ bool id (const Dune::Stuff::LA::EigenDenseVector< T >& first, \ const Dune::DynamicVector< T >& second, \ typename Dune::FloatCmp::EpsilonType< T >::Type epsilon = Dune::FloatCmp::DefaultEpsilon< T, style >::value()) \ { \ assert(first.size() == second.size()); \ for (size_t ii = 0; ii < first.size(); ++ii) \ if (!Dune::FloatCmp:: id< T, style >(first[ii], second.backend()[ii], epsilon)) \ return false; \ return true; \ } // DUNE_STUFF_GENERATE_VECTOR_COMPARATOR DUNE_STUFF_GENERATE_VECTOR_COMPARATOR(eq) DUNE_STUFF_GENERATE_VECTOR_COMPARATOR(ne) DUNE_STUFF_GENERATE_VECTOR_COMPARATOR(gt) DUNE_STUFF_GENERATE_VECTOR_COMPARATOR(lt) DUNE_STUFF_GENERATE_VECTOR_COMPARATOR(ge) DUNE_STUFF_GENERATE_VECTOR_COMPARATOR(le) #undef DUNE_STUFF_GENERATE_VECTOR_COMPARATOR #endif // HAVE_EIGEN } // namespace FloatCmp } // namespace Common } // namespace Stuff } // namespace Dune #endif // DUNE_STUFF_COMMON_FLOAT_CMP_HH <commit_msg>[common.float_cmp] allow comparison of LA::VectorInterface vectors<commit_after>// This file is part of the dune-stuff project: // https://users.dune-project.org/projects/dune-stuff // Copyright holders: Rene Milk, Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_STUFF_COMMON_FLOAT_CMP_HH #define DUNE_STUFF_COMMON_FLOAT_CMP_HH #include <dune/stuff/common/disable_warnings.hh> # include <dune/common/float_cmp.hh> #include <dune/stuff/common/reenable_warnings.hh> #include <dune/common/dynvector.hh> #include <dune/common/fvector.hh> #include <dune/stuff/la/container/interfaces.hh> #include <type_traits> namespace Dune { namespace Stuff { namespace Common { namespace FloatCmp { #define DUNE_STUFF_GENERATE_VECTOR_COMPARATOR(id) \ template< class T, Dune::FloatCmp::CmpStyle style = Dune::FloatCmp::defaultCmpStyle > \ typename std::enable_if< std::is_arithmetic< T >::value, bool >::type \ id (const T& first, \ const T& second, \ typename Dune::FloatCmp::EpsilonType< T >::Type epsilon = Dune::FloatCmp::DefaultEpsilon< T, style >::value()) \ { \ return Dune::FloatCmp:: id < T, style >(first, second, epsilon); \ } \ \ template< class T, Dune::FloatCmp::CmpStyle style = Dune::FloatCmp::defaultCmpStyle > \ typename std::enable_if< std::is_arithmetic< T >::value, bool >::type \ id (const std::vector< T >& first, \ const std::vector< T >& second, \ typename Dune::FloatCmp::EpsilonType< T >::Type epsilon = Dune::FloatCmp::DefaultEpsilon< T, style >::value()) \ { \ assert(first.size() == second.size()); \ for (size_t ii = 0; ii < first.size(); ++ii) \ if (!Dune::FloatCmp:: id < T, style >(first[ii], second[ii], epsilon)) \ return false; \ return true; \ } \ \ template< class T, Dune::FloatCmp::CmpStyle style = Dune::FloatCmp::defaultCmpStyle > \ bool id (const Dune::DynamicVector< T >& first, \ const Dune::DynamicVector< T >& second, \ typename Dune::FloatCmp::EpsilonType< T >::Type epsilon = Dune::FloatCmp::DefaultEpsilon< T, style >::value()) \ { \ assert(first.size() == second.size()); \ for (size_t ii = 0; ii < first.size(); ++ii) \ if (!Dune::FloatCmp:: id < T, style >(first[ii], second[ii], epsilon)) \ return false; \ return true; \ } \ \ template< class T, int size, Dune::FloatCmp::CmpStyle style = Dune::FloatCmp::defaultCmpStyle > \ bool id (const Dune::FieldVector< T, size >& first, \ const Dune::FieldVector< T, size >& second, \ typename Dune::FloatCmp::EpsilonType< T >::Type epsilon = Dune::FloatCmp::DefaultEpsilon< T, style >::value()) \ { \ for (size_t ii = 0; ii < size; ++ii) \ if (!Dune::FloatCmp:: id < T, style >(first[ii], second[ii], epsilon)) \ return false; \ return true; \ } \ template< class F, class S, Dune::FloatCmp::CmpStyle style = Dune::FloatCmp::defaultCmpStyle > \ bool id (const Stuff::LA::VectorInterface< F >& first, \ const Stuff::LA::VectorInterface< S >& second, \ typename Dune::FloatCmp::EpsilonType< typename F::ScalarType >::Type epsilon = Dune::FloatCmp::DefaultEpsilon< typename F::ScalarType, style >::value()) \ { \ assert(first.size() == second.size()); \ for (size_t ii = 0; ii < first.size(); ++ii) \ if (!Dune::FloatCmp:: id < typename F::ScalarType, style >(first[ii], second[ii], epsilon)) \ return false; \ return true; \ } // DUNE_STUFF_GENERATE_VECTOR_COMPARATOR DUNE_STUFF_GENERATE_VECTOR_COMPARATOR(eq) DUNE_STUFF_GENERATE_VECTOR_COMPARATOR(ne) DUNE_STUFF_GENERATE_VECTOR_COMPARATOR(gt) DUNE_STUFF_GENERATE_VECTOR_COMPARATOR(lt) DUNE_STUFF_GENERATE_VECTOR_COMPARATOR(ge) DUNE_STUFF_GENERATE_VECTOR_COMPARATOR(le) #undef DUNE_STUFF_GENERATE_VECTOR_COMPARATOR } // namespace FloatCmp } // namespace Common } // namespace Stuff } // namespace Dune #endif // DUNE_STUFF_COMMON_FLOAT_CMP_HH <|endoftext|>
<commit_before>#include "map/framework.hpp" #include "map/user_mark_container.hpp" #include "drape_frontend/drape_engine.hpp" #include "drape_frontend/tile_key.hpp" #include "drape_frontend/user_mark_shapes.hpp" #include "base/scope_guard.hpp" #include "base/macros.hpp" #include "base/stl_add.hpp" #include "std/algorithm.hpp" //////////////////////////////////////////////////////////////////////// namespace { class FindMarkFunctor { public: FindMarkFunctor(UserMark ** mark, double & minD, m2::AnyRectD const & rect) : m_mark(mark) , m_minD(minD) , m_rect(rect) { m_globalCenter = rect.GlobalCenter(); } void operator()(UserMark * mark) { m2::PointD const & org = mark->GetPivot(); if (m_rect.IsPointInside(org)) { double minDCandidate = m_globalCenter.SquareLength(org); if (minDCandidate < m_minD) { *m_mark = mark; m_minD = minDCandidate; } } } UserMark ** m_mark; double & m_minD; m2::AnyRectD const & m_rect; m2::PointD m_globalCenter; }; df::TileKey CreateTileKey(UserMarkContainer const * cont) { switch (cont->GetType()) { case UserMarkType::API_MARK: return df::GetApiTileKey(); case UserMarkType::SEARCH_MARK: return df::GetSearchTileKey(); case UserMarkType::BOOKMARK_MARK: return df::GetBookmarkTileKey(reinterpret_cast<size_t>(cont)); case UserMarkType::DEBUG_MARK: return df::GetDebugTileKey(); default: ASSERT(false, ()); break; } return df::TileKey(); } size_t const VisibleFlag = 0; size_t const VisibleDirtyFlag = 1; size_t const DrawableFlag = 2; size_t const DrawableDirtyFlag = 3; } UserMarkContainer::UserMarkContainer(double layerDepth, UserMarkType type, Framework & fm) : m_framework(fm) , m_layerDepth(layerDepth) , m_type(type) { m_flags.set(); } UserMarkContainer::~UserMarkContainer() { RequestController().Clear(); ReleaseController(); } UserMark const * UserMarkContainer::FindMarkInRect(m2::AnyRectD const & rect, double & d) const { UserMark * mark = nullptr; if (IsVisible()) { FindMarkFunctor f(&mark, d, rect); for (size_t i = 0; i < m_userMarks.size(); ++i) { if (rect.IsPointInside(m_userMarks[i]->GetPivot())) f(m_userMarks[i].get()); } } return mark; } namespace { unique_ptr<PoiMarkPoint> g_selectionUserMark; unique_ptr<MyPositionMarkPoint> g_myPosition; } UserMarkDLCache::Key UserMarkContainer::GetDefaultKey() const { return UserMarkDLCache::Key(GetTypeName(), graphics::EPosCenter, GetDepth()); } void UserMarkContainer::InitStaticMarks(UserMarkContainer * container) { if (g_selectionUserMark == NULL) g_selectionUserMark.reset(new PoiMarkPoint(container)); if (g_myPosition == NULL) g_myPosition.reset(new MyPositionMarkPoint(container)); } PoiMarkPoint * UserMarkContainer::UserMarkForPoi() { ASSERT(g_selectionUserMark != NULL, ()); return g_selectionUserMark.get(); } MyPositionMarkPoint * UserMarkContainer::UserMarkForMyPostion() { ASSERT(g_myPosition != NULL, ()); return g_myPosition.get(); } UserMarksController & UserMarkContainer::RequestController() { BeginWrite(); return *this; } void UserMarkContainer::ReleaseController() { MY_SCOPE_GUARD(endWriteGuard, [this]{ EndWrite(); }); ref_ptr<df::DrapeEngine> engine = m_framework.GetDrapeEngine(); if (engine == nullptr) return; df::TileKey key = CreateTileKey(this); if (IsVisibleFlagDirty() || IsDrawableFlagDirty()) engine->ChangeVisibilityUserMarksLayer(key, IsVisible() && IsDrawable()); m_flags[VisibleDirtyFlag] = false; m_flags[DrawableDirtyFlag] = false; if (IsDirty()) { if (GetUserPointCount() == 0 && GetUserLineCount() == 0) engine->ClearUserMarksLayer(key); else engine->UpdateUserMarksLayer(key, this); } } size_t UserMarkContainer::GetUserPointCount() const { return m_userMarks.size(); } df::UserPointMark const * UserMarkContainer::GetUserPointMark(size_t index) const { return GetUserMark(index); } size_t UserMarkContainer::GetUserLineCount() const { return 0; } df::UserLineMark const * UserMarkContainer::GetUserLineMark(size_t index) const { UNUSED_VALUE(index); ASSERT(false, ()); return nullptr; } float UserMarkContainer::GetPointDepth() const { return m_layerDepth; } bool UserMarkContainer::IsVisible() const { return m_flags[VisibleFlag]; } bool UserMarkContainer::IsDrawable() const { return m_flags[DrawableFlag]; } UserMark * UserMarkContainer::CreateUserMark(m2::PointD const & ptOrg) { SetDirty(); m_userMarks.push_back(unique_ptr<UserMark>(AllocateUserMark(ptOrg))); return m_userMarks.back().get(); } size_t UserMarkContainer::GetUserMarkCount() const { return GetUserPointCount(); } UserMark const * UserMarkContainer::GetUserMark(size_t index) const { ASSERT_LESS(index, m_userMarks.size(), ()); return m_userMarks[index].get(); } UserMarkType UserMarkContainer::GetType() const { return m_type; } UserMark * UserMarkContainer::GetUserMarkForEdit(size_t index) { SetDirty(); ASSERT_LESS(index, m_userMarks.size(), ()); return m_userMarks[index].get(); } void UserMarkContainer::Clear(size_t skipCount/* = 0*/) { SetDirty(); if (skipCount < m_userMarks.size()) m_userMarks.erase(m_userMarks.begin() + skipCount, m_userMarks.end()); } void UserMarkContainer::SetIsDrawable(bool isDrawable) { if (IsDrawable() != isDrawable) { m_flags[DrawableDirtyFlag] = true; m_flags[DrawableFlag] = isDrawable; } } void UserMarkContainer::SetIsVisible(bool isVisible) { if (IsVisible() != isVisible) { m_flags[VisibleDirtyFlag] = true; m_flags[VisibleFlag] = isVisible; } } bool UserMarkContainer::IsVisibleFlagDirty() { return m_flags[VisibleDirtyFlag]; } bool UserMarkContainer::IsDrawableFlagDirty() { return m_flags[DrawableDirtyFlag]; } namespace { template <class T> void DeleteItem(vector<T> & v, size_t i) { if (i < v.size()) { delete v[i]; v.erase(v.begin() + i); } else { LOG(LWARNING, ("Trying to delete non-existing item at index", i)); } } } void UserMarkContainer::DeleteUserMark(size_t index) { SetDirty(); ASSERT_LESS(index, m_userMarks.size(), ()); if (index < m_userMarks.size()) m_userMarks.erase(m_userMarks.begin() + index); else LOG(LWARNING, ("Trying to delete non-existing item at index", index)); } SearchUserMarkContainer::SearchUserMarkContainer(double layerDepth, Framework & framework) : UserMarkContainer(layerDepth, UserMarkType::SEARCH_MARK, framework) { } UserMark * SearchUserMarkContainer::AllocateUserMark(const m2::PointD & ptOrg) { return new SearchMarkPoint(ptOrg, this); } ApiUserMarkContainer::ApiUserMarkContainer(double layerDepth, Framework & framework) : UserMarkContainer(layerDepth, UserMarkType::API_MARK, framework) { } UserMark * ApiUserMarkContainer::AllocateUserMark(const m2::PointD & ptOrg) { return new ApiMarkPoint(ptOrg, this); } DebugUserMarkContainer::DebugUserMarkContainer(double layerDepth, Framework & framework) : UserMarkContainer(layerDepth, UserMarkType::DEBUG_MARK, framework) { } UserMark * DebugUserMarkContainer::AllocateUserMark(const m2::PointD & ptOrg) { return new DebugMarkPoint(ptOrg, this); } <commit_msg>Review fixes<commit_after>#include "map/framework.hpp" #include "map/user_mark_container.hpp" #include "drape_frontend/drape_engine.hpp" #include "drape_frontend/tile_key.hpp" #include "drape_frontend/user_mark_shapes.hpp" #include "base/scope_guard.hpp" #include "base/macros.hpp" #include "base/stl_add.hpp" #include "std/algorithm.hpp" //////////////////////////////////////////////////////////////////////// namespace { class FindMarkFunctor { public: FindMarkFunctor(UserMark ** mark, double & minD, m2::AnyRectD const & rect) : m_mark(mark) , m_minD(minD) , m_rect(rect) { m_globalCenter = rect.GlobalCenter(); } void operator()(UserMark * mark) { m2::PointD const & org = mark->GetPivot(); if (m_rect.IsPointInside(org)) { double minDCandidate = m_globalCenter.SquareLength(org); if (minDCandidate < m_minD) { *m_mark = mark; m_minD = minDCandidate; } } } UserMark ** m_mark; double & m_minD; m2::AnyRectD const & m_rect; m2::PointD m_globalCenter; }; df::TileKey CreateTileKey(UserMarkContainer const * cont) { switch (cont->GetType()) { case UserMarkType::API_MARK: return df::GetApiTileKey(); case UserMarkType::SEARCH_MARK: return df::GetSearchTileKey(); case UserMarkType::BOOKMARK_MARK: return df::GetBookmarkTileKey(reinterpret_cast<size_t>(cont)); case UserMarkType::DEBUG_MARK: return df::GetDebugTileKey(); } ASSERT(false, ()); return df::TileKey(); } size_t const VisibleFlag = 0; size_t const VisibleDirtyFlag = 1; size_t const DrawableFlag = 2; size_t const DrawableDirtyFlag = 3; } UserMarkContainer::UserMarkContainer(double layerDepth, UserMarkType type, Framework & fm) : m_framework(fm) , m_layerDepth(layerDepth) , m_type(type) { m_flags.set(); } UserMarkContainer::~UserMarkContainer() { RequestController().Clear(); ReleaseController(); } UserMark const * UserMarkContainer::FindMarkInRect(m2::AnyRectD const & rect, double & d) const { UserMark * mark = nullptr; if (IsVisible()) { FindMarkFunctor f(&mark, d, rect); for (size_t i = 0; i < m_userMarks.size(); ++i) { if (rect.IsPointInside(m_userMarks[i]->GetPivot())) f(m_userMarks[i].get()); } } return mark; } namespace { unique_ptr<PoiMarkPoint> g_selectionUserMark; unique_ptr<MyPositionMarkPoint> g_myPosition; } UserMarkDLCache::Key UserMarkContainer::GetDefaultKey() const { return UserMarkDLCache::Key(GetTypeName(), graphics::EPosCenter, GetDepth()); } void UserMarkContainer::InitStaticMarks(UserMarkContainer * container) { if (g_selectionUserMark == NULL) g_selectionUserMark.reset(new PoiMarkPoint(container)); if (g_myPosition == NULL) g_myPosition.reset(new MyPositionMarkPoint(container)); } PoiMarkPoint * UserMarkContainer::UserMarkForPoi() { ASSERT(g_selectionUserMark != NULL, ()); return g_selectionUserMark.get(); } MyPositionMarkPoint * UserMarkContainer::UserMarkForMyPostion() { ASSERT(g_myPosition != NULL, ()); return g_myPosition.get(); } UserMarksController & UserMarkContainer::RequestController() { BeginWrite(); return *this; } void UserMarkContainer::ReleaseController() { MY_SCOPE_GUARD(endWriteGuard, [this]{ EndWrite(); }); ref_ptr<df::DrapeEngine> engine = m_framework.GetDrapeEngine(); if (engine == nullptr) return; df::TileKey key = CreateTileKey(this); if (IsVisibleFlagDirty() || IsDrawableFlagDirty()) engine->ChangeVisibilityUserMarksLayer(key, IsVisible() && IsDrawable()); m_flags[VisibleDirtyFlag] = false; m_flags[DrawableDirtyFlag] = false; if (IsDirty()) { if (GetUserPointCount() == 0 && GetUserLineCount() == 0) engine->ClearUserMarksLayer(key); else engine->UpdateUserMarksLayer(key, this); } } size_t UserMarkContainer::GetUserPointCount() const { return m_userMarks.size(); } df::UserPointMark const * UserMarkContainer::GetUserPointMark(size_t index) const { return GetUserMark(index); } size_t UserMarkContainer::GetUserLineCount() const { return 0; } df::UserLineMark const * UserMarkContainer::GetUserLineMark(size_t index) const { UNUSED_VALUE(index); ASSERT(false, ()); return nullptr; } float UserMarkContainer::GetPointDepth() const { return m_layerDepth; } bool UserMarkContainer::IsVisible() const { return m_flags[VisibleFlag]; } bool UserMarkContainer::IsDrawable() const { return m_flags[DrawableFlag]; } UserMark * UserMarkContainer::CreateUserMark(m2::PointD const & ptOrg) { SetDirty(); m_userMarks.push_back(unique_ptr<UserMark>(AllocateUserMark(ptOrg))); return m_userMarks.back().get(); } size_t UserMarkContainer::GetUserMarkCount() const { return GetUserPointCount(); } UserMark const * UserMarkContainer::GetUserMark(size_t index) const { ASSERT_LESS(index, m_userMarks.size(), ()); return m_userMarks[index].get(); } UserMarkType UserMarkContainer::GetType() const { return m_type; } UserMark * UserMarkContainer::GetUserMarkForEdit(size_t index) { SetDirty(); ASSERT_LESS(index, m_userMarks.size(), ()); return m_userMarks[index].get(); } void UserMarkContainer::Clear(size_t skipCount/* = 0*/) { SetDirty(); if (skipCount < m_userMarks.size()) m_userMarks.erase(m_userMarks.begin() + skipCount, m_userMarks.end()); } void UserMarkContainer::SetIsDrawable(bool isDrawable) { if (IsDrawable() != isDrawable) { m_flags[DrawableDirtyFlag] = true; m_flags[DrawableFlag] = isDrawable; } } void UserMarkContainer::SetIsVisible(bool isVisible) { if (IsVisible() != isVisible) { m_flags[VisibleDirtyFlag] = true; m_flags[VisibleFlag] = isVisible; } } bool UserMarkContainer::IsVisibleFlagDirty() { return m_flags[VisibleDirtyFlag]; } bool UserMarkContainer::IsDrawableFlagDirty() { return m_flags[DrawableDirtyFlag]; } namespace { template <class T> void DeleteItem(vector<T> & v, size_t i) { if (i < v.size()) { delete v[i]; v.erase(v.begin() + i); } else { LOG(LWARNING, ("Trying to delete non-existing item at index", i)); } } } void UserMarkContainer::DeleteUserMark(size_t index) { SetDirty(); ASSERT_LESS(index, m_userMarks.size(), ()); if (index < m_userMarks.size()) m_userMarks.erase(m_userMarks.begin() + index); else LOG(LWARNING, ("Trying to delete non-existing item at index", index)); } SearchUserMarkContainer::SearchUserMarkContainer(double layerDepth, Framework & framework) : UserMarkContainer(layerDepth, UserMarkType::SEARCH_MARK, framework) { } UserMark * SearchUserMarkContainer::AllocateUserMark(const m2::PointD & ptOrg) { return new SearchMarkPoint(ptOrg, this); } ApiUserMarkContainer::ApiUserMarkContainer(double layerDepth, Framework & framework) : UserMarkContainer(layerDepth, UserMarkType::API_MARK, framework) { } UserMark * ApiUserMarkContainer::AllocateUserMark(const m2::PointD & ptOrg) { return new ApiMarkPoint(ptOrg, this); } DebugUserMarkContainer::DebugUserMarkContainer(double layerDepth, Framework & framework) : UserMarkContainer(layerDepth, UserMarkType::DEBUG_MARK, framework) { } UserMark * DebugUserMarkContainer::AllocateUserMark(const m2::PointD & ptOrg) { return new DebugMarkPoint(ptOrg, this); } <|endoftext|>
<commit_before>/******************************************************************************\ * File: frame.cpp * Purpose: Implementation of wxExFrameWithHistory class * Author: Anton van Wezenbeek * RCS-ID: $Id$ * * Copyright (c) 1998-2009 Anton van Wezenbeek * All rights are reserved. Reproduction in whole or part is prohibited * without the written consent of the copyright owner. \******************************************************************************/ #include <wx/wxprec.h> #ifndef WX_PRECOMP #include <wx/wx.h> #endif #include <wx/config.h> #include <wx/tokenzr.h> #include <wx/extension/configdlg.h> #include <wx/extension/frd.h> #include <wx/extension/log.h> #include <wx/extension/util.h> #include <wx/extension/report/frame.h> #include <wx/extension/report/defs.h> #include <wx/extension/report/dir.h> #include <wx/extension/report/listitem.h> #include <wx/extension/report/listviewfile.h> #include <wx/extension/report/process.h> #include <wx/extension/report/stc.h> #include <wx/extension/report/util.h> // The maximal number of files and projects to be supported. const int NUMBER_RECENT_FILES = 25; const int NUMBER_RECENT_PROJECTS = 25; const int ID_RECENT_PROJECT_LOWEST = wxID_FILE1 + NUMBER_RECENT_FILES + 1; BEGIN_EVENT_TABLE(wxExFrameWithHistory, wxExManagedFrame) EVT_CLOSE(wxExFrameWithHistory::OnClose) EVT_IDLE(wxExFrameWithHistory::OnIdle) EVT_MENU(wxID_OPEN, wxExFrameWithHistory::OnCommand) EVT_MENU(ID_TERMINATED_PROCESS, wxExFrameWithHistory::OnCommand) EVT_MENU_RANGE( wxID_FILE1, wxID_FILE1 + NUMBER_RECENT_FILES, wxExFrameWithHistory::OnCommand) EVT_MENU_RANGE( ID_RECENT_PROJECT_LOWEST, ID_RECENT_PROJECT_LOWEST + NUMBER_RECENT_PROJECTS, wxExFrameWithHistory::OnCommand) EVT_MENU_RANGE( ID_EXTENSION_REPORT_LOWEST, ID_EXTENSION_REPORT_HIGHEST, wxExFrameWithHistory::OnCommand) END_EVENT_TABLE() wxExFrameWithHistory::wxExFrameWithHistory(wxWindow* parent, wxWindowID id, const wxString& title, size_t maxFiles, size_t maxProjects, int style) : wxExManagedFrame(parent, id, title, style) , m_FiFDialog(NULL) , m_TextInFiles(_("In files")) , m_TextInFolder(_("In folder")) , m_FileHistory(maxFiles, wxID_FILE1) , m_FileHistoryList(NULL) , m_ProjectHistory(maxProjects, ID_RECENT_PROJECT_LOWEST) , m_Process(NULL) { // There is only support for one history in the config. // We use file history for this, so update project history ourselves. // The order should be inverted, as the last one added is the most recent used. for (int i = m_ProjectHistory.GetMaxFiles() - 1 ; i >=0 ; i--) { SetRecentProject( wxConfigBase::Get()->Read(wxString::Format("RecentProject%d", i))); } #ifdef wxExUSE_EMBEDDED_SQL wxExTool::Get()->AddInfo( ID_TOOL_SQL, _("Executed %ld SQL queries in"), wxExEllipsed(_("&SQL Query Run"))); wxExTool::Get()->AddInfo( ID_TOOL_REPORT_SQL, _("Reported %ld SQL queries in"), _("Report SQL &Query")); #endif } wxExFrameWithHistory::~wxExFrameWithHistory() { if (m_FiFDialog != NULL) { m_FiFDialog->Destroy(); } } void wxExFrameWithHistory::DoRecent( wxFileHistory& history, int index, long flags) { if (history.GetCount() > 0) { const wxString file(history.GetHistoryFile(index)); if (!wxFileExists(file)) { history.RemoveFileFromHistory(index); wxLogMessage(_("Removed not existing file: %s from history"), file.c_str()); } else { OpenFile(file, 0, wxEmptyString, flags); } } } void wxExFrameWithHistory::FindInFiles(wxWindowID dialogid) { const bool replace = (dialogid == ID_REPLACE_IN_FILES); const wxExTool tool = (replace ? ID_TOOL_REPORT_REPLACE: ID_TOOL_REPORT_FIND); if (!wxExTextFileWithListView::SetupTool(tool, this)) { return; } wxExLog::Get()->Log( wxExFindReplaceData::Get()->GetFindReplaceInfoText(replace)); wxExDirTool dir( tool, wxExConfigFirstOf(m_TextInFolder), wxExConfigFirstOf(m_TextInFiles)); dir.FindFiles(); tool.Log( &dir.GetStatistics().GetElements(), wxExConfigFirstOf(m_TextInFolder)); } int wxExFrameWithHistory::FindInFilesDialog(int id) { if (m_FiFDialog != NULL) { m_FiFDialog->Destroy(); m_FiFDialog = NULL; } GetFindString(); std::vector<wxExConfigItem> v; v.push_back( wxExConfigItem(wxExFindReplaceData::Get()->GetTextFindWhat(), CONFIG_COMBOBOX, wxEmptyString, true)); if (id == ID_REPLACE_IN_FILES) { v.push_back(wxExConfigItem( wxExFindReplaceData::Get()->GetTextReplaceWith(), CONFIG_COMBOBOX)); } v.push_back(wxExConfigItem( m_TextInFiles, CONFIG_COMBOBOX, wxEmptyString, true)); v.push_back(wxExConfigItem( m_TextInFolder, CONFIG_COMBOBOXDIR, wxEmptyString, true, 1000)); if (id == ID_REPLACE_IN_FILES) { // Match whole word does not work with replace. std::set<wxString> s; s.insert(wxExFindReplaceData::Get()->GetTextMatchCase()); s.insert(wxExFindReplaceData::Get()->GetTextRegEx()); v.push_back(wxExConfigItem(s)); } else { v.push_back(wxExConfigItem(wxExFindReplaceData::Get()->GetInfo())); } m_FiFDialog = new wxExConfigDialog(this, v, (id == ID_REPLACE_IN_FILES ? _("Replace In Files"): _("Find In Files")), 0, 1, wxOK | wxCANCEL, id); return m_FiFDialog->Show(); } void wxExFrameWithHistory::OnClose(wxCloseEvent& event) { if (event.CanVeto() && m_Process != NULL) { if (m_Process->IsRunning()) { wxLogMessage(_("Process is running")); event.Veto(); return; } } wxDELETE(m_Process); m_FileHistory.Save(*wxConfigBase::Get()); for (size_t i = 0; i < m_ProjectHistory.GetCount(); i++) { wxConfigBase::Get()->Write( wxString::Format("RecentProject%d", i), m_ProjectHistory.GetHistoryFile(i)); } event.Skip(); } void wxExFrameWithHistory::OnCommand(wxCommandEvent& event) { if (event.GetId() >= wxID_FILE1 && event.GetId() <= wxID_FILE1 + NUMBER_RECENT_FILES) { DoRecent(m_FileHistory, event.GetId() - wxID_FILE1); } else if (event.GetId() >= ID_RECENT_PROJECT_LOWEST && event.GetId() <= ID_RECENT_PROJECT_LOWEST + NUMBER_RECENT_PROJECTS) { DoRecent(m_ProjectHistory, event.GetId() - ID_RECENT_PROJECT_LOWEST, wxExSTCWithFrame::STC_WIN_IS_PROJECT); } else { switch (event.GetId()) { case wxID_OPEN: if (!event.GetString().empty()) { wxArrayString files; wxStringTokenizer tkz(event.GetString()); auto* stc = GetSTC(); while (tkz.HasMoreTokens()) { const wxString token = tkz.GetNextToken(); wxFileName file(token); if (file.IsRelative() && stc != NULL) { file.MakeAbsolute(stc->GetFileName().GetPath()); if (!file.FileExists()) { wxLogError(_("Cannot locate file") + ": " + token); } else { files.Add(file.GetFullPath()); } } else { files.Add(file.GetFullPath()); } } wxExOpenFiles(this, files); } else { wxExOpenFilesDialog(this); } break; case ID_PROJECT_SAVE: { wxExListViewFile* project = GetProject(); if (project != NULL) { project->FileSave(); SetTitle(wxEmptyString, project->GetFileName().GetName()); } } break; case ID_FIND_IN_FILES: case ID_REPLACE_IN_FILES: FindInFilesDialog(event.GetId()); break; case ID_TERMINATED_PROCESS: wxBell(); wxDELETE(m_Process); break; default: wxFAIL; } } } void wxExFrameWithHistory::OnCommandConfigDialog( wxWindowID dialogid, int commandid) { switch (commandid) { case wxID_CANCEL: if (wxExDir::GetIsBusy()) { wxExDir::Cancel(); #if wxUSE_STATUSBAR wxExFrame::StatusText(_("Cancelled")); #endif } break; case wxID_OK: switch (dialogid) { case wxID_ADD: GetProject()->AddItems(); break; case ID_FIND_IN_FILES: case ID_REPLACE_IN_FILES: FindInFiles(dialogid); break; default: wxFAIL; } break; default: wxFAIL; } } void wxExFrameWithHistory::OnIdle(wxIdleEvent& event) { event.Skip(); auto* stc = GetFocusedSTC(); auto* project = GetProject(); const wxString title(GetTitle()); const wxUniChar indicator('*'); if ((project != NULL && project->GetContentsChanged()) || // using GetContentsChanged gives assert in vcs dialog (stc != NULL && stc->GetModify())) { // Project or editor changed, add indicator if not yet done. if (title.Last() != indicator) { wxFrame::SetTitle(title + " " + indicator); } } else { // Project or editor not changed, remove indicator if not yet done. if (title.Last() == indicator) { wxFrame::SetTitle(title.substr(0, title.length() - 2)); } } } bool wxExFrameWithHistory::OpenFile( const wxExFileName& filename, int line_number, const wxString& match, long flags) { if (wxExManagedFrame::OpenFile(filename, line_number, match, flags)) { SetRecentFile(filename.GetFullPath()); return true; } return false; } int wxExFrameWithHistory::ProcessConfigDialog( wxWindow* parent, const wxString& title) const { return wxExProcess::ConfigDialog(parent, title); } bool wxExFrameWithHistory::ProcessIsRunning() const { return (m_Process != NULL && m_Process->IsRunning()); } bool wxExFrameWithHistory::ProcessIsSelected() const { return wxExProcess::IsSelected(); } bool wxExFrameWithHistory::ProcessRun(const wxString& command) { wxASSERT(m_Process == NULL); if ((m_Process = new wxExProcess(this, command)) != NULL) { if (m_Process->Execute() > 0) { return true; } wxDELETE(m_Process); } return false; } bool wxExFrameWithHistory::ProcessStop() { if (m_Process->IsRunning()) { if (m_Process->Kill() == wxKILL_ERROR) { // Even if the process could not be killed, set it to NULL, as it is deleted. wxFAIL; m_Process = NULL; return false; } else { m_Process = NULL; return true; } } return true; } void wxExFrameWithHistory::SetRecentFile(const wxString& file) { if (!file.empty()) { m_FileHistory.AddFileToHistory(file); if (m_FileHistoryList != NULL) { wxExListItem item(m_FileHistoryList, file); item.Insert((long)0); if (m_FileHistoryList->GetItemCount() > 1) { for (auto i = m_FileHistoryList->GetItemCount() - 1; i >= 1 ; i--) { wxExListItem item(m_FileHistoryList, i); if (item.GetFileName().GetFullPath() == file) { m_FileHistoryList->DeleteItem(i); } } } } } } void wxExFrameWithHistory::SetTitle( const wxString& file, const wxString& project) { // If one of the strings is empty, try to get a better string. wxString better_file(file); wxString better_project(project); if (better_file.empty()) { auto* stc = GetSTC(); if (stc != NULL) { better_file = stc->GetFileName().GetFullPath(); } } if (better_project.empty()) { wxExListViewFile* lv = (wxExListViewFile*)GetListView(); if (lv != NULL && lv->GetType() == wxExListViewStandard::LIST_FILE) { better_project = lv->GetFileName().GetName(); } } // And now update the title. if (better_file.empty() && better_project.empty()) { wxExFrame::SetTitle(wxTheApp->GetAppName()); } else { const wxString sep = (!better_file.empty() && !better_project.empty() ? wxString(" - "): wxString(wxEmptyString)); wxExFrame::SetTitle(better_file + sep + better_project); } } void wxExFrameWithHistory::UseFileHistory(wxWindowID id, wxMenu* menu) { UseHistory(id, menu, m_FileHistory); // We can load file history now. m_FileHistory.Load(*wxConfigBase::Get()); } void wxExFrameWithHistory::UseFileHistoryList(wxExListView* list) { m_FileHistoryList = list; m_FileHistoryList->Hide(); // Add all (existing) items from FileHistory. for (size_t i = 0; i < m_FileHistory.GetCount(); i++) { wxExListItem item( m_FileHistoryList, m_FileHistory.GetHistoryFile(i)); if (item.GetFileName().GetStat().IsOk()) { item.Insert(); } } } void wxExFrameWithHistory::UseHistory( wxWindowID id, wxMenu* menu, wxFileHistory& history) { wxMenu* submenu = new wxMenu; menu->Append(id, _("Open &Recent"), submenu); history.UseMenu(submenu); } void wxExFrameWithHistory::UseProjectHistory(wxWindowID id, wxMenu* menu) { UseHistory(id, menu, m_ProjectHistory); // And add the files to the menu. m_ProjectHistory.AddFilesToMenu(); } <commit_msg>fixed crash when stopping not running process<commit_after>/******************************************************************************\ * File: frame.cpp * Purpose: Implementation of wxExFrameWithHistory class * Author: Anton van Wezenbeek * RCS-ID: $Id$ * * Copyright (c) 1998-2009 Anton van Wezenbeek * All rights are reserved. Reproduction in whole or part is prohibited * without the written consent of the copyright owner. \******************************************************************************/ #include <wx/wxprec.h> #ifndef WX_PRECOMP #include <wx/wx.h> #endif #include <wx/config.h> #include <wx/tokenzr.h> #include <wx/extension/configdlg.h> #include <wx/extension/frd.h> #include <wx/extension/log.h> #include <wx/extension/util.h> #include <wx/extension/report/frame.h> #include <wx/extension/report/defs.h> #include <wx/extension/report/dir.h> #include <wx/extension/report/listitem.h> #include <wx/extension/report/listviewfile.h> #include <wx/extension/report/process.h> #include <wx/extension/report/stc.h> #include <wx/extension/report/util.h> // The maximal number of files and projects to be supported. const int NUMBER_RECENT_FILES = 25; const int NUMBER_RECENT_PROJECTS = 25; const int ID_RECENT_PROJECT_LOWEST = wxID_FILE1 + NUMBER_RECENT_FILES + 1; BEGIN_EVENT_TABLE(wxExFrameWithHistory, wxExManagedFrame) EVT_CLOSE(wxExFrameWithHistory::OnClose) EVT_IDLE(wxExFrameWithHistory::OnIdle) EVT_MENU(wxID_OPEN, wxExFrameWithHistory::OnCommand) EVT_MENU(ID_TERMINATED_PROCESS, wxExFrameWithHistory::OnCommand) EVT_MENU_RANGE( wxID_FILE1, wxID_FILE1 + NUMBER_RECENT_FILES, wxExFrameWithHistory::OnCommand) EVT_MENU_RANGE( ID_RECENT_PROJECT_LOWEST, ID_RECENT_PROJECT_LOWEST + NUMBER_RECENT_PROJECTS, wxExFrameWithHistory::OnCommand) EVT_MENU_RANGE( ID_EXTENSION_REPORT_LOWEST, ID_EXTENSION_REPORT_HIGHEST, wxExFrameWithHistory::OnCommand) END_EVENT_TABLE() wxExFrameWithHistory::wxExFrameWithHistory(wxWindow* parent, wxWindowID id, const wxString& title, size_t maxFiles, size_t maxProjects, int style) : wxExManagedFrame(parent, id, title, style) , m_FiFDialog(NULL) , m_TextInFiles(_("In files")) , m_TextInFolder(_("In folder")) , m_FileHistory(maxFiles, wxID_FILE1) , m_FileHistoryList(NULL) , m_ProjectHistory(maxProjects, ID_RECENT_PROJECT_LOWEST) , m_Process(NULL) { // There is only support for one history in the config. // We use file history for this, so update project history ourselves. // The order should be inverted, as the last one added is the most recent used. for (int i = m_ProjectHistory.GetMaxFiles() - 1 ; i >=0 ; i--) { SetRecentProject( wxConfigBase::Get()->Read(wxString::Format("RecentProject%d", i))); } #ifdef wxExUSE_EMBEDDED_SQL wxExTool::Get()->AddInfo( ID_TOOL_SQL, _("Executed %ld SQL queries in"), wxExEllipsed(_("&SQL Query Run"))); wxExTool::Get()->AddInfo( ID_TOOL_REPORT_SQL, _("Reported %ld SQL queries in"), _("Report SQL &Query")); #endif } wxExFrameWithHistory::~wxExFrameWithHistory() { if (m_FiFDialog != NULL) { m_FiFDialog->Destroy(); } } void wxExFrameWithHistory::DoRecent( wxFileHistory& history, int index, long flags) { if (history.GetCount() > 0) { const wxString file(history.GetHistoryFile(index)); if (!wxFileExists(file)) { history.RemoveFileFromHistory(index); wxLogMessage(_("Removed not existing file: %s from history"), file.c_str()); } else { OpenFile(file, 0, wxEmptyString, flags); } } } void wxExFrameWithHistory::FindInFiles(wxWindowID dialogid) { const bool replace = (dialogid == ID_REPLACE_IN_FILES); const wxExTool tool = (replace ? ID_TOOL_REPORT_REPLACE: ID_TOOL_REPORT_FIND); if (!wxExTextFileWithListView::SetupTool(tool, this)) { return; } wxExLog::Get()->Log( wxExFindReplaceData::Get()->GetFindReplaceInfoText(replace)); wxExDirTool dir( tool, wxExConfigFirstOf(m_TextInFolder), wxExConfigFirstOf(m_TextInFiles)); dir.FindFiles(); tool.Log( &dir.GetStatistics().GetElements(), wxExConfigFirstOf(m_TextInFolder)); } int wxExFrameWithHistory::FindInFilesDialog(int id) { if (m_FiFDialog != NULL) { m_FiFDialog->Destroy(); m_FiFDialog = NULL; } GetFindString(); std::vector<wxExConfigItem> v; v.push_back( wxExConfigItem(wxExFindReplaceData::Get()->GetTextFindWhat(), CONFIG_COMBOBOX, wxEmptyString, true)); if (id == ID_REPLACE_IN_FILES) { v.push_back(wxExConfigItem( wxExFindReplaceData::Get()->GetTextReplaceWith(), CONFIG_COMBOBOX)); } v.push_back(wxExConfigItem( m_TextInFiles, CONFIG_COMBOBOX, wxEmptyString, true)); v.push_back(wxExConfigItem( m_TextInFolder, CONFIG_COMBOBOXDIR, wxEmptyString, true, 1000)); if (id == ID_REPLACE_IN_FILES) { // Match whole word does not work with replace. std::set<wxString> s; s.insert(wxExFindReplaceData::Get()->GetTextMatchCase()); s.insert(wxExFindReplaceData::Get()->GetTextRegEx()); v.push_back(wxExConfigItem(s)); } else { v.push_back(wxExConfigItem(wxExFindReplaceData::Get()->GetInfo())); } m_FiFDialog = new wxExConfigDialog(this, v, (id == ID_REPLACE_IN_FILES ? _("Replace In Files"): _("Find In Files")), 0, 1, wxOK | wxCANCEL, id); return m_FiFDialog->Show(); } void wxExFrameWithHistory::OnClose(wxCloseEvent& event) { if (event.CanVeto() && m_Process != NULL) { if (m_Process->IsRunning()) { wxLogMessage(_("Process is running")); event.Veto(); return; } } wxDELETE(m_Process); m_FileHistory.Save(*wxConfigBase::Get()); for (size_t i = 0; i < m_ProjectHistory.GetCount(); i++) { wxConfigBase::Get()->Write( wxString::Format("RecentProject%d", i), m_ProjectHistory.GetHistoryFile(i)); } event.Skip(); } void wxExFrameWithHistory::OnCommand(wxCommandEvent& event) { if (event.GetId() >= wxID_FILE1 && event.GetId() <= wxID_FILE1 + NUMBER_RECENT_FILES) { DoRecent(m_FileHistory, event.GetId() - wxID_FILE1); } else if (event.GetId() >= ID_RECENT_PROJECT_LOWEST && event.GetId() <= ID_RECENT_PROJECT_LOWEST + NUMBER_RECENT_PROJECTS) { DoRecent(m_ProjectHistory, event.GetId() - ID_RECENT_PROJECT_LOWEST, wxExSTCWithFrame::STC_WIN_IS_PROJECT); } else { switch (event.GetId()) { case wxID_OPEN: if (!event.GetString().empty()) { wxArrayString files; wxStringTokenizer tkz(event.GetString()); auto* stc = GetSTC(); while (tkz.HasMoreTokens()) { const wxString token = tkz.GetNextToken(); wxFileName file(token); if (file.IsRelative() && stc != NULL) { file.MakeAbsolute(stc->GetFileName().GetPath()); if (!file.FileExists()) { wxLogError(_("Cannot locate file") + ": " + token); } else { files.Add(file.GetFullPath()); } } else { files.Add(file.GetFullPath()); } } wxExOpenFiles(this, files); } else { wxExOpenFilesDialog(this); } break; case ID_PROJECT_SAVE: { wxExListViewFile* project = GetProject(); if (project != NULL) { project->FileSave(); SetTitle(wxEmptyString, project->GetFileName().GetName()); } } break; case ID_FIND_IN_FILES: case ID_REPLACE_IN_FILES: FindInFilesDialog(event.GetId()); break; case ID_TERMINATED_PROCESS: wxBell(); wxDELETE(m_Process); break; default: wxFAIL; } } } void wxExFrameWithHistory::OnCommandConfigDialog( wxWindowID dialogid, int commandid) { switch (commandid) { case wxID_CANCEL: if (wxExDir::GetIsBusy()) { wxExDir::Cancel(); #if wxUSE_STATUSBAR wxExFrame::StatusText(_("Cancelled")); #endif } break; case wxID_OK: switch (dialogid) { case wxID_ADD: GetProject()->AddItems(); break; case ID_FIND_IN_FILES: case ID_REPLACE_IN_FILES: FindInFiles(dialogid); break; default: wxFAIL; } break; default: wxFAIL; } } void wxExFrameWithHistory::OnIdle(wxIdleEvent& event) { event.Skip(); auto* stc = GetFocusedSTC(); auto* project = GetProject(); const wxString title(GetTitle()); const wxUniChar indicator('*'); if ((project != NULL && project->GetContentsChanged()) || // using GetContentsChanged gives assert in vcs dialog (stc != NULL && stc->GetModify())) { // Project or editor changed, add indicator if not yet done. if (title.Last() != indicator) { wxFrame::SetTitle(title + " " + indicator); } } else { // Project or editor not changed, remove indicator if not yet done. if (title.Last() == indicator) { wxFrame::SetTitle(title.substr(0, title.length() - 2)); } } } bool wxExFrameWithHistory::OpenFile( const wxExFileName& filename, int line_number, const wxString& match, long flags) { if (wxExManagedFrame::OpenFile(filename, line_number, match, flags)) { SetRecentFile(filename.GetFullPath()); return true; } return false; } int wxExFrameWithHistory::ProcessConfigDialog( wxWindow* parent, const wxString& title) const { return wxExProcess::ConfigDialog(parent, title); } bool wxExFrameWithHistory::ProcessIsRunning() const { return (m_Process != NULL && m_Process->IsRunning()); } bool wxExFrameWithHistory::ProcessIsSelected() const { return wxExProcess::IsSelected(); } bool wxExFrameWithHistory::ProcessRun(const wxString& command) { wxASSERT(m_Process == NULL); if ((m_Process = new wxExProcess(this, command)) != NULL) { if (m_Process->Execute() > 0) { return true; } wxDELETE(m_Process); } return false; } bool wxExFrameWithHistory::ProcessStop() { if (m_Process == NULL) { return true; } else if (m_Process->IsRunning()) { if (m_Process->Kill() == wxKILL_ERROR) { // Even if the process could not be killed, set it to NULL, as it is deleted. wxFAIL; m_Process = NULL; return false; } else { m_Process = NULL; return true; } return true; } } void wxExFrameWithHistory::SetRecentFile(const wxString& file) { if (!file.empty()) { m_FileHistory.AddFileToHistory(file); if (m_FileHistoryList != NULL) { wxExListItem item(m_FileHistoryList, file); item.Insert((long)0); if (m_FileHistoryList->GetItemCount() > 1) { for (auto i = m_FileHistoryList->GetItemCount() - 1; i >= 1 ; i--) { wxExListItem item(m_FileHistoryList, i); if (item.GetFileName().GetFullPath() == file) { m_FileHistoryList->DeleteItem(i); } } } } } } void wxExFrameWithHistory::SetTitle( const wxString& file, const wxString& project) { // If one of the strings is empty, try to get a better string. wxString better_file(file); wxString better_project(project); if (better_file.empty()) { auto* stc = GetSTC(); if (stc != NULL) { better_file = stc->GetFileName().GetFullPath(); } } if (better_project.empty()) { wxExListViewFile* lv = (wxExListViewFile*)GetListView(); if (lv != NULL && lv->GetType() == wxExListViewStandard::LIST_FILE) { better_project = lv->GetFileName().GetName(); } } // And now update the title. if (better_file.empty() && better_project.empty()) { wxExFrame::SetTitle(wxTheApp->GetAppName()); } else { const wxString sep = (!better_file.empty() && !better_project.empty() ? wxString(" - "): wxString(wxEmptyString)); wxExFrame::SetTitle(better_file + sep + better_project); } } void wxExFrameWithHistory::UseFileHistory(wxWindowID id, wxMenu* menu) { UseHistory(id, menu, m_FileHistory); // We can load file history now. m_FileHistory.Load(*wxConfigBase::Get()); } void wxExFrameWithHistory::UseFileHistoryList(wxExListView* list) { m_FileHistoryList = list; m_FileHistoryList->Hide(); // Add all (existing) items from FileHistory. for (size_t i = 0; i < m_FileHistory.GetCount(); i++) { wxExListItem item( m_FileHistoryList, m_FileHistory.GetHistoryFile(i)); if (item.GetFileName().GetStat().IsOk()) { item.Insert(); } } } void wxExFrameWithHistory::UseHistory( wxWindowID id, wxMenu* menu, wxFileHistory& history) { wxMenu* submenu = new wxMenu; menu->Append(id, _("Open &Recent"), submenu); history.UseMenu(submenu); } void wxExFrameWithHistory::UseProjectHistory(wxWindowID id, wxMenu* menu) { UseHistory(id, menu, m_ProjectHistory); // And add the files to the menu. m_ProjectHistory.AddFilesToMenu(); } <|endoftext|>
<commit_before>// ======================================================================== // // Copyright 2018-2019 Intel 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 <iterator> #include <memory> #include <random> #include "GLFWOSPRayWindow.h" #include "ospray_testing.h" #include <imgui.h> using namespace ospcommon; OSPGeometry createGroundPlaneGeometry() { OSPGeometry planeGeometry = ospNewGeometry("quads"); struct Vertex { vec3f position; vec3f normal; vec4f color; }; struct QuadIndex { int x; int y; int z; int w; }; std::vector<Vertex> vertices; std::vector<QuadIndex> quadIndices; // ground plane int startingIndex = vertices.size(); // extent of plane in the (x, z) directions const float planeExtent = 1.5f; const vec3f up = vec3f{0.f, 1.f, 0.f}; const vec4f gray = vec4f{0.9f, 0.9f, 0.9f, 0.75f}; vertices.push_back(Vertex{vec3f{-planeExtent, -1.f, -planeExtent}, up, gray}); vertices.push_back(Vertex{vec3f{planeExtent, -1.f, -planeExtent}, up, gray}); vertices.push_back(Vertex{vec3f{planeExtent, -1.f, planeExtent}, up, gray}); vertices.push_back(Vertex{vec3f{-planeExtent, -1.f, planeExtent}, up, gray}); quadIndices.push_back(QuadIndex{ startingIndex, startingIndex + 1, startingIndex + 2, startingIndex + 3}); // stripes on ground plane const float stripeWidth = 0.025f; const float paddedExtent = planeExtent + stripeWidth; const size_t numStripes = 10; const vec4f stripeColor = vec4f{1.0f, 0.1f, 0.1f, 1.f}; for (size_t i = 0; i < numStripes; i++) { // the center coordinate of the stripe, either in the x or z direction const float coord = -planeExtent + float(i) / float(numStripes - 1) * 2.f * planeExtent; // offset the stripes by an epsilon above the ground plane const float yLevel = -1.f + 1e-3f; // x-direction stripes startingIndex = vertices.size(); vertices.push_back(Vertex{ vec3f{-paddedExtent, yLevel, coord - stripeWidth}, up, stripeColor}); vertices.push_back(Vertex{ vec3f{paddedExtent, yLevel, coord - stripeWidth}, up, stripeColor}); vertices.push_back(Vertex{ vec3f{paddedExtent, yLevel, coord + stripeWidth}, up, stripeColor}); vertices.push_back(Vertex{ vec3f{-paddedExtent, yLevel, coord + stripeWidth}, up, stripeColor}); quadIndices.push_back(QuadIndex{startingIndex, startingIndex + 1, startingIndex + 2, startingIndex + 3}); // z-direction stripes startingIndex = vertices.size(); vertices.push_back(Vertex{ vec3f{coord - stripeWidth, yLevel, -paddedExtent}, up, stripeColor}); vertices.push_back(Vertex{ vec3f{coord + stripeWidth, yLevel, -paddedExtent}, up, stripeColor}); vertices.push_back(Vertex{ vec3f{coord + stripeWidth, yLevel, paddedExtent}, up, stripeColor}); vertices.push_back(Vertex{ vec3f{coord - stripeWidth, yLevel, paddedExtent}, up, stripeColor}); quadIndices.push_back(QuadIndex{startingIndex, startingIndex + 1, startingIndex + 2, startingIndex + 3}); } // create OSPRay data objects std::vector<vec3f> positionVector; std::vector<vec3f> normalVector; std::vector<vec4f> colorVector; std::transform(vertices.begin(), vertices.end(), std::back_inserter(positionVector), [](Vertex const &v) { return v.position; }); std::transform(vertices.begin(), vertices.end(), std::back_inserter(normalVector), [](Vertex const &v) { return v.normal; }); std::transform(vertices.begin(), vertices.end(), std::back_inserter(colorVector), [](Vertex const &v) { return v.color; }); OSPData positionData = ospNewData(vertices.size(), OSP_FLOAT3, positionVector.data()); OSPData normalData = ospNewData(vertices.size(), OSP_FLOAT3, normalVector.data()); OSPData colorData = ospNewData(vertices.size(), OSP_FLOAT4, colorVector.data()); OSPData indexData = ospNewData(quadIndices.size(), OSP_INT4, quadIndices.data()); // set vertex / index data on the geometry ospSetData(planeGeometry, "vertex", positionData); ospSetData(planeGeometry, "vertex.normal", normalData); ospSetData(planeGeometry, "vertex.color", colorData); ospSetData(planeGeometry, "index", indexData); // create and assign a material to the geometry OSPMaterial material = ospNewMaterial2("scivis", "OBJMaterial"); ospCommit(material); ospSetMaterial(planeGeometry, material); // finally, commit the geometry ospCommit(planeGeometry); // release handles we no longer need ospRelease(positionData); ospRelease(normalData); ospRelease(colorData); ospRelease(indexData); ospRelease(material); return planeGeometry; } int main(int argc, const char **argv) { // initialize OSPRay; OSPRay parses (and removes) its commandline parameters, // e.g. "--osp:debug" OSPError initError = ospInit(&argc, argv); if (initError != OSP_NO_ERROR) return initError; // set an error callback to catch any OSPRay errors and exit the application ospDeviceSetErrorFunc( ospGetCurrentDevice(), [](OSPError error, const char *errorDetails) { std::cerr << "OSPRay error: " << errorDetails << std::endl; exit(error); }); // create the "world" model which will contain all of our geometries OSPModel world = ospNewModel(); // add in subdivision geometry OSPTestingGeometry subdivisionGeometry = ospTestingNewGeometry("subdivision_cube", "scivis"); ospAddGeometry(world, subdivisionGeometry.geometry); ospRelease(subdivisionGeometry.geometry); // add in a ground plane geometry ospAddGeometry(world, createGroundPlaneGeometry()); // commit the world model ospCommit(world); // create OSPRay renderer OSPRenderer renderer = ospNewRenderer("scivis"); OSPData lightsData = ospTestingNewLights("ambient_and_directional"); ospSetData(renderer, "lights", lightsData); ospRelease(lightsData); ospCommit(renderer); // create a GLFW OSPRay window: this object will create and manage the OSPRay // frame buffer and camera directly auto glfwOSPRayWindow = std::unique_ptr<GLFWOSPRayWindow>(new GLFWOSPRayWindow( vec2i{1024, 768}, box3f(vec3f(-1.f), vec3f(1.f)), world, renderer)); glfwOSPRayWindow->registerImGuiCallback([=]() { static int spp = 1; if (ImGui::SliderInt("spp", &spp, 1, 64)) { ospSet1i(renderer, "spp", spp); ospCommit(renderer); } static float subdivisionLevel = 1.f; if (ImGui::SliderFloat("subdivision level", &subdivisionLevel, 1.f, 25.f)) { ospSet1f(subdivisionGeometry.geometry, "level", subdivisionLevel); ospCommit(subdivisionGeometry.geometry); ospCommit(world); GLFWOSPRayWindow::getActiveWindow()->clearFrameBuffer(); } }); // start the GLFW main loop, which will continuously render glfwOSPRayWindow->mainLoop(); // cleanup remaining objects ospRelease(world); ospRelease(renderer); // cleanly shut OSPRay down ospShutdown(); return 0; } <commit_msg>using ints for subdivision level slider.<commit_after>// ======================================================================== // // Copyright 2018-2019 Intel 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 <iterator> #include <memory> #include <random> #include "GLFWOSPRayWindow.h" #include "ospray_testing.h" #include <imgui.h> using namespace ospcommon; OSPGeometry createGroundPlaneGeometry() { OSPGeometry planeGeometry = ospNewGeometry("quads"); struct Vertex { vec3f position; vec3f normal; vec4f color; }; struct QuadIndex { int x; int y; int z; int w; }; std::vector<Vertex> vertices; std::vector<QuadIndex> quadIndices; // ground plane int startingIndex = vertices.size(); // extent of plane in the (x, z) directions const float planeExtent = 1.5f; const vec3f up = vec3f{0.f, 1.f, 0.f}; const vec4f gray = vec4f{0.9f, 0.9f, 0.9f, 0.75f}; vertices.push_back(Vertex{vec3f{-planeExtent, -1.f, -planeExtent}, up, gray}); vertices.push_back(Vertex{vec3f{planeExtent, -1.f, -planeExtent}, up, gray}); vertices.push_back(Vertex{vec3f{planeExtent, -1.f, planeExtent}, up, gray}); vertices.push_back(Vertex{vec3f{-planeExtent, -1.f, planeExtent}, up, gray}); quadIndices.push_back(QuadIndex{ startingIndex, startingIndex + 1, startingIndex + 2, startingIndex + 3}); // stripes on ground plane const float stripeWidth = 0.025f; const float paddedExtent = planeExtent + stripeWidth; const size_t numStripes = 10; const vec4f stripeColor = vec4f{1.0f, 0.1f, 0.1f, 1.f}; for (size_t i = 0; i < numStripes; i++) { // the center coordinate of the stripe, either in the x or z direction const float coord = -planeExtent + float(i) / float(numStripes - 1) * 2.f * planeExtent; // offset the stripes by an epsilon above the ground plane const float yLevel = -1.f + 1e-3f; // x-direction stripes startingIndex = vertices.size(); vertices.push_back(Vertex{ vec3f{-paddedExtent, yLevel, coord - stripeWidth}, up, stripeColor}); vertices.push_back(Vertex{ vec3f{paddedExtent, yLevel, coord - stripeWidth}, up, stripeColor}); vertices.push_back(Vertex{ vec3f{paddedExtent, yLevel, coord + stripeWidth}, up, stripeColor}); vertices.push_back(Vertex{ vec3f{-paddedExtent, yLevel, coord + stripeWidth}, up, stripeColor}); quadIndices.push_back(QuadIndex{startingIndex, startingIndex + 1, startingIndex + 2, startingIndex + 3}); // z-direction stripes startingIndex = vertices.size(); vertices.push_back(Vertex{ vec3f{coord - stripeWidth, yLevel, -paddedExtent}, up, stripeColor}); vertices.push_back(Vertex{ vec3f{coord + stripeWidth, yLevel, -paddedExtent}, up, stripeColor}); vertices.push_back(Vertex{ vec3f{coord + stripeWidth, yLevel, paddedExtent}, up, stripeColor}); vertices.push_back(Vertex{ vec3f{coord - stripeWidth, yLevel, paddedExtent}, up, stripeColor}); quadIndices.push_back(QuadIndex{startingIndex, startingIndex + 1, startingIndex + 2, startingIndex + 3}); } // create OSPRay data objects std::vector<vec3f> positionVector; std::vector<vec3f> normalVector; std::vector<vec4f> colorVector; std::transform(vertices.begin(), vertices.end(), std::back_inserter(positionVector), [](Vertex const &v) { return v.position; }); std::transform(vertices.begin(), vertices.end(), std::back_inserter(normalVector), [](Vertex const &v) { return v.normal; }); std::transform(vertices.begin(), vertices.end(), std::back_inserter(colorVector), [](Vertex const &v) { return v.color; }); OSPData positionData = ospNewData(vertices.size(), OSP_FLOAT3, positionVector.data()); OSPData normalData = ospNewData(vertices.size(), OSP_FLOAT3, normalVector.data()); OSPData colorData = ospNewData(vertices.size(), OSP_FLOAT4, colorVector.data()); OSPData indexData = ospNewData(quadIndices.size(), OSP_INT4, quadIndices.data()); // set vertex / index data on the geometry ospSetData(planeGeometry, "vertex", positionData); ospSetData(planeGeometry, "vertex.normal", normalData); ospSetData(planeGeometry, "vertex.color", colorData); ospSetData(planeGeometry, "index", indexData); // create and assign a material to the geometry OSPMaterial material = ospNewMaterial2("scivis", "OBJMaterial"); ospCommit(material); ospSetMaterial(planeGeometry, material); // finally, commit the geometry ospCommit(planeGeometry); // release handles we no longer need ospRelease(positionData); ospRelease(normalData); ospRelease(colorData); ospRelease(indexData); ospRelease(material); return planeGeometry; } int main(int argc, const char **argv) { // initialize OSPRay; OSPRay parses (and removes) its commandline parameters, // e.g. "--osp:debug" OSPError initError = ospInit(&argc, argv); if (initError != OSP_NO_ERROR) return initError; // set an error callback to catch any OSPRay errors and exit the application ospDeviceSetErrorFunc( ospGetCurrentDevice(), [](OSPError error, const char *errorDetails) { std::cerr << "OSPRay error: " << errorDetails << std::endl; exit(error); }); // create the "world" model which will contain all of our geometries OSPModel world = ospNewModel(); // add in subdivision geometry OSPTestingGeometry subdivisionGeometry = ospTestingNewGeometry("subdivision_cube", "scivis"); ospAddGeometry(world, subdivisionGeometry.geometry); ospRelease(subdivisionGeometry.geometry); // add in a ground plane geometry ospAddGeometry(world, createGroundPlaneGeometry()); // commit the world model ospCommit(world); // create OSPRay renderer OSPRenderer renderer = ospNewRenderer("scivis"); OSPData lightsData = ospTestingNewLights("ambient_and_directional"); ospSetData(renderer, "lights", lightsData); ospRelease(lightsData); ospCommit(renderer); // create a GLFW OSPRay window: this object will create and manage the OSPRay // frame buffer and camera directly auto glfwOSPRayWindow = std::unique_ptr<GLFWOSPRayWindow>(new GLFWOSPRayWindow( vec2i{1024, 768}, box3f(vec3f(-1.f), vec3f(1.f)), world, renderer)); glfwOSPRayWindow->registerImGuiCallback([=]() { static int spp = 1; if (ImGui::SliderInt("spp", &spp, 1, 64)) { ospSet1i(renderer, "spp", spp); ospCommit(renderer); } static int subdivisionLevel = 5; if (ImGui::SliderInt("subdivision level", &subdivisionLevel, 1, 10)) { ospSet1f(subdivisionGeometry.geometry, "level", subdivisionLevel); ospCommit(subdivisionGeometry.geometry); ospCommit(world); GLFWOSPRayWindow::getActiveWindow()->clearFrameBuffer(); } }); // start the GLFW main loop, which will continuously render glfwOSPRayWindow->mainLoop(); // cleanup remaining objects ospRelease(world); ospRelease(renderer); // cleanly shut OSPRay down ospShutdown(); return 0; } <|endoftext|>
<commit_before>// // Sends a request to call hello() from within a worker. // // Uses SimpleAmqpClient (https://github.com/alanxz/SimpleAmqpClient) to // connect to RabbitMQ and nlohmann/json (https://github.com/nlohmann/json) to // create JSON. // #include <iostream> #include <string> // Access to https://github.com/alanxz/SimpleAmqpClient #include <SimpleAmqpClient/SimpleAmqpClient.h> // Access to https://github.com/nlohmann/json #include <json.hpp> // A convenience type alias. using json = nlohmann::json; int main(int argc, char** argv) { // Two arguments are required: name (string) and age (int). if (argc != 3) { std::cout << "usage: " << argv[0] << " NAME AGE\n"; return 1; } // Parse the arguments. auto name = std::string(argv[1]); auto age = std::stoi(argv[2]); // Create a connection to our AMQP server (RabbitMQ). // // Technically, in AMQP, a single connection can contain multiple channels, // where channels that can be thought of as "lightweight connections that // share a single TCP connection" // (https://www.rabbitmq.com/tutorials/amqp-concepts.html). // However, the used AMQP library only allows creation of channels, not // connections. auto channel = AmqpClient::Channel::Create( /*host*/"localhost", /*port*/5672, /*username*/"guest", /*password*/"guest", /*vhost*/"/" ); // Create a body of the message. // // This assumes that Celery uses JSON as a way of serializing and // de-serializing messages, which is the default. auto body = json{ {name, age}, // args json::object(), // kwargs json::object() // other data }; // Create a message with the above body, serialized into a string. auto msg = AmqpClient::BasicMessage::Create(body.dump()); // As said above, Celery by default uses JSON to serialize and de-serialize // message bodies. msg->ContentType("application/json"); // Assume UTF-8. msg->ContentEncoding("utf-8"); // Celery requires two headers: id and task. The former can be any string // you want (http://docs.celeryproject.org/en/latest/faq.html#can-i-specify-a-custom-task-id), // although Celery uses UUIDs. The latter has to be the name of the task, // as registered in the Python part. // // In a real world scenario, you would probably want generate a random ID ;-). msg->HeaderTable({ {"id", "3149beef-be66-4b0e-ba47-2fc46e4edac3"}, {"task", "tasks.hello"} }); // Send the message to the 'celery' exchange (default) with the 'celery' // routing key (default). This effectively sends the message to the // 'celery' queue because 'celery' is a direct exchange // (https://www.rabbitmq.com/tutorials/amqp-concepts.html). channel->BasicPublish("celery", "celery", msg); return 0; } <commit_msg>en-2017-06-25: The ID should be unique.<commit_after>// // Sends a request to call hello() from within a worker. // // Uses SimpleAmqpClient (https://github.com/alanxz/SimpleAmqpClient) to // connect to RabbitMQ and nlohmann/json (https://github.com/nlohmann/json) to // create JSON. // #include <iostream> #include <string> // Access to https://github.com/alanxz/SimpleAmqpClient #include <SimpleAmqpClient/SimpleAmqpClient.h> // Access to https://github.com/nlohmann/json #include <json.hpp> // A convenience type alias. using json = nlohmann::json; int main(int argc, char** argv) { // Two arguments are required: name (string) and age (int). if (argc != 3) { std::cout << "usage: " << argv[0] << " NAME AGE\n"; return 1; } // Parse the arguments. auto name = std::string(argv[1]); auto age = std::stoi(argv[2]); // Create a connection to our AMQP server (RabbitMQ). // // Technically, in AMQP, a single connection can contain multiple channels, // where channels that can be thought of as "lightweight connections that // share a single TCP connection" // (https://www.rabbitmq.com/tutorials/amqp-concepts.html). // However, the used AMQP library only allows creation of channels, not // connections. auto channel = AmqpClient::Channel::Create( /*host*/"localhost", /*port*/5672, /*username*/"guest", /*password*/"guest", /*vhost*/"/" ); // Create a body of the message. // // This assumes that Celery uses JSON as a way of serializing and // de-serializing messages, which is the default. auto body = json{ {name, age}, // args json::object(), // kwargs json::object() // other data }; // Create a message with the above body, serialized into a string. auto msg = AmqpClient::BasicMessage::Create(body.dump()); // As said above, Celery by default uses JSON to serialize and de-serialize // message bodies. msg->ContentType("application/json"); // Assume UTF-8. msg->ContentEncoding("utf-8"); // Celery requires two headers: id and task. The former can be any unique // string you want // (http://docs.celeryproject.org/en/latest/faq.html#can-i-specify-a-custom-task-id), // although Celery uses UUIDs. The latter has to be the name of the task, // as registered in the Python part. // // In a real world scenario, you would probably want generate a random ID ;-). msg->HeaderTable({ {"id", "3149beef-be66-4b0e-ba47-2fc46e4edac3"}, {"task", "tasks.hello"} }); // Send the message to the 'celery' exchange (default) with the 'celery' // routing key (default). This effectively sends the message to the // 'celery' queue because 'celery' is a direct exchange // (https://www.rabbitmq.com/tutorials/amqp-concepts.html). channel->BasicPublish("celery", "celery", msg); return 0; } <|endoftext|>
<commit_before>#ifndef _RPC_SESSION_H #define _RPC_SESSION_H #include <string> #include <vector> #include <thread> #include <memory> #include <boost/asio.hpp> #include "base/header.hpp" #include "base/atimer.hpp" #include "base/scope_guard.hpp" namespace easyrpc { class rpc_session { public: rpc_session(const rpc_session&) = delete; rpc_session& operator=(const rpc_session&) = delete; rpc_session() : work_(ios_), socket_(ios_), timer_work_(timer_ios_), timer_(timer_ios_) {} ~rpc_session() { stop(); } void connect(const std::string& ip, const std::string& port) { boost::asio::ip::tcp::resolver resolver(ios_); boost::asio::ip::tcp::resolver::query query(boost::asio::ip::tcp::v4(), ip, port); endpoint_iter_ = resolver.resolve(query); } void timeout(std::size_t timeout_milli) { timeout_milli_ = timeout_milli; } void run() { thread_ = std::make_unique<std::thread>([this]{ ios_.run(); }); if (timeout_milli_ != 0) { timer_thread_ = std::make_unique<std::thread>([this]{ timer_ios_.run(); }); } } void stop() { stop_ios_thread(); stop_timer_thread(); } std::vector<char> call(const std::string& protocol, const call_mode& mode, const std::string& body) { write(protocol, mode, body); return read(); } void connect() { boost::asio::connect(socket_, endpoint_iter_); } void disconnect() { if (socket_.is_open()) { boost::system::error_code ignore_ec; socket_.shutdown(boost::asio::socket_base::shutdown_both, ignore_ec); socket_.close(ignore_ec); } } private: void write(const std::string& protocol, const call_mode& mode, const std::string& body) { unsigned int protocol_len = static_cast<unsigned int>(protocol.size()); unsigned int body_len = static_cast<unsigned int>(body.size()); if (protocol_len + body_len > max_buffer_len) { throw std::runtime_error("Send data is too big"); } const auto& buffer = get_buffer(request_header{ protocol_len, body_len, mode }, protocol, body); write_impl(buffer); } std::vector<boost::asio::const_buffer> get_buffer(const request_header& head, const std::string& protocol, const std::string& body) { std::vector<boost::asio::const_buffer> buffer; buffer.emplace_back(boost::asio::buffer(&head, sizeof(request_header))); buffer.emplace_back(boost::asio::buffer(protocol)); buffer.emplace_back(boost::asio::buffer(body)); return buffer; } void write_impl(const std::vector<boost::asio::const_buffer>& buffer) { boost::system::error_code ec; boost::asio::write(socket_, buffer, ec); if (ec) { throw std::runtime_error(ec.message()); } } std::vector<char> read() { start_timer(); auto guard = make_guard([this]{ stop_timer(); }); read_head(); check_head(); return read_body(); } void read_head() { boost::system::error_code ec; boost::asio::read(socket_, boost::asio::buffer(head_), ec); if (ec) { throw std::runtime_error(ec.message()); } } void check_head() { memcpy(&_res_head, head_, sizeof(head_)); if (_res_head.body_len > max_buffer_len) { throw std::runtime_error("Body len is too big"); } } std::vector<char> read_body() { body_.clear(); body_.resize(_res_head.body_len); boost::system::error_code ec; boost::asio::read(socket_, boost::asio::buffer(body_), ec); if (ec) { throw std::runtime_error(ec.message()); } return body_; } void start_timer() { if (timeout_milli_ == 0) { return; } timer_.bind([this]{ disconnect(); }); timer_.set_single_shot(true); timer_.start(timeout_milli_); } void stop_timer() { if (timeout_milli_ == 0) { return; } timer_.stop(); } void stop_ios_thread() { ios_.stop(); if (thread_ != nullptr) { if (thread_->joinable()) { thread_->join(); } } } void stop_timer_thread() { timer_ios_.stop(); if (timer_thread_ != nullptr) { if (timer_thread_->joinable()) { timer_thread_->join(); } } } private: boost::asio::io_service ios_; boost::asio::io_service::work work_; boost::asio::ip::tcp::socket socket_; boost::asio::ip::tcp::resolver::iterator endpoint_iter_; std::unique_ptr<std::thread> thread_; char head_[response_header_len]; response_header _res_head; std::vector<char> body_; boost::asio::io_service timer_ios_; boost::asio::io_service::work timer_work_; std::unique_ptr<std::thread> timer_thread_; atimer<> timer_; std::size_t timeout_milli_ = 0; }; } #endif <commit_msg>Update<commit_after>#ifndef _RPC_SESSION_H #define _RPC_SESSION_H #include <string> #include <vector> #include <thread> #include <memory> #include <boost/asio.hpp> #include "base/header.hpp" #include "base/atimer.hpp" #include "base/scope_guard.hpp" namespace easyrpc { class rpc_session { public: rpc_session(const rpc_session&) = delete; rpc_session& operator=(const rpc_session&) = delete; rpc_session() : work_(ios_), socket_(ios_), timer_work_(timer_ios_), timer_(timer_ios_) {} ~rpc_session() { stop(); } void connect(const std::string& ip, const std::string& port) { boost::asio::ip::tcp::resolver resolver(ios_); boost::asio::ip::tcp::resolver::query query(boost::asio::ip::tcp::v4(), ip, port); endpoint_iter_ = resolver.resolve(query); } void timeout(std::size_t timeout_milli) { timeout_milli_ = timeout_milli; } void run() { thread_ = std::make_unique<std::thread>([this]{ ios_.run(); }); if (timeout_milli_ != 0) { timer_thread_ = std::make_unique<std::thread>([this]{ timer_ios_.run(); }); } } void stop() { stop_ios_thread(); stop_timer_thread(); } std::vector<char> call(const std::string& protocol, const call_mode& mode, const std::string& body) { write(protocol, mode, body); return read(); } void connect() { boost::asio::connect(socket_, endpoint_iter_); } void disconnect() { if (socket_.is_open()) { boost::system::error_code ignore_ec; socket_.shutdown(boost::asio::socket_base::shutdown_both, ignore_ec); socket_.close(ignore_ec); } } private: void write(const std::string& protocol, const call_mode& mode, const std::string& body) { unsigned int protocol_len = static_cast<unsigned int>(protocol.size()); unsigned int body_len = static_cast<unsigned int>(body.size()); if (protocol_len + body_len > max_buffer_len) { throw std::runtime_error("Send data is too big"); } const auto& buffer = get_buffer(request_header{ protocol_len, body_len, mode }, protocol, body); write_impl(buffer); } std::vector<boost::asio::const_buffer> get_buffer(const request_header& head, const std::string& protocol, const std::string& body) { std::vector<boost::asio::const_buffer> buffer; buffer.emplace_back(boost::asio::buffer(&head, sizeof(request_header))); buffer.emplace_back(boost::asio::buffer(protocol)); buffer.emplace_back(boost::asio::buffer(body)); return buffer; } void write_impl(const std::vector<boost::asio::const_buffer>& buffer) { boost::system::error_code ec; boost::asio::write(socket_, buffer, ec); if (ec) { throw std::runtime_error(ec.message()); } } std::vector<char> read() { start_timer(); auto guard = make_guard([this]{ stop_timer(); }); read_head(); check_head(); return read_body(); } void read_head() { boost::system::error_code ec; boost::asio::read(socket_, boost::asio::buffer(head_), ec); if (ec) { throw std::runtime_error(ec.message()); } } void check_head() { memcpy(&res_head_, head_, sizeof(head_)); if (res_head_.body_len > max_buffer_len) { throw std::runtime_error("Body len is too big"); } } std::vector<char> read_body() { body_.clear(); body_.resize(res_head_.body_len); boost::system::error_code ec; boost::asio::read(socket_, boost::asio::buffer(body_), ec); if (ec) { throw std::runtime_error(ec.message()); } return body_; } void start_timer() { if (timeout_milli_ == 0) { return; } timer_.bind([this]{ disconnect(); }); timer_.set_single_shot(true); timer_.start(timeout_milli_); } void stop_timer() { if (timeout_milli_ == 0) { return; } timer_.stop(); } void stop_ios_thread() { ios_.stop(); if (thread_ != nullptr) { if (thread_->joinable()) { thread_->join(); } } } void stop_timer_thread() { timer_ios_.stop(); if (timer_thread_ != nullptr) { if (timer_thread_->joinable()) { timer_thread_->join(); } } } private: boost::asio::io_service ios_; boost::asio::io_service::work work_; boost::asio::ip::tcp::socket socket_; boost::asio::ip::tcp::resolver::iterator endpoint_iter_; std::unique_ptr<std::thread> thread_; char head_[response_header_len]; response_header res_head_; std::vector<char> body_; boost::asio::io_service timer_ios_; boost::asio::io_service::work timer_work_; std::unique_ptr<std::thread> timer_thread_; atimer<> timer_; std::size_t timeout_milli_ = 0; }; } #endif <|endoftext|>
<commit_before>// Natron // /* 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/. */ /* * Created by Alexandre GAUTHIER-FOICHAT on 6/1/2012. * contact: immarespond at gmail dot com * */ #include "ScaleSliderQWidget.h" #include <cassert> CLANG_DIAG_OFF(unused-private-field) // /opt/local/include/QtGui/qmime.h:119:10: warning: private field 'type' is not used [-Wunused-private-field] #include <QtGui/QPaintEvent> CLANG_DIAG_ON(unused-private-field) #include <QtGui/QMouseEvent> #include <QtGui/QPainter> #include <QStyleOption> #include "Gui/ticks.h" #define TICK_HEIGHT 7 #define SLIDER_WIDTH 4 #define SLIDER_HEIGHT 20 ScaleSliderQWidget::ScaleSliderQWidget(double bottom, double top, double initialPos, Natron::ScaleTypeEnum type, QWidget* parent) : QWidget(parent) , _zoomCtx() , _oldClick() , _minimum(bottom) , _maximum(top) , _type(type) , _value(initialPos) , _dragging(false) , _font( new QFont(NATRON_FONT_ALT, NATRON_FONT_SIZE_8) ) , _textColor(200,200,200,255) , _scaleColor(100,100,100,255) , _sliderColor(97,83,30,255) , _initialized(false) , _mustInitializeSliderPosition(true) , _readOnly(false) , _ctrlDown(false) , _shiftDown(false) , _currentZoom(1.) { setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding); QSize sizeh = sizeHint(); _zoomCtx.setScreenSize(sizeh.width(), sizeh.height()); setFocusPolicy(Qt::ClickFocus); } QSize ScaleSliderQWidget::sizeHint() const { return QSize(150,30); } ScaleSliderQWidget::~ScaleSliderQWidget() { delete _font; } void ScaleSliderQWidget::mousePressEvent(QMouseEvent* e) { if (!_readOnly) { QPoint newClick = e->pos(); _oldClick = newClick; QPointF newClick_opengl = _zoomCtx.toZoomCoordinates( newClick.x(),newClick.y() ); seekInternal( newClick_opengl.x() ); } QWidget::mousePressEvent(e); } void ScaleSliderQWidget::mouseMoveEvent(QMouseEvent* e) { if (!_readOnly) { QPoint newClick = e->pos(); QPointF newClick_opengl = _zoomCtx.toZoomCoordinates( newClick.x(),newClick.y() ); seekInternal( newClick_opengl.x() ); } } void ScaleSliderQWidget::mouseReleaseEvent(QMouseEvent* e) { emit editingFinished(); QWidget::mouseReleaseEvent(e); } void ScaleSliderQWidget::keyPressEvent(QKeyEvent* e) { if (e->key() == Qt::Key_Control) { _ctrlDown = true; double scale = _shiftDown ? 100. : 10.; _currentZoom = scale; _zoomCtx.zoomx(_value, 0, scale); update(); } else if (e->key() == Qt::Key_Shift) { _shiftDown = true; if (_ctrlDown) { _zoomCtx.zoomx(_value, 0, 10.); _currentZoom = 100.; } update(); } QWidget::keyPressEvent(e); } void ScaleSliderQWidget::keyReleaseEvent(QKeyEvent* e) { if (e->key() == Qt::Key_Control) { _ctrlDown = false; _zoomCtx.zoomx(_value, 0, 1. / _currentZoom); _currentZoom = 1.; centerOn(_minimum, _maximum); return; } else if (e->key() == Qt::Key_Shift) { _shiftDown = false; if (_ctrlDown) { _zoomCtx.zoomx(_value, 0, 1. / 10.); _currentZoom = 10.; } else { _zoomCtx.zoomx(_value, 0, 1. / _currentZoom); centerOn(_minimum, _maximum); _currentZoom = 1.; return; } update(); } QWidget::keyReleaseEvent(e); } void ScaleSliderQWidget::seekScalePosition(double v) { if (v < _minimum) { v = _minimum; } if (v > _maximum) { v = _maximum; } if ( (v == _value) && _initialized ) { return; } _value = v; if (_initialized) { update(); } } void ScaleSliderQWidget::seekInternal(double v) { if (v < _minimum) { v = _minimum; } if (v > _maximum) { v = _maximum; } if (v == _value) { return; } _value = v; if (_initialized) { update(); } emit positionChanged(v); } void ScaleSliderQWidget::setMinimumAndMaximum(double min, double max) { _minimum = min; _maximum = max; centerOn(_minimum, _maximum); } void ScaleSliderQWidget::centerOn(double left, double right) { double w = right - left; _zoomCtx.fill(left - w * 0.05, right + w * 0.05, _zoomCtx.bottom(), _zoomCtx.top()); update(); } void ScaleSliderQWidget::resizeEvent(QResizeEvent* e) { _zoomCtx.setScreenSize(e->size().width(), e->size().height()); QWidget::resizeEvent(e); } void ScaleSliderQWidget::paintEvent(QPaintEvent* /*e*/) { if (_mustInitializeSliderPosition) { centerOn(_minimum, _maximum); _mustInitializeSliderPosition = false; seekScalePosition(_value); _initialized = true; } ///fill the background with the appropriate style color QStyleOption opt; opt.init(this); QPainter p(this); style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this); QFontMetrics fontM(*_font); p.setPen(_scaleColor); QPointF btmLeft = _zoomCtx.toZoomCoordinates(0,height() - 1); QPointF topRight = _zoomCtx.toZoomCoordinates(width() - 1, 0); if ( btmLeft.x() == topRight.x() ) { return; } /*drawing X axis*/ double lineYpos = height() - 1 - fontM.height() - TICK_HEIGHT / 2; p.drawLine(0, lineYpos, width() - 1, lineYpos); double tickBottom = _zoomCtx.toZoomCoordinates( 0,height() - 1 - fontM.height() ).y(); double tickTop = _zoomCtx.toZoomCoordinates(0,height() - 1 - fontM.height() - TICK_HEIGHT).y(); const double smallestTickSizePixel = 5.; // tick size (in pixels) for alpha = 0. const double largestTickSizePixel = 1000.; // tick size (in pixels) for alpha = 1. std::vector<double> acceptedDistances; acceptedDistances.push_back(1.); acceptedDistances.push_back(5.); acceptedDistances.push_back(10.); acceptedDistances.push_back(50.); const double rangePixel = width(); const double range_min = btmLeft.x(); const double range_max = topRight.x(); const double range = range_max - range_min; double smallTickSize; bool half_tick; ticks_size(range_min, range_max, rangePixel, smallestTickSizePixel, &smallTickSize, &half_tick); int m1, m2; const int ticks_max = 1000; double offset; ticks_bounds(range_min, range_max, smallTickSize, half_tick, ticks_max, &offset, &m1, &m2); std::vector<int> ticks; ticks_fill(half_tick, ticks_max, m1, m2, &ticks); const double smallestTickSize = range * smallestTickSizePixel / rangePixel; const double largestTickSize = range * largestTickSizePixel / rangePixel; const double minTickSizeTextPixel = fontM.width( QString("00") ); // AXIS-SPECIFIC const double minTickSizeText = range * minTickSizeTextPixel / rangePixel; for (int i = m1; i <= m2; ++i) { double value = i * smallTickSize + offset; const double tickSize = ticks[i - m1] * smallTickSize; const double alpha = ticks_alpha(smallestTickSize, largestTickSize, tickSize); QColor color(_textColor); color.setAlphaF(alpha); QPen pen(color); pen.setWidthF(1.9); p.setPen(pen); QPointF tickBottomPos = _zoomCtx.toWidgetCoordinates(value, tickBottom); QPointF tickTopPos = _zoomCtx.toWidgetCoordinates(value, tickTop); p.drawLine(tickBottomPos,tickTopPos); if (tickSize > minTickSizeText) { const int tickSizePixel = rangePixel * tickSize / range; const QString s = QString::number(value); const int sSizePixel = fontM.width(s); if (tickSizePixel > sSizePixel) { const int sSizeFullPixel = sSizePixel + minTickSizeTextPixel; double alphaText = 1.0; //alpha; if (tickSizePixel < sSizeFullPixel) { // when the text size is between sSizePixel and sSizeFullPixel, // draw it with a lower alpha alphaText *= (tickSizePixel - sSizePixel) / (double)minTickSizeTextPixel; } QColor c = _readOnly || !isEnabled() ? Qt::black : _textColor; c.setAlphaF(alphaText); p.setFont(*_font); p.setPen(c); QPointF textPos = _zoomCtx.toWidgetCoordinates( value, btmLeft.y() ); p.drawText(textPos, s); } } } double positionValue = _zoomCtx.toWidgetCoordinates(_value,0).x(); QPointF sliderBottomLeft(positionValue - SLIDER_WIDTH / 2,height() - 1 - fontM.height() / 2); QPointF sliderTopRight(positionValue + SLIDER_WIDTH / 2,height() - 1 - fontM.height() / 2 - SLIDER_HEIGHT); /*draw the slider*/ p.setPen(_sliderColor); p.fillRect(sliderBottomLeft.x(), sliderBottomLeft.y(), sliderTopRight.x() - sliderBottomLeft.x(), sliderTopRight.y() - sliderBottomLeft.y(),_sliderColor); /*draw a black rect around the slider for contrast*/ p.setPen(Qt::black); p.drawLine( sliderBottomLeft.x(),sliderBottomLeft.y(),sliderBottomLeft.x(),sliderTopRight.y() ); p.drawLine( sliderBottomLeft.x(),sliderTopRight.y(),sliderTopRight.x(),sliderTopRight.y() ); p.drawLine( sliderTopRight.x(),sliderTopRight.y(),sliderTopRight.x(),sliderBottomLeft.y() ); p.drawLine( sliderTopRight.x(),sliderBottomLeft.y(),sliderBottomLeft.x(),sliderBottomLeft.y() ); } // paintEvent void ScaleSliderQWidget::setReadOnly(bool ro) { _readOnly = ro; update(); } <commit_msg>Sliders are now aligned properly<commit_after>// Natron // /* 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/. */ /* * Created by Alexandre GAUTHIER-FOICHAT on 6/1/2012. * contact: immarespond at gmail dot com * */ #include "ScaleSliderQWidget.h" #include <cassert> CLANG_DIAG_OFF(unused-private-field) // /opt/local/include/QtGui/qmime.h:119:10: warning: private field 'type' is not used [-Wunused-private-field] #include <QtGui/QPaintEvent> CLANG_DIAG_ON(unused-private-field) #include <QtGui/QMouseEvent> #include <QtGui/QPainter> #include <QStyleOption> #include "Gui/ticks.h" #define TICK_HEIGHT 7 #define SLIDER_WIDTH 4 #define SLIDER_HEIGHT 15 ScaleSliderQWidget::ScaleSliderQWidget(double bottom, double top, double initialPos, Natron::ScaleTypeEnum type, QWidget* parent) : QWidget(parent) , _zoomCtx() , _oldClick() , _minimum(bottom) , _maximum(top) , _type(type) , _value(initialPos) , _dragging(false) , _font( new QFont(NATRON_FONT_ALT, NATRON_FONT_SIZE_8) ) , _textColor(200,200,200,255) , _scaleColor(100,100,100,255) , _sliderColor(97,83,30,255) , _initialized(false) , _mustInitializeSliderPosition(true) , _readOnly(false) , _ctrlDown(false) , _shiftDown(false) , _currentZoom(1.) { setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding); QSize sizeh = sizeHint(); _zoomCtx.setScreenSize(sizeh.width(), sizeh.height()); setFocusPolicy(Qt::ClickFocus); } QSize ScaleSliderQWidget::sizeHint() const { return QSize(150,20); } ScaleSliderQWidget::~ScaleSliderQWidget() { delete _font; } void ScaleSliderQWidget::mousePressEvent(QMouseEvent* e) { if (!_readOnly) { QPoint newClick = e->pos(); _oldClick = newClick; QPointF newClick_opengl = _zoomCtx.toZoomCoordinates( newClick.x(),newClick.y() ); seekInternal( newClick_opengl.x() ); } QWidget::mousePressEvent(e); } void ScaleSliderQWidget::mouseMoveEvent(QMouseEvent* e) { if (!_readOnly) { QPoint newClick = e->pos(); QPointF newClick_opengl = _zoomCtx.toZoomCoordinates( newClick.x(),newClick.y() ); seekInternal( newClick_opengl.x() ); } } void ScaleSliderQWidget::mouseReleaseEvent(QMouseEvent* e) { emit editingFinished(); QWidget::mouseReleaseEvent(e); } void ScaleSliderQWidget::keyPressEvent(QKeyEvent* e) { if (e->key() == Qt::Key_Control) { _ctrlDown = true; double scale = _shiftDown ? 100. : 10.; _currentZoom = scale; _zoomCtx.zoomx(_value, 0, scale); update(); } else if (e->key() == Qt::Key_Shift) { _shiftDown = true; if (_ctrlDown) { _zoomCtx.zoomx(_value, 0, 10.); _currentZoom = 100.; } update(); } QWidget::keyPressEvent(e); } void ScaleSliderQWidget::keyReleaseEvent(QKeyEvent* e) { if (e->key() == Qt::Key_Control) { _ctrlDown = false; _zoomCtx.zoomx(_value, 0, 1. / _currentZoom); _currentZoom = 1.; centerOn(_minimum, _maximum); return; } else if (e->key() == Qt::Key_Shift) { _shiftDown = false; if (_ctrlDown) { _zoomCtx.zoomx(_value, 0, 1. / 10.); _currentZoom = 10.; } else { _zoomCtx.zoomx(_value, 0, 1. / _currentZoom); centerOn(_minimum, _maximum); _currentZoom = 1.; return; } update(); } QWidget::keyReleaseEvent(e); } void ScaleSliderQWidget::seekScalePosition(double v) { if (v < _minimum) { v = _minimum; } if (v > _maximum) { v = _maximum; } if ( (v == _value) && _initialized ) { return; } _value = v; if (_initialized) { update(); } } void ScaleSliderQWidget::seekInternal(double v) { if (v < _minimum) { v = _minimum; } if (v > _maximum) { v = _maximum; } if (v == _value) { return; } _value = v; if (_initialized) { update(); } emit positionChanged(v); } void ScaleSliderQWidget::setMinimumAndMaximum(double min, double max) { _minimum = min; _maximum = max; centerOn(_minimum, _maximum); } void ScaleSliderQWidget::centerOn(double left, double right) { double w = right - left; _zoomCtx.fill(left - w * 0.05, right + w * 0.05, _zoomCtx.bottom(), _zoomCtx.top()); update(); } void ScaleSliderQWidget::resizeEvent(QResizeEvent* e) { _zoomCtx.setScreenSize(e->size().width(), e->size().height()); QWidget::resizeEvent(e); } void ScaleSliderQWidget::paintEvent(QPaintEvent* /*e*/) { if (_mustInitializeSliderPosition) { centerOn(_minimum, _maximum); _mustInitializeSliderPosition = false; seekScalePosition(_value); _initialized = true; } ///fill the background with the appropriate style color QStyleOption opt; opt.init(this); QPainter p(this); style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this); QFontMetrics fontM(*_font); p.setPen(_scaleColor); QPointF btmLeft = _zoomCtx.toZoomCoordinates(0,height() - 1); QPointF topRight = _zoomCtx.toZoomCoordinates(width() - 1, 0); if ( btmLeft.x() == topRight.x() ) { return; } /*drawing X axis*/ double lineYpos = height() - 1 - fontM.height() - TICK_HEIGHT / 2; p.drawLine(0, lineYpos, width() - 1, lineYpos); double tickBottom = _zoomCtx.toZoomCoordinates( 0,height() - 1 - fontM.height() ).y(); double tickTop = _zoomCtx.toZoomCoordinates(0,height() - 1 - fontM.height() - TICK_HEIGHT).y(); const double smallestTickSizePixel = 5.; // tick size (in pixels) for alpha = 0. const double largestTickSizePixel = 1000.; // tick size (in pixels) for alpha = 1. std::vector<double> acceptedDistances; acceptedDistances.push_back(1.); acceptedDistances.push_back(5.); acceptedDistances.push_back(10.); acceptedDistances.push_back(50.); const double rangePixel = width(); const double range_min = btmLeft.x(); const double range_max = topRight.x(); const double range = range_max - range_min; double smallTickSize; bool half_tick; ticks_size(range_min, range_max, rangePixel, smallestTickSizePixel, &smallTickSize, &half_tick); int m1, m2; const int ticks_max = 1000; double offset; ticks_bounds(range_min, range_max, smallTickSize, half_tick, ticks_max, &offset, &m1, &m2); std::vector<int> ticks; ticks_fill(half_tick, ticks_max, m1, m2, &ticks); const double smallestTickSize = range * smallestTickSizePixel / rangePixel; const double largestTickSize = range * largestTickSizePixel / rangePixel; const double minTickSizeTextPixel = fontM.width( QString("00") ); // AXIS-SPECIFIC const double minTickSizeText = range * minTickSizeTextPixel / rangePixel; for (int i = m1; i <= m2; ++i) { double value = i * smallTickSize + offset; const double tickSize = ticks[i - m1] * smallTickSize; const double alpha = ticks_alpha(smallestTickSize, largestTickSize, tickSize); QColor color(_textColor); color.setAlphaF(alpha); QPen pen(color); pen.setWidthF(1.9); p.setPen(pen); QPointF tickBottomPos = _zoomCtx.toWidgetCoordinates(value, tickBottom); QPointF tickTopPos = _zoomCtx.toWidgetCoordinates(value, tickTop); p.drawLine(tickBottomPos,tickTopPos); if (tickSize > minTickSizeText) { const int tickSizePixel = rangePixel * tickSize / range; const QString s = QString::number(value); const int sSizePixel = fontM.width(s); if (tickSizePixel > sSizePixel) { const int sSizeFullPixel = sSizePixel + minTickSizeTextPixel; double alphaText = 1.0; //alpha; if (tickSizePixel < sSizeFullPixel) { // when the text size is between sSizePixel and sSizeFullPixel, // draw it with a lower alpha alphaText *= (tickSizePixel - sSizePixel) / (double)minTickSizeTextPixel; } QColor c = _readOnly || !isEnabled() ? Qt::black : _textColor; c.setAlphaF(alphaText); p.setFont(*_font); p.setPen(c); QPointF textPos = _zoomCtx.toWidgetCoordinates( value, btmLeft.y() ); p.drawText(textPos, s); } } } double positionValue = _zoomCtx.toWidgetCoordinates(_value,0).x(); QPointF sliderBottomLeft(positionValue - SLIDER_WIDTH / 2,height() - 1 - fontM.height() / 2); QPointF sliderTopRight(positionValue + SLIDER_WIDTH / 2,height() - 1 - fontM.height() / 2 - SLIDER_HEIGHT); /*draw the slider*/ p.setPen(_sliderColor); p.fillRect(sliderBottomLeft.x(), sliderBottomLeft.y(), sliderTopRight.x() - sliderBottomLeft.x(), sliderTopRight.y() - sliderBottomLeft.y(),_sliderColor); /*draw a black rect around the slider for contrast*/ p.setPen(Qt::black); p.drawLine( sliderBottomLeft.x(),sliderBottomLeft.y(),sliderBottomLeft.x(),sliderTopRight.y() ); p.drawLine( sliderBottomLeft.x(),sliderTopRight.y(),sliderTopRight.x(),sliderTopRight.y() ); p.drawLine( sliderTopRight.x(),sliderTopRight.y(),sliderTopRight.x(),sliderBottomLeft.y() ); p.drawLine( sliderTopRight.x(),sliderBottomLeft.y(),sliderBottomLeft.x(),sliderBottomLeft.y() ); } // paintEvent void ScaleSliderQWidget::setReadOnly(bool ro) { _readOnly = ro; update(); } <|endoftext|>
<commit_before>#include <QDebug> #include <QSettings> #include <QFileInfo> #include <QDir> #include <QThread> #include <coreplugin/messagemanager.h> #include <coreplugin/progressmanager/progressmanager.h> #include <coreplugin/progressmanager/futureprogress.h> #include <utils/macroexpander.h> #include "CppcheckRunner.h" #include "Constants.h" #include "Settings.h" using namespace QtcCppcheck::Internal; namespace { enum ErrorField { ErrorFieldFile = 0, ErrorFieldLine, ErrorFieldSeverity, ErrorFieldId, ErrorFieldMessage }; QStringList includePaths (const QStringList& files) { QStringList paths; foreach (const QString& file, files) { QFileInfo info (file); QString current = QString (QLatin1String("-I")) + info.absolutePath (); if (!paths.contains(current)) { paths << current; } } return paths; } } CppcheckRunner::CppcheckRunner(Settings *settings, QObject *parent) : QObject(parent), settings_ (settings), showOutput_ (false), showId_(false), futureInterface_ (NULL), maxArgumentsLength_ (0) { #ifdef __linux__ QProcess getConf; getConf.start (QLatin1String("getconf ARG_MAX")); getConf.waitForFinished (2000); QByteArray argMax = getConf.readAllStandardOutput ().replace ("\n", ""); maxArgumentsLength_ = std::max (argMax.toInt (), 32000); #else maxArgumentsLength_ = 32767; #endif Q_ASSERT (settings_ != NULL); connect (&process_, SIGNAL (readyReadStandardOutput()), SLOT (readOutput())); connect (&process_, SIGNAL (readyReadStandardError()), SLOT (readError())); connect (&process_, SIGNAL (started()), SLOT (started())); connect (&process_, SIGNAL (error(QProcess::ProcessError)), SLOT (error(QProcess::ProcessError))); connect (&process_, SIGNAL (finished(int, QProcess::ExitStatus)), SLOT (finished(int, QProcess::ExitStatus))); // Restart checking if got queue. connect (&process_, SIGNAL (finished(int, QProcess::ExitStatus)), SLOT (checkQueuedFiles ())); } CppcheckRunner::~CppcheckRunner() { if (process_.isOpen()) { process_.kill(); } queueTimer_.stop (); settings_ = NULL; delete futureInterface_; } void CppcheckRunner::updateSettings() { Q_ASSERT (settings_ != NULL); showOutput_ = settings_->showBinaryOutput (); showId_ = settings_->showId (); runArguments_.clear (); QString enabled = QLatin1String ("--enable=warning,style,performance," "portability,information,missingInclude"); // Overwrite enable with user parameters if present for(int i = runArguments_.size () - 1; i >= 0; --i) { if (runArguments_.at (i).startsWith (QLatin1String ("--enable"))) { enabled = runArguments_.takeAt (i); break; } } if (settings_->checkUnused ()) { enabled += QLatin1String (",unusedFunction"); } else //TODO always check with threads but rescan for unused after finish? { runArguments_ << (QLatin1String ("-j ") + QString::number (QThread::idealThreadCount ())); } runArguments_ << enabled; if (settings_->checkInconclusive ()) { runArguments_ << QLatin1String ("--inconclusive"); } runArguments_ << QLatin1String ("--template={file},{line},{severity},{id},{message}"); } void CppcheckRunner::checkFiles(const QStringList &fileNames) { Q_ASSERT (!fileNames.isEmpty ()); fileCheckQueue_ += fileNames; fileCheckQueue_.removeDuplicates (); fileCheckQueue_.sort (); if (process_.isOpen ()) { if (fileCheckQueue_ == currentlyCheckingFiles_) { process_.kill (); // Rechecking will be restarted on finish signal. } return; } // Delay helps to avoid double checking same file on editor change. const int checkDelayInMs = 200; if (!queueTimer_.isActive ()) { queueTimer_.singleShot (checkDelayInMs, this, SLOT (checkQueuedFiles ())); } } void CppcheckRunner::stopChecking() { fileCheckQueue_.clear (); if (process_.isOpen ()) { process_.kill (); } } void CppcheckRunner::checkQueuedFiles() { if (fileCheckQueue_.isEmpty ()) { return; } QString binary = settings_->binaryFile (); if (binary.isEmpty ()) { return; } // Pass custom params BEFORE most of runner's to shadow if some repeat. auto expander = Utils::globalMacroExpander(); auto expanded = expander->expand (settings_->customParameters ()); QStringList arguments (expanded.split (QLatin1Char (' '), QString::SkipEmptyParts)); arguments += runArguments_; QStringList includes = includePaths (fileCheckQueue_); arguments += includes; arguments += fileCheckQueue_; currentlyCheckingFiles_ = fileCheckQueue_; fileCheckQueue_.clear (); int argumentLength = arguments.join (QLatin1Literal (" ")).length (); if (argumentLength >= maxArgumentsLength_) { if (fileListFileContents_ != currentlyCheckingFiles_) { fileListFileContents_ = currentlyCheckingFiles_; if (fileListFile_.open () && includeListFile_.open ()){ QByteArray filesArg = fileListFileContents_.join (QLatin1String ("\n")).toLocal8Bit (); fileListFile_.write (filesArg); QByteArray includesArg = includes.join (QLatin1String ("\n")).toLocal8Bit (); includeListFile_.write (includesArg); } else { Core::MessageManager::write (tr ("Failed to write cppcheck's argument files"), Core::MessageManager::Silent); return; } } arguments = runArguments_; arguments << QString (QLatin1String("--file-list=%1")).arg (fileListFile_.fileName ()); arguments << QString (QLatin1String("--includes-file=%1")).arg (includeListFile_.fileName ()); } emit startedChecking (currentlyCheckingFiles_); if (showOutput_) { Core::MessageManager::write(QString("Starting CppChecker with:%1, %2").arg(binary,arguments.join(" ")), Core::MessageManager::WithFocus); } process_.start (binary, arguments); } void CppcheckRunner::readOutput() { if (!showOutput_) { return; } process_.setReadChannel (QProcess::StandardOutput); while (!process_.atEnd ()) { QByteArray rawLine = process_.readLine (); QString line = QString::fromUtf8 (rawLine).trimmed (); if (line.isEmpty ()) { continue; } const QString progressSample = QLatin1String ("% done"); // check futureInterface because read can be triggered before started.. if (line.endsWith (progressSample) && futureInterface_ != NULL) { int percentEndIndex = line.length () - progressSample.length (); int percentStartIndex = line.lastIndexOf(QLatin1String (" "), percentEndIndex); int done = line.mid (percentStartIndex, percentEndIndex - percentStartIndex).toInt (); futureInterface_->setProgressValue (done); } Core::MessageManager::write (line, Core::MessageManager::Silent); } } void CppcheckRunner::readError() { process_.setReadChannel (QProcess::StandardError); while (!process_.atEnd ()) { QByteArray rawLine = process_.readLine (); QString line = QString::fromUtf8 (rawLine).trimmed (); if (line.isEmpty ()) { continue; } if (showOutput_) { Core::MessageManager::write (line, Core::MessageManager::Silent); } QStringList details = line.split (QLatin1Char (',')); if (details.size () <= ErrorFieldMessage) { continue; } QString file = QDir::fromNativeSeparators(details.at (ErrorFieldFile)); int lineNumber = details.at (ErrorFieldLine).toInt (); char type = details.at (ErrorFieldSeverity).at (0).toLatin1 (); QString id = ""; if (showId_) { id = details.at (ErrorFieldId); } QString description = line.mid (line.indexOf (details.at (ErrorFieldMessage))); emit newTask (type, id, description, file, lineNumber); } } void CppcheckRunner::started() { if (showOutput_) { Core::MessageManager::write (tr ("Cppcheck started"), Core::MessageManager::Silent); } using namespace Core; delete futureInterface_; futureInterface_ = new QFutureInterface<void>; FutureProgress *progress = ProgressManager::addTask(futureInterface_->future(), tr("Cppcheck"), Constants::TASK_CHECKING); connect (progress, SIGNAL(canceled ()), SLOT(stopChecking ())); futureInterface_->setProgressRange(0, 100); // % futureInterface_->reportStarted(); } void CppcheckRunner::error(QProcess::ProcessError error) { Q_UNUSED (error); if (showOutput_) { Core::MessageManager::write (tr ("Cppcheck error occured"), Core::MessageManager::Silent); } if (error == QProcess::FailedToStart) { finished (-1, QProcess::CrashExit); } } void CppcheckRunner::finished(int exitCode, QProcess::ExitStatus exitStatus) { Q_UNUSED (exitCode); Q_UNUSED (exitStatus); if (futureInterface_ != NULL) { futureInterface_->reportFinished (); } process_.close (); if (showOutput_) { Core::MessageManager::write (tr("Cppcheck finished"), Core::MessageManager::Silent); } } <commit_msg>Fixed generation of wrong '--includes-file' option's file.<commit_after>#include <QDebug> #include <QSettings> #include <QFileInfo> #include <QDir> #include <QThread> #include <coreplugin/messagemanager.h> #include <coreplugin/progressmanager/progressmanager.h> #include <coreplugin/progressmanager/futureprogress.h> #include <utils/macroexpander.h> #include "CppcheckRunner.h" #include "Constants.h" #include "Settings.h" using namespace QtcCppcheck::Internal; namespace { enum ErrorField { ErrorFieldFile = 0, ErrorFieldLine, ErrorFieldSeverity, ErrorFieldId, ErrorFieldMessage }; QStringList includePaths (const QStringList& files) { QStringList paths; foreach (const QString& file, files) { QFileInfo info (file); QString current = info.absolutePath (); if (!paths.contains(current)) { paths << current; } } return paths; } } CppcheckRunner::CppcheckRunner(Settings *settings, QObject *parent) : QObject(parent), settings_ (settings), showOutput_ (false), showId_(false), futureInterface_ (NULL), maxArgumentsLength_ (0) { #ifdef __linux__ QProcess getConf; getConf.start (QLatin1String("getconf ARG_MAX")); getConf.waitForFinished (2000); QByteArray argMax = getConf.readAllStandardOutput ().replace ("\n", ""); maxArgumentsLength_ = std::max (argMax.toInt (), 32000); #else maxArgumentsLength_ = 32767; #endif Q_ASSERT (settings_ != NULL); connect (&process_, SIGNAL (readyReadStandardOutput()), SLOT (readOutput())); connect (&process_, SIGNAL (readyReadStandardError()), SLOT (readError())); connect (&process_, SIGNAL (started()), SLOT (started())); connect (&process_, SIGNAL (error(QProcess::ProcessError)), SLOT (error(QProcess::ProcessError))); connect (&process_, SIGNAL (finished(int, QProcess::ExitStatus)), SLOT (finished(int, QProcess::ExitStatus))); // Restart checking if got queue. connect (&process_, SIGNAL (finished(int, QProcess::ExitStatus)), SLOT (checkQueuedFiles ())); } CppcheckRunner::~CppcheckRunner() { if (process_.isOpen()) { process_.kill(); } queueTimer_.stop (); settings_ = NULL; delete futureInterface_; } void CppcheckRunner::updateSettings() { Q_ASSERT (settings_ != NULL); showOutput_ = settings_->showBinaryOutput (); showId_ = settings_->showId (); runArguments_.clear (); QString enabled = QLatin1String ("--enable=warning,style,performance," "portability,information,missingInclude"); // Overwrite enable with user parameters if present for(int i = runArguments_.size () - 1; i >= 0; --i) { if (runArguments_.at (i).startsWith (QLatin1String ("--enable"))) { enabled = runArguments_.takeAt (i); break; } } if (settings_->checkUnused ()) { enabled += QLatin1String (",unusedFunction"); } else //TODO always check with threads but rescan for unused after finish? { runArguments_ << (QLatin1String ("-j ") + QString::number (QThread::idealThreadCount ())); } runArguments_ << enabled; if (settings_->checkInconclusive ()) { runArguments_ << QLatin1String ("--inconclusive"); } runArguments_ << QLatin1String ("--template={file},{line},{severity},{id},{message}"); } void CppcheckRunner::checkFiles(const QStringList &fileNames) { Q_ASSERT (!fileNames.isEmpty ()); fileCheckQueue_ += fileNames; fileCheckQueue_.removeDuplicates (); fileCheckQueue_.sort (); if (process_.isOpen ()) { if (fileCheckQueue_ == currentlyCheckingFiles_) { process_.kill (); // Rechecking will be restarted on finish signal. } return; } // Delay helps to avoid double checking same file on editor change. const int checkDelayInMs = 200; if (!queueTimer_.isActive ()) { queueTimer_.singleShot (checkDelayInMs, this, SLOT (checkQueuedFiles ())); } } void CppcheckRunner::stopChecking() { fileCheckQueue_.clear (); if (process_.isOpen ()) { process_.kill (); } } void CppcheckRunner::checkQueuedFiles() { if (fileCheckQueue_.isEmpty ()) { return; } QString binary = settings_->binaryFile (); if (binary.isEmpty ()) { return; } // Pass custom params BEFORE most of runner's to shadow if some repeat. auto expander = Utils::globalMacroExpander(); auto expanded = expander->expand (settings_->customParameters ()); QStringList arguments (expanded.split (QLatin1Char (' '), QString::SkipEmptyParts)); arguments += runArguments_; QStringList includes = includePaths (fileCheckQueue_); arguments += includes; arguments += fileCheckQueue_; currentlyCheckingFiles_ = fileCheckQueue_; fileCheckQueue_.clear (); int argumentLength = arguments.join (QLatin1Literal (" ")).length (); if (argumentLength >= maxArgumentsLength_) { if (fileListFileContents_ != currentlyCheckingFiles_) { fileListFileContents_ = currentlyCheckingFiles_; if (fileListFile_.open () && includeListFile_.open ()){ QByteArray filesArg = fileListFileContents_.join (QLatin1String ("\n")).toLocal8Bit (); fileListFile_.write (filesArg); QByteArray includesArg = includes.join (QLatin1String ("\n")).toLocal8Bit (); includeListFile_.write (includesArg); } else { Core::MessageManager::write (tr ("Failed to write cppcheck's argument files"), Core::MessageManager::Silent); return; } } arguments = runArguments_; arguments << QString (QLatin1String("--file-list=%1")).arg (fileListFile_.fileName ()); arguments << QString (QLatin1String("--includes-file=%1")).arg (includeListFile_.fileName ()); } emit startedChecking (currentlyCheckingFiles_); if (showOutput_) { Core::MessageManager::write(QString("Starting CppChecker with:%1, %2").arg(binary,arguments.join(" ")), Core::MessageManager::WithFocus); } process_.start (binary, arguments); } void CppcheckRunner::readOutput() { if (!showOutput_) { return; } process_.setReadChannel (QProcess::StandardOutput); while (!process_.atEnd ()) { QByteArray rawLine = process_.readLine (); QString line = QString::fromUtf8 (rawLine).trimmed (); if (line.isEmpty ()) { continue; } const QString progressSample = QLatin1String ("% done"); // check futureInterface because read can be triggered before started.. if (line.endsWith (progressSample) && futureInterface_ != NULL) { int percentEndIndex = line.length () - progressSample.length (); int percentStartIndex = line.lastIndexOf(QLatin1String (" "), percentEndIndex); int done = line.mid (percentStartIndex, percentEndIndex - percentStartIndex).toInt (); futureInterface_->setProgressValue (done); } Core::MessageManager::write (line, Core::MessageManager::Silent); } } void CppcheckRunner::readError() { process_.setReadChannel (QProcess::StandardError); while (!process_.atEnd ()) { QByteArray rawLine = process_.readLine (); QString line = QString::fromUtf8 (rawLine).trimmed (); if (line.isEmpty ()) { continue; } if (showOutput_) { Core::MessageManager::write (line, Core::MessageManager::Silent); } QStringList details = line.split (QLatin1Char (',')); if (details.size () <= ErrorFieldMessage) { continue; } QString file = QDir::fromNativeSeparators(details.at (ErrorFieldFile)); int lineNumber = details.at (ErrorFieldLine).toInt (); char type = details.at (ErrorFieldSeverity).at (0).toLatin1 (); QString id = ""; if (showId_) { id = details.at (ErrorFieldId); } QString description = line.mid (line.indexOf (details.at (ErrorFieldMessage))); emit newTask (type, id, description, file, lineNumber); } } void CppcheckRunner::started() { if (showOutput_) { Core::MessageManager::write (tr ("Cppcheck started"), Core::MessageManager::Silent); } using namespace Core; delete futureInterface_; futureInterface_ = new QFutureInterface<void>; FutureProgress *progress = ProgressManager::addTask(futureInterface_->future(), tr("Cppcheck"), Constants::TASK_CHECKING); connect (progress, SIGNAL(canceled ()), SLOT(stopChecking ())); futureInterface_->setProgressRange(0, 100); // % futureInterface_->reportStarted(); } void CppcheckRunner::error(QProcess::ProcessError error) { Q_UNUSED (error); if (showOutput_) { Core::MessageManager::write (tr ("Cppcheck error occured"), Core::MessageManager::Silent); } if (error == QProcess::FailedToStart) { finished (-1, QProcess::CrashExit); } } void CppcheckRunner::finished(int exitCode, QProcess::ExitStatus exitStatus) { Q_UNUSED (exitCode); Q_UNUSED (exitStatus); if (futureInterface_ != NULL) { futureInterface_->reportFinished (); } process_.close (); if (showOutput_) { Core::MessageManager::write (tr("Cppcheck finished"), Core::MessageManager::Silent); } } <|endoftext|>
<commit_before>// Copyright (c) 2022 The Orbit 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 <absl/container/flat_hash_map.h> #include <absl/strings/str_format.h> #include <gmock/gmock.h> #include <gtest/gtest.h> #include <QApplication> #include <QComboBox> #include <QLineEdit> #include <QListWidget> #include <QStringLiteral> #include <QTest> #include <array> #include <limits> #include <string> #include "ClientData/ScopeInfo.h" #include "MizarBase/ThreadId.h" #include "MizarWidgets/SamplingWithFrameTrackInputWidget.h" #include "TestUtils/ContainerHelpers.h" using orbit_mizar_base::TID; using testing::ElementsAreArray; using testing::NotNull; using testing::Return; using testing::ReturnRef; using testing::UnorderedElementsAreArray; using orbit_test_utils::MakeMap; namespace { class MockPairedData { public: MOCK_METHOD((const absl::flat_hash_map<TID, std::string>&), TidToNames, (), (const)); MOCK_METHOD((const absl::flat_hash_map<TID, std::uint64_t>&), TidToCallstackSampleCounts, (), (const)); MOCK_METHOD((const absl::flat_hash_map<uint64_t, orbit_client_data::ScopeInfo>), GetFrameTracks, (), (const)); }; } // namespace namespace orbit_mizar_widgets { constexpr TID kTid(0x3EAD1); constexpr TID kOtherTid(0x3EAD2); const std::string kThreadName = "Thread"; const std::string kOtherThreadName = "Other Thread"; constexpr uint64_t kThreadSamplesCount = 5; constexpr uint64_t kOtherThreadSamplesCount = 2; const absl::flat_hash_map<TID, std::string> kTidToName = {{kTid, kThreadName}, {kOtherTid, kOtherThreadName}}; const absl::flat_hash_map<TID, uint64_t> kTidToCount = {{kTid, kThreadSamplesCount}, {kOtherTid, kOtherThreadSamplesCount}}; constexpr size_t kThreadCount = 2; static std::string MakeThreadListItemString(std::string_view name, TID tid) { return absl::StrFormat("[%u] %s", *tid, name); } const std::vector<std::string> kThreadNamesSorted = { MakeThreadListItemString(kThreadName, kTid), MakeThreadListItemString(kOtherThreadName, kOtherTid)}; const QString kInputName = QStringLiteral("InputName"); constexpr size_t kFrameTracksCount = 3; constexpr std::array<uint64_t, kFrameTracksCount> kScopeIds = {1, 2, 10}; constexpr std::array<std::string_view, kFrameTracksCount> kFrameTrackNames = {"Foo", "Boo", "Manual"}; constexpr std::array<orbit_client_data::ScopeType, kFrameTracksCount> kScopeInfoTypes = { orbit_client_data::ScopeType::kDynamicallyInstrumentedFunction, orbit_client_data::ScopeType::kDynamicallyInstrumentedFunction, orbit_client_data::ScopeType::kApiScope}; const absl::flat_hash_map<orbit_client_data::ScopeType, std::string> kScopeTypeToString = { {orbit_client_data::ScopeType::kDynamicallyInstrumentedFunction, "[ D]"}, {orbit_client_data::ScopeType::kApiScope, "[MS]"}}; const std::vector<std::string> kExpectedFrameTrackListContent = {"[ D] Boo", "[ D] Foo", "[MS] Manual"}; constexpr std::array<uint64_t, kFrameTracksCount> kScopeIdsInExpectedOrder = {2, 1, 10}; const std::vector<orbit_client_data::ScopeInfo> kScopeInfos = [] { std::vector<orbit_client_data::ScopeInfo> result; for (size_t i = 0; i < kFrameTracksCount; ++i) { result.emplace_back(std::string(kFrameTrackNames[i]), kScopeInfoTypes[i]); } return result; }(); const absl::flat_hash_map<uint64_t, orbit_client_data::ScopeInfo> kFrameTracks = MakeMap(kScopeIds, kScopeInfos); constexpr const char* kOrgName = "The Orbit Authors"; class SamplingWithFrameTrackInputWidgetTest : public ::testing::Test { public: SamplingWithFrameTrackInputWidgetTest() : widget_(std::make_unique<SamplingWithFrameTrackInputWidgetTmpl<MockPairedData>>(nullptr)) { QApplication::setOrganizationName(kOrgName); QApplication::setApplicationName("SamplingWithFrameTrackInputWidgetTest.InitIsCorrect"); EXPECT_CALL(data_, TidToNames).WillRepeatedly(ReturnRef(kTidToName)); EXPECT_CALL(data_, TidToCallstackSampleCounts).WillRepeatedly(ReturnRef(kTidToCount)); EXPECT_CALL(data_, GetFrameTracks).WillRepeatedly(Return(kFrameTracks)); widget_->Init(data_, kInputName); // TODO(b/238058915) use ASSERT_THAT title_ = widget_->findChild<QLabel*>("title_"); EXPECT_THAT(title_, NotNull()); thread_list_ = widget_->findChild<QListWidget*>("thread_list_"); EXPECT_THAT(thread_list_, NotNull()); frame_track_list_ = widget_->findChild<QComboBox*>("frame_track_list_"); EXPECT_THAT(thread_list_, NotNull()); start_ms_ = widget_->findChild<QLineEdit*>("start_ms_"); EXPECT_THAT(start_ms_, NotNull()); } void SelectThreadListRow(int row) const { thread_list_->selectionModel()->select(thread_list_->model()->index(row, 0), QItemSelectionModel::Select); } void ClearThreadListSelection() const { thread_list_->selectionModel()->clearSelection(); } void ExpectSelectedTidsAre(std::initializer_list<TID> tids) const { EXPECT_THAT(widget_->MakeConfig().tids, UnorderedElementsAreArray(tids)); } void ExpectSelectedFrameTrackIdIs(uint32_t scope_id) const { EXPECT_EQ(widget_->MakeConfig().frame_track_scope_id, scope_id); } void ExpectRelativeStartNsIs(uint64_t start_relative_ns_) const { EXPECT_EQ(widget_->MakeConfig().start_relative_ns, start_relative_ns_); } MockPairedData data_; std::unique_ptr<SamplingWithFrameTrackInputWidgetTmpl<MockPairedData>> widget_; QLabel* title_; QListWidget* thread_list_; QComboBox* frame_track_list_; QLineEdit* start_ms_; }; TEST_F(SamplingWithFrameTrackInputWidgetTest, InitIsCorrect) { EXPECT_EQ(title_->text(), kInputName); EXPECT_EQ(thread_list_->count(), kThreadCount); for (int i = 0; i < thread_list_->count(); ++i) { QListWidgetItem* item = thread_list_->item(i); EXPECT_THAT(item, NotNull()); EXPECT_EQ(item->text().toStdString(), kThreadNamesSorted[i]); } } TEST_F(SamplingWithFrameTrackInputWidgetTest, OnThreadSelectionChangedIsCorrect) { SelectThreadListRow(0); ExpectSelectedTidsAre({kTid}); SelectThreadListRow(1); ExpectSelectedTidsAre({kTid, kOtherTid}); ClearThreadListSelection(); SelectThreadListRow(1); ExpectSelectedTidsAre({kOtherTid}); } TEST_F(SamplingWithFrameTrackInputWidgetTest, OnFrameTrackSelectionChangedIsCorrect) { std::vector<std::string> frame_track_list_content; for (int i = 0; i < frame_track_list_->count(); ++i) { frame_track_list_content.push_back(frame_track_list_->itemText(i).toStdString()); } EXPECT_THAT(frame_track_list_content, ElementsAreArray(frame_track_list_content)); frame_track_list_->setCurrentIndex(0); ExpectSelectedFrameTrackIdIs(kScopeIdsInExpectedOrder[0]); frame_track_list_->setCurrentIndex(2); ExpectSelectedFrameTrackIdIs(kScopeIdsInExpectedOrder[2]); frame_track_list_->setCurrentIndex(1); ExpectSelectedFrameTrackIdIs(kScopeIdsInExpectedOrder[1]); } TEST_F(SamplingWithFrameTrackInputWidgetTest, OnStartMsChangedIsCorrect) { start_ms_->setText(""); ExpectRelativeStartNsIs(0); start_ms_->setText("123"); ExpectRelativeStartNsIs(123000); start_ms_->setText("0123"); ExpectRelativeStartNsIs(123000); start_ms_->setText("99999999999999999999999999"); ExpectRelativeStartNsIs(static_cast<uint64_t>(std::numeric_limits<uint64_t>::max())); start_ms_->setText("-0"); ExpectRelativeStartNsIs(0); start_ms_->setText("-0"); ExpectRelativeStartNsIs(0); } } // namespace orbit_mizar_widgets<commit_msg>Use ASSERT_THAT for null checks in SamplingWithFrameTrackInputWidgetTest (#3895)<commit_after>// Copyright (c) 2022 The Orbit 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 <absl/container/flat_hash_map.h> #include <absl/strings/str_format.h> #include <gmock/gmock.h> #include <gtest/gtest.h> #include <QApplication> #include <QComboBox> #include <QLineEdit> #include <QListWidget> #include <QStringLiteral> #include <QTest> #include <array> #include <limits> #include <string> #include "ClientData/ScopeInfo.h" #include "MizarBase/ThreadId.h" #include "MizarWidgets/SamplingWithFrameTrackInputWidget.h" #include "TestUtils/ContainerHelpers.h" using orbit_mizar_base::TID; using testing::ElementsAreArray; using testing::NotNull; using testing::Return; using testing::ReturnRef; using testing::UnorderedElementsAreArray; using orbit_test_utils::MakeMap; namespace { class MockPairedData { public: MOCK_METHOD((const absl::flat_hash_map<TID, std::string>&), TidToNames, (), (const)); MOCK_METHOD((const absl::flat_hash_map<TID, std::uint64_t>&), TidToCallstackSampleCounts, (), (const)); MOCK_METHOD((const absl::flat_hash_map<uint64_t, orbit_client_data::ScopeInfo>), GetFrameTracks, (), (const)); }; } // namespace namespace orbit_mizar_widgets { constexpr TID kTid(0x3EAD1); constexpr TID kOtherTid(0x3EAD2); const std::string kThreadName = "Thread"; const std::string kOtherThreadName = "Other Thread"; constexpr uint64_t kThreadSamplesCount = 5; constexpr uint64_t kOtherThreadSamplesCount = 2; const absl::flat_hash_map<TID, std::string> kTidToName = {{kTid, kThreadName}, {kOtherTid, kOtherThreadName}}; const absl::flat_hash_map<TID, uint64_t> kTidToCount = {{kTid, kThreadSamplesCount}, {kOtherTid, kOtherThreadSamplesCount}}; constexpr size_t kThreadCount = 2; static std::string MakeThreadListItemString(std::string_view name, TID tid) { return absl::StrFormat("[%u] %s", *tid, name); } const std::vector<std::string> kThreadNamesSorted = { MakeThreadListItemString(kThreadName, kTid), MakeThreadListItemString(kOtherThreadName, kOtherTid)}; const QString kInputName = QStringLiteral("InputName"); constexpr size_t kFrameTracksCount = 3; constexpr std::array<uint64_t, kFrameTracksCount> kScopeIds = {1, 2, 10}; constexpr std::array<std::string_view, kFrameTracksCount> kFrameTrackNames = {"Foo", "Boo", "Manual"}; constexpr std::array<orbit_client_data::ScopeType, kFrameTracksCount> kScopeInfoTypes = { orbit_client_data::ScopeType::kDynamicallyInstrumentedFunction, orbit_client_data::ScopeType::kDynamicallyInstrumentedFunction, orbit_client_data::ScopeType::kApiScope}; const absl::flat_hash_map<orbit_client_data::ScopeType, std::string> kScopeTypeToString = { {orbit_client_data::ScopeType::kDynamicallyInstrumentedFunction, "[ D]"}, {orbit_client_data::ScopeType::kApiScope, "[MS]"}}; const std::vector<std::string> kExpectedFrameTrackListContent = {"[ D] Boo", "[ D] Foo", "[MS] Manual"}; constexpr std::array<uint64_t, kFrameTracksCount> kScopeIdsInExpectedOrder = {2, 1, 10}; const std::vector<orbit_client_data::ScopeInfo> kScopeInfos = [] { std::vector<orbit_client_data::ScopeInfo> result; for (size_t i = 0; i < kFrameTracksCount; ++i) { result.emplace_back(std::string(kFrameTrackNames[i]), kScopeInfoTypes[i]); } return result; }(); const absl::flat_hash_map<uint64_t, orbit_client_data::ScopeInfo> kFrameTracks = MakeMap(kScopeIds, kScopeInfos); class SamplingWithFrameTrackInputWidgetTest : public ::testing::Test { public: SamplingWithFrameTrackInputWidgetTest() : widget_(std::make_unique<SamplingWithFrameTrackInputWidgetTmpl<MockPairedData>>(nullptr)) { EXPECT_CALL(data_, TidToNames).WillRepeatedly(ReturnRef(kTidToName)); EXPECT_CALL(data_, TidToCallstackSampleCounts).WillRepeatedly(ReturnRef(kTidToCount)); EXPECT_CALL(data_, GetFrameTracks).WillRepeatedly(Return(kFrameTracks)); widget_->Init(data_, kInputName); } void SetUp() override { title_ = widget_->findChild<QLabel*>("title_"); ASSERT_THAT(title_, NotNull()); thread_list_ = widget_->findChild<QListWidget*>("thread_list_"); ASSERT_THAT(thread_list_, NotNull()); frame_track_list_ = widget_->findChild<QComboBox*>("frame_track_list_"); ASSERT_THAT(thread_list_, NotNull()); start_ms_ = widget_->findChild<QLineEdit*>("start_ms_"); ASSERT_THAT(start_ms_, NotNull()); } void SelectThreadListRow(int row) const { thread_list_->selectionModel()->select(thread_list_->model()->index(row, 0), QItemSelectionModel::Select); } void ClearThreadListSelection() const { thread_list_->selectionModel()->clearSelection(); } void ExpectSelectedTidsAre(std::initializer_list<TID> tids) const { EXPECT_THAT(widget_->MakeConfig().tids, UnorderedElementsAreArray(tids)); } void ExpectSelectedFrameTrackIdIs(uint32_t scope_id) const { EXPECT_EQ(widget_->MakeConfig().frame_track_scope_id, scope_id); } void ExpectRelativeStartNsIs(uint64_t start_relative_ns_) const { EXPECT_EQ(widget_->MakeConfig().start_relative_ns, start_relative_ns_); } MockPairedData data_; std::unique_ptr<SamplingWithFrameTrackInputWidgetTmpl<MockPairedData>> widget_; QLabel* title_{}; QListWidget* thread_list_{}; QComboBox* frame_track_list_{}; QLineEdit* start_ms_{}; }; TEST_F(SamplingWithFrameTrackInputWidgetTest, InitIsCorrect) { EXPECT_EQ(title_->text(), kInputName); EXPECT_EQ(thread_list_->count(), kThreadCount); for (int i = 0; i < thread_list_->count(); ++i) { QListWidgetItem* item = thread_list_->item(i); EXPECT_THAT(item, NotNull()); EXPECT_EQ(item->text().toStdString(), kThreadNamesSorted[i]); } } TEST_F(SamplingWithFrameTrackInputWidgetTest, OnThreadSelectionChangedIsCorrect) { SelectThreadListRow(0); ExpectSelectedTidsAre({kTid}); SelectThreadListRow(1); ExpectSelectedTidsAre({kTid, kOtherTid}); ClearThreadListSelection(); SelectThreadListRow(1); ExpectSelectedTidsAre({kOtherTid}); } TEST_F(SamplingWithFrameTrackInputWidgetTest, OnFrameTrackSelectionChangedIsCorrect) { std::vector<std::string> frame_track_list_content; for (int i = 0; i < frame_track_list_->count(); ++i) { frame_track_list_content.push_back(frame_track_list_->itemText(i).toStdString()); } EXPECT_THAT(frame_track_list_content, ElementsAreArray(frame_track_list_content)); frame_track_list_->setCurrentIndex(0); ExpectSelectedFrameTrackIdIs(kScopeIdsInExpectedOrder[0]); frame_track_list_->setCurrentIndex(2); ExpectSelectedFrameTrackIdIs(kScopeIdsInExpectedOrder[2]); frame_track_list_->setCurrentIndex(1); ExpectSelectedFrameTrackIdIs(kScopeIdsInExpectedOrder[1]); } TEST_F(SamplingWithFrameTrackInputWidgetTest, OnStartMsChangedIsCorrect) { start_ms_->setText(""); ExpectRelativeStartNsIs(0); start_ms_->setText("123"); ExpectRelativeStartNsIs(123000); start_ms_->setText("0123"); ExpectRelativeStartNsIs(123000); start_ms_->setText("99999999999999999999999999"); ExpectRelativeStartNsIs(static_cast<uint64_t>(std::numeric_limits<uint64_t>::max())); start_ms_->setText("-0"); ExpectRelativeStartNsIs(0); start_ms_->setText("-0"); ExpectRelativeStartNsIs(0); } } // namespace orbit_mizar_widgets<|endoftext|>
<commit_before>// This is sometimes required to support the full curses API #define _XOPEN_SOURCE #define _XOPEN_SOURCE_EXTENDED #ifdef __GNUC__ // Enable printf and scanf argument checking #define GCC_PRINTF #define GCC_SCANF #endif #include <curses.h> #include <climits> #include <cstdio> #include <unordered_map> #include <QString> #include <QTextBoundaryFinder> #include "lirch_constants.h" #include "plugins/lirch_plugin.h" #include "plugins/display_messages.h" #include "plugins/notify_messages.h" #include "plugins/edict_messages.h" #include "plugins/channel_messages.h" #include "core/core_messages.h" namespace std { template <> struct hash<QString> { size_t operator()(const QString& v) const { return std::hash<std::string>()(v.toStdString()); } }; } inline char CTRL(char c) { //Leave only the lower 5 bits, so the return value is the numeric value //of CTRL+key (e.g. CTRL('c') gives you 3, which is the value you get //when hitting ctrl-c) return c&0x1f; } using namespace std; template <class... args> string strprintf(const string &format, args... a) { //Thankfully, the C++ standard grabbed the definition from POSIX //instead of Windows, so I don't have to binary-search the correct //string size. int size=snprintf(NULL, 0, format.c_str(), a...); //Add padding for the terminating byte vector<char> s(size+1); //We can use sprintf instead of snprintf because we know the buffer is large enough sprintf(s.data(), format.c_str(), a...); return s.data(); } //Same as wprintf, but handles unicode characters properly template <class... args> void wprintu(WINDOW *w, const string &format, args... a) { string s=strprintf(format, a...); for (unsigned char c : s) waddch(w, c|(c>0x7f ? A_ALTCHARSET : 0)); } //This wraps WINDOW pointers so they're be destroyed on exit class WindowWrapper { public: WindowWrapper(WINDOW *ww) : w(ww, delwin) {} WindowWrapper() {int maxx, maxy; getmaxyx(stdscr, maxy, maxx); w=shared_ptr<WINDOW>(newpad(maxy-1, maxx), delwin); scrollok(get(), TRUE);} WINDOW *get() const {return w.get();} operator WINDOW*() const {return get();} WINDOW& operator*() const {return *w;} WINDOW* operator->() const {return get();} private: shared_ptr<WINDOW> w; }; void runplugin(plugin_pipe &p, const string &name) { QString input; QString channel="default"; int maxx, maxy; getmaxyx(stdscr, maxy, maxx); //10000 lines of scrollback should be enough for anyone //WindowWrapper channel_output=newpad(10000, maxx); unordered_map<QString, WindowWrapper> channel_windows; if (channel_windows["default"]==nullptr) return; WindowWrapper input_display=newwin(1, maxx-1, maxy-1, 0); if (input_display==nullptr) return; //Be lazy and let the input scroll scrollok(input_display, TRUE); //p.write(registration_message::create(-30000, name, "display")); while (true) { wint_t key; int rc=get_wch(&key); if (rc==OK) { if (key=='\r' || key=='\n') { p.write(raw_edict_message::create(input,channel)); input=""; } else if (key==WEOF) break; else input.push_back(QString::fromWcharArray(&key, 1)); } else if (rc==KEY_CODE_YES) { if (key==KEY_BACKSPACE) { QTextBoundaryFinder bounds(QTextBoundaryFinder::Grapheme, input); bounds.toEnd(); int pos=bounds.toPreviousBoundary(); if (pos!=-1) { input.remove(pos, INT_MAX); } } else if (key==KEY_ENTER) { p.write(raw_edict_message::create(input,channel)); input=""; } } while (p.has_message()) { message m=p.read(); if (m.type=="shutdown") { return; } else if (m.type=="registration_status") { auto s=dynamic_cast<registration_status *>(m.getdata()); if (!s) continue; if (!s->status) { if (s->priority>-32000) p.write(registration_message::create(s->priority-1, name, s->type)); } } else if (m.type=="display") { auto s=dynamic_cast<display_message *>(m.getdata()); if (!s) continue; p.write(m.decrement_priority()); QString message_channel=s->channel; string nick=s->nick.toLocal8Bit().constData(); string contents=s->contents.toLocal8Bit().constData(); if (s->channel=="") s->channel=channel; if (channel_windows.count(message_channel)!=0) { if(s->subtype==display_message_subtype::NORMAL) wprintu(channel_windows[message_channel], "<%s> %s\n", nick.c_str(), contents.c_str()); if(s->subtype==display_message_subtype::ME) wprintu(channel_windows[message_channel], "* %s %s\n", nick.c_str(), contents.c_str()); if(s->subtype==display_message_subtype::NOTIFY) wprintu(channel_windows[message_channel], "‼‽ %s\n", contents.c_str()); } } else if (m.type=="set_channel") { auto i=dynamic_cast<set_channel *>(m.getdata()); if (!i) continue; p.write(m.decrement_priority()); if (i->channel=="") p.write(notify_message::create(channel, "On channel "+channel)); else channel=i->channel; } else if (m.type=="leave_channel") { auto i=dynamic_cast<leave_channel *>(m.getdata()); if (!i) continue; p.write(m.decrement_priority()); channel_windows.erase(i->channel); } else p.write(m.decrement_priority()); } int x,y; getyx(channel_windows[channel], y, x); pnoutrefresh(channel_windows[channel], max(y-(maxy-1),0), 0, 0,0,maxy-2,maxx-1); wmove(input_display, 0, 0); wprintu(input_display, "\n%s", input.toLocal8Bit().constData()); wnoutrefresh(input_display); //This doesn't need to run all the time, but we should be able //to cope with the screen refreshing at 10Hz doupdate(); } p.write(core_quit_message::create()); } void run(plugin_pipe p, string name) { p.write(registration_message::create(-30000, name, "display")); p.write(registration_message::create(-30000, name, "set_channel")); p.write(registration_message::create(-30000, name, "leave_channel")); //Set the delay when hitting escape to 10 milliseconds, unless it was //already set. The ESCDELAY variable is not supported in all curses //implementations, but should not cause problems in implementations //that ignore it. setenv("ESCDELAY", "10", 0); //Initialize curses initscr(); //Don't buffer typed characters cbreak(); //Wain no more than a tenth of a second for input timeout(100); noecho(); //Makes enter return \r instead of \n nonl(); //Flush the input buffer if an interrupt key is pressed. This ensures //we don't miss keystrokes in the event of a SIGSTOP intrflush(stdscr, FALSE); //Enable keycodes keypad(stdscr, TRUE); runplugin(p, name); //Make sure to always restore the terminal to a sane configuration endwin(); return; } <commit_msg>Nothing to see here<commit_after>// This is sometimes required to support the full curses API #define _XOPEN_SOURCE #define _XOPEN_SOURCE_EXTENDED #ifdef __GNUC__ // Enable printf and scanf argument checking #define GCC_PRINTF #define GCC_SCANF #endif #include <curses.h> #include <climits> #include <cstdio> #include <unordered_map> #include <QString> #include <QTextBoundaryFinder> #include "lirch_constants.h" #include "plugins/lirch_plugin.h" #include "plugins/display_messages.h" #include "plugins/notify_messages.h" #include "plugins/edict_messages.h" #include "plugins/channel_messages.h" #include "core/core_messages.h" namespace std { template <> struct hash<QString> { size_t operator()(const QString& v) const { return std::hash<std::string>()(v.toStdString()); } }; } inline char CTRL(char c) { //Leave only the lower 5 bits, so the return value is the numeric value //of CTRL+key (e.g. CTRL('c') gives you 3, which is the value you get //when hitting ctrl-c) return c&0x1f; } using namespace std; template <class... args> string strprintf(const string &format, args... a) { //Thankfully, the C++ standard grabbed the definition from POSIX //instead of Windows, so I don't have to binary-search the correct //string size. int size=snprintf(NULL, 0, format.c_str(), a...); //Add padding for the terminating byte vector<char> s(size+1); //We can use sprintf instead of snprintf because we know the buffer is large enough sprintf(s.data(), format.c_str(), a...); return s.data(); } //Same as wprintf, but handles unicode characters properly template <class... args> void wprintu(WINDOW *w, const string &format, args... a) { string s=strprintf(format, a...); for (unsigned char c : s) waddch(w, c|(c>0x7f ? A_ALTCHARSET : 0)); } //This wraps WINDOW pointers so they're be destroyed on exit class WindowWrapper { public: WindowWrapper(WINDOW *ww) : w(ww, delwin) {} WindowWrapper() {int maxx, maxy; getmaxyx(stdscr, maxy, maxx); w=shared_ptr<WINDOW>(newpad(maxy-1, maxx), delwin); scrollok(get(), TRUE);} WINDOW *get() const {return w.get();} operator WINDOW*() const {return get();} WINDOW& operator*() const {return *w;} WINDOW* operator->() const {return get();} private: shared_ptr<WINDOW> w; }; void runplugin(plugin_pipe &p, const string &name) { QString input; QString channel="default"; int maxx, maxy; getmaxyx(stdscr, maxy, maxx); //10000 lines of scrollback should be enough for anyone //WindowWrapper channel_output=newpad(10000, maxx); unordered_map<QString, WindowWrapper> channel_windows; if (channel_windows["default"]==nullptr) return; WindowWrapper input_display=newwin(1, maxx-1, maxy-1, 0); if (input_display==nullptr) return; //Be lazy and let the input scroll scrollok(input_display, TRUE); //p.write(registration_message::create(-30000, name, "display")); while (true) { wint_t key; int rc=get_wch(&key); if (rc==OK) { if (key=='\r' || key=='\n') { p.write(raw_edict_message::create(input,channel)); input=""; } else if (key==WEOF) { //Quit since we have no more input break; } else { //This conversion is always valid, since key's //only valid values are valid wchar_t values //and WEOF, and we know it's not WEOF. wchar_t tmp=key; input.push_back(QString::fromWCharArray(&tmp, 1)); } } else if (rc==KEY_CODE_YES) { if (key==KEY_BACKSPACE) { QTextBoundaryFinder bounds(QTextBoundaryFinder::Grapheme, input); bounds.toEnd(); int pos=bounds.toPreviousBoundary(); if (pos!=-1) { input.remove(pos, INT_MAX); } } else if (key==KEY_ENTER) { p.write(raw_edict_message::create(input,channel)); input=""; } } while (p.has_message()) { message m=p.read(); if (m.type=="shutdown") { return; } else if (m.type=="registration_status") { auto s=dynamic_cast<registration_status *>(m.getdata()); if (!s) continue; if (!s->status) { if (s->priority>-32000) p.write(registration_message::create(s->priority-1, name, s->type)); } } else if (m.type=="display") { auto s=dynamic_cast<display_message *>(m.getdata()); if (!s) continue; p.write(m.decrement_priority()); QString message_channel=s->channel; string nick=s->nick.toLocal8Bit().constData(); string contents=s->contents.toLocal8Bit().constData(); if (s->channel=="") s->channel=channel; if (channel_windows.count(message_channel)!=0) { if(s->subtype==display_message_subtype::NORMAL) wprintu(channel_windows[message_channel], "<%s> %s\n", nick.c_str(), contents.c_str()); if(s->subtype==display_message_subtype::ME) wprintu(channel_windows[message_channel], "* %s %s\n", nick.c_str(), contents.c_str()); if(s->subtype==display_message_subtype::NOTIFY) wprintu(channel_windows[message_channel], "‼‽ %s\n", contents.c_str()); } } else if (m.type=="set_channel") { auto i=dynamic_cast<set_channel *>(m.getdata()); if (!i) continue; p.write(m.decrement_priority()); if (i->channel=="") p.write(notify_message::create(channel, "On channel "+channel)); else channel=i->channel; } else if (m.type=="leave_channel") { auto i=dynamic_cast<leave_channel *>(m.getdata()); if (!i) continue; p.write(m.decrement_priority()); channel_windows.erase(i->channel); } else p.write(m.decrement_priority()); } int x,y; getyx(channel_windows[channel], y, x); pnoutrefresh(channel_windows[channel], max(y-(maxy-1),0), 0, 0,0,maxy-2,maxx-1); wmove(input_display, 0, 0); wprintu(input_display, "\n%s", input.toLocal8Bit().constData()); wnoutrefresh(input_display); //This doesn't need to run all the time, but we should be able //to cope with the screen refreshing at 10Hz doupdate(); } p.write(core_quit_message::create()); } void run(plugin_pipe p, string name) { p.write(registration_message::create(-30000, name, "display")); p.write(registration_message::create(-30000, name, "set_channel")); p.write(registration_message::create(-30000, name, "leave_channel")); //Set the delay when hitting escape to 10 milliseconds, unless it was //already set. The ESCDELAY variable is not supported in all curses //implementations, but should not cause problems in implementations //that ignore it. setenv("ESCDELAY", "10", 0); //Initialize curses initscr(); //Don't buffer typed characters cbreak(); //Wain no more than a tenth of a second for input timeout(100); noecho(); //Makes enter return \r instead of \n nonl(); //Flush the input buffer if an interrupt key is pressed. This ensures //we don't miss keystrokes in the event of a SIGSTOP intrflush(stdscr, FALSE); //Enable keycodes keypad(stdscr, TRUE); runplugin(p, name); //Make sure to always restore the terminal to a sane configuration endwin(); return; } <|endoftext|>
<commit_before>/* mutexops.cpp: Copyright (C) 2007 by Steven Yi Mutex lock and unlocking opcodes, used for when running Csound with multiple threads This file is part of Csound. The Csound 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. Csound 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 Csound; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <csdl.h> #include "csGblMtx.h" #include <map> static std::map<CSOUND *, std::map<size_t, std::map<size_t, void *> > > mutexes; typedef struct { OPDS h; MYFLT *ilocknum; void *mutex; } OPCODE_MUTEX; static void * getMutex(CSOUND *csound, size_t instrNum, size_t lockNum) { csound_global_mutex_lock(); if(mutexes.find(csound) == mutexes.end()) { std::map<size_t, std::map<size_t, void *> > values; mutexes[csound] = values; } if(mutexes[csound].find(instrNum) == mutexes[csound].end()) { std::map<size_t, void*> mutexMap; mutexes[csound][instrNum] = mutexMap; } if (mutexes[csound][instrNum].find(lockNum) == mutexes[csound][instrNum].end()) { void * mutex = csound->Create_Mutex(0); mutexes[csound][instrNum][lockNum] = mutex; csound->Message(csound, "Created new mutex [%ld:%ld]\n", (long)instrNum, (long)lockNum); } csound_global_mutex_unlock(); return mutexes[csound][instrNum][lockNum]; } static int mutexLock(CSOUND *csound, OPCODE_MUTEX *p) { if(p->mutex == NULL) { size_t instrNum = static_cast<size_t>(p->h.insdshead->p1); size_t lockNum = static_cast<size_t>(*p->ilocknum); p->mutex = getMutex(csound, instrNum, lockNum); } csound->LockMutex(p->mutex); return OK; } static int mutexUnlock(CSOUND *csound, OPCODE_MUTEX *p) { if(p->mutex == NULL) { size_t instrNum = static_cast<size_t>(p->h.insdshead->p1); size_t lockNum = static_cast<size_t>(*p->ilocknum); p->mutex = getMutex(csound, instrNum, lockNum); } csound->UnlockMutex(p->mutex); return OK; } #define S(x) sizeof(x) static OENTRY localops[] = { { "mutex_lock", S(OPCODE_MUTEX), 2, "", "i", NULL, (SUBR)mutexLock, NULL }, { "mutex_unlock", S(OPCODE_MUTEX), 2, "", "i", NULL, (SUBR)mutexUnlock, NULL }, { "mutex_locki", S(OPCODE_MUTEX), 1, "", "i", (SUBR)mutexLock, NULL, NULL }, { "mutex_unlocki", S(OPCODE_MUTEX), 1, "", "i", (SUBR)mutexUnlock, NULL, NULL } }; LINKAGE <commit_msg>no message<commit_after>/* mutexops.cpp: Copyright (C) 2007 by Steven Yi Mutex lock and unlocking opcodes, used for when running Csound with multiple threads This file is part of Csound. The Csound 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. Csound 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 Csound; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "csdl.h" #include "csGblMtx.h" #include <map> static std::map<CSOUND *, std::map<size_t, std::map<size_t, void *> > > mutexes; typedef struct { OPDS h; MYFLT *ilocknum; void *mutex; } OPCODE_MUTEX; static void * getMutex(CSOUND *csound, size_t instrNum, size_t lockNum) { csound_global_mutex_lock(); if(mutexes.find(csound) == mutexes.end()) { std::map<size_t, std::map<size_t, void *> > values; mutexes[csound] = values; } if(mutexes[csound].find(instrNum) == mutexes[csound].end()) { std::map<size_t, void*> mutexMap; mutexes[csound][instrNum] = mutexMap; } if (mutexes[csound][instrNum].find(lockNum) == mutexes[csound][instrNum].end()) { void * mutex = csound->Create_Mutex(0); mutexes[csound][instrNum][lockNum] = mutex; csound->Message(csound, "Created new mutex [%ld:%ld]\n", (long)instrNum, (long)lockNum); } csound_global_mutex_unlock(); return mutexes[csound][instrNum][lockNum]; } static int mutexLock(CSOUND *csound, OPCODE_MUTEX *p) { if(p->mutex == NULL) { size_t instrNum = static_cast<size_t>(p->h.insdshead->p1); size_t lockNum = static_cast<size_t>(*p->ilocknum); p->mutex = getMutex(csound, instrNum, lockNum); } csound->LockMutex(p->mutex); return OK; } static int mutexUnlock(CSOUND *csound, OPCODE_MUTEX *p) { if(p->mutex == NULL) { size_t instrNum = static_cast<size_t>(p->h.insdshead->p1); size_t lockNum = static_cast<size_t>(*p->ilocknum); p->mutex = getMutex(csound, instrNum, lockNum); } csound->UnlockMutex(p->mutex); return OK; } #define S(x) sizeof(x) static OENTRY localops[] = { { "mutex_lock", S(OPCODE_MUTEX), 2, "", "i", NULL, (SUBR)mutexLock, NULL }, { "mutex_unlock", S(OPCODE_MUTEX), 2, "", "i", NULL, (SUBR)mutexUnlock, NULL }, { "mutex_locki", S(OPCODE_MUTEX), 1, "", "i", (SUBR)mutexLock, NULL, NULL }, { "mutex_unlocki", S(OPCODE_MUTEX), 1, "", "i", (SUBR)mutexUnlock, NULL, NULL } }; LINKAGE <|endoftext|>
<commit_before>#include <Adafruit_GPS.h> #include <SoftwareSerial.h> #include <SPI.h> #include <SD.h> File myFile; uint32_t lastsave(0); SoftwareSerial mySerial(3, 2); Adafruit_GPS GPS(&mySerial); #define GPSECHO false boolean usingInterrupt = false; void useInterrupt(boolean); // Func prototype keeps Arduino 0023 happy String getFileName() { File counter; counter = SD.open(F("counter.txt"), FILE_WRITE); counter.seek(0); uint32_t num = 0; if(counter.size()>0) num = counter.read(); counter.seek(0); counter.write(num+1); counter.close(); String str = String(num); return "GPS"+str+".txt"; } void setup() { Serial.begin(115200); GPS.begin(9600); GPS.sendCommand(PMTK_SET_NMEA_OUTPUT_RMCGGA); GPS.sendCommand(PMTK_SET_NMEA_UPDATE_1HZ); // 1 Hz update rate GPS.sendCommand(PGCMD_ANTENNA); useInterrupt(true); delay(1000); mySerial.println(PMTK_Q_RELEASE); if (!SD.begin(4)) { return; } String fileName = getFileName(); myFile = SD.open(fileName, FILE_WRITE); myFile.println(F("date, time, fix, quality, latitude, longitude, altitude(metres), satellites")); myFile.flush(); } SIGNAL(TIMER0_COMPA_vect) { char c = GPS.read(); #ifdef UDR0 if (GPSECHO) if (c) UDR0 = c; #endif } void useInterrupt(boolean v) { if (v) { OCR0A = 0xAF; TIMSK0 |= _BV(OCIE0A); usingInterrupt = true; } else { TIMSK0 &= ~_BV(OCIE0A); usingInterrupt = false; } } uint32_t timer = millis(); char* getRow(char *row, Adafruit_GPS& gpsNow) { char lat[15], lng[16], alt[9], spd[6], agl[7]; sprintf(row, "%d/%d/%d, %d:%d:%d, %d, %d, %s, %s, %s, %d", gpsNow.day, gpsNow.month, gpsNow.year, gpsNow.hour, gpsNow.minute, gpsNow.seconds, gpsNow.fix, gpsNow.fixquality, dtostrf(gpsNow.latitudeDegrees, 14, 10, lat), dtostrf(gpsNow.longitudeDegrees, 15, 10, lng), dtostrf(gpsNow.altitude, 8, 2, alt), gpsNow.satellites); return row; } void loop() { if(myFile){ if (! usingInterrupt) { char c = GPS.read(); if (GPSECHO) if (c) Serial.print(c); } if (GPS.newNMEAreceived()) { if (!GPS.parse(GPS.lastNMEA())) return; } if (timer > millis()) timer = millis(); if (millis() - timer > 2000) { timer = millis(); // reset the timer char row[128]; getRow(row, GPS); myFile.println(row); Serial.println(row); myFile.flush(); } } else Serial.print(F("File is corrupt")); }<commit_msg>SD.open(..) is not overloaded to accept F(..)<commit_after>#include <Adafruit_GPS.h> #include <SoftwareSerial.h> #include <SPI.h> #include <SD.h> File myFile; uint32_t lastsave(0); SoftwareSerial mySerial(3, 2); Adafruit_GPS GPS(&mySerial); #define GPSECHO false boolean usingInterrupt = false; void useInterrupt(boolean); // Func prototype keeps Arduino 0023 happy String getFileName() { File counter; counter = SD.open("last", FILE_WRITE); counter.seek(0); uint32_t num = 0; if(counter.size()>0) num = counter.read(); counter.seek(0); counter.write(num+1); counter.close(); String str = String(num); return "GPS"+str+".txt"; } void setup() { Serial.begin(115200); GPS.begin(9600); GPS.sendCommand(PMTK_SET_NMEA_OUTPUT_RMCGGA); GPS.sendCommand(PMTK_SET_NMEA_UPDATE_1HZ); // 1 Hz update rate GPS.sendCommand(PGCMD_ANTENNA); useInterrupt(true); delay(1000); mySerial.println(PMTK_Q_RELEASE); if (!SD.begin(4)) { return; } String fileName = getFileName(); myFile = SD.open(fileName, FILE_WRITE); myFile.println(F("date, time, fix, quality, latitude, longitude, altitude(metres), satellites")); myFile.flush(); } SIGNAL(TIMER0_COMPA_vect) { char c = GPS.read(); #ifdef UDR0 if (GPSECHO) if (c) UDR0 = c; #endif } void useInterrupt(boolean v) { if (v) { OCR0A = 0xAF; TIMSK0 |= _BV(OCIE0A); usingInterrupt = true; } else { TIMSK0 &= ~_BV(OCIE0A); usingInterrupt = false; } } uint32_t timer = millis(); char* getRow(char *row, Adafruit_GPS& gpsNow) { char lat[15], lng[16], alt[9], spd[6], agl[7]; sprintf(row, "%d/%d/%d, %d:%d:%d, %d, %d, %s, %s, %s, %d", gpsNow.day, gpsNow.month, gpsNow.year, gpsNow.hour, gpsNow.minute, gpsNow.seconds, gpsNow.fix, gpsNow.fixquality, dtostrf(gpsNow.latitudeDegrees, 14, 10, lat), dtostrf(gpsNow.longitudeDegrees, 15, 10, lng), dtostrf(gpsNow.altitude, 8, 2, alt), gpsNow.satellites); return row; } void loop() { if(myFile){ if (! usingInterrupt) { char c = GPS.read(); if (GPSECHO) if (c) Serial.print(c); } if (GPS.newNMEAreceived()) { if (!GPS.parse(GPS.lastNMEA())) return; } if (timer > millis()) timer = millis(); if (millis() - timer > 2000) { timer = millis(); // reset the timer char row[128]; getRow(row, GPS); myFile.println(row); Serial.println(row); myFile.flush(); } } else Serial.print(F("File is corrupt")); }<|endoftext|>
<commit_before>/****************************************************************************** * _ _____ __________ * * | | / / _ | / __/_ __/ Visibility * * | |/ / __ |_\ \ / / Across * * |___/_/ |_/___/ /_/ Space and Time * * * * This file is part of VAST. It is subject to the license terms in the * * LICENSE file found in the top-level directory of this distribution and at * * http://vast.io/license. No part of VAST, including this file, may be * * copied, modified, propagated, or distributed except according to the terms * * contained in the LICENSE file. * ******************************************************************************/ #include "vast/system/application.hpp" #include <iostream> #include <caf/atom.hpp> #include <caf/error.hpp> #include "vast/detail/adjust_resource_consumption.hpp" #include "vast/detail/assert.hpp" #include "vast/error.hpp" using std::string; using namespace std::chrono_literals; using namespace std::string_literals; using namespace caf; namespace vast::system { application::application() { // TODO: this function has side effects...should we put it elsewhere where // it's explicit to the user? Or perhaps make whatever this function does // simply a configuration option and use it later? detail::adjust_resource_consumption(); } void render_error(const application& app, const caf::error& err, std::ostream& os) { if (err) // The user most likely killed the process via CTRL+C, print nothing. return; os << render(err); if (err.category() == caf::atom("vast")) { auto x = static_cast<vast::ec>(err.code()); switch (x) { default: break; case ec::invalid_subcommand: case ec::missing_subcommand: case ec::unrecognized_option: { auto ctx = err.context(); if (ctx.match_element<std::string>(1)) { auto name = ctx.get_as<std::string>(1); if (auto cmd = resolve(app.root, name)) helptext(*cmd, os); } else { VAST_ASSERT("User visible error contexts must consist of strings!"); } break; } } } } } // namespace vast::system <commit_msg>Fix segfault in error reporting<commit_after>/****************************************************************************** * _ _____ __________ * * | | / / _ | / __/_ __/ Visibility * * | |/ / __ |_\ \ / / Across * * |___/_/ |_/___/ /_/ Space and Time * * * * This file is part of VAST. It is subject to the license terms in the * * LICENSE file found in the top-level directory of this distribution and at * * http://vast.io/license. No part of VAST, including this file, may be * * copied, modified, propagated, or distributed except according to the terms * * contained in the LICENSE file. * ******************************************************************************/ #include "vast/system/application.hpp" #include <iostream> #include <caf/atom.hpp> #include <caf/error.hpp> #include "vast/detail/adjust_resource_consumption.hpp" #include "vast/detail/assert.hpp" #include "vast/error.hpp" using std::string; using namespace std::chrono_literals; using namespace std::string_literals; using namespace caf; namespace vast::system { application::application() { // TODO: this function has side effects...should we put it elsewhere where // it's explicit to the user? Or perhaps make whatever this function does // simply a configuration option and use it later? detail::adjust_resource_consumption(); } void render_error(const application& app, const caf::error& err, std::ostream& os) { if (!err) // The user most likely killed the process via CTRL+C, print nothing. return; os << render(err); if (err.category() == caf::atom("vast")) { auto x = static_cast<vast::ec>(err.code()); switch (x) { default: break; case ec::invalid_subcommand: case ec::missing_subcommand: case ec::unrecognized_option: { auto ctx = err.context(); if (ctx.match_element<std::string>(1)) { auto name = ctx.get_as<std::string>(1); if (auto cmd = resolve(app.root, name)) helptext(*cmd, os); } else { VAST_ASSERT("User visible error contexts must consist of strings!"); } break; } } } } } // namespace vast::system <|endoftext|>
<commit_before>/****************************************************************************** * _ _____ __________ * * | | / / _ | / __/_ __/ Visibility * * | |/ / __ |_\ \ / / Across * * |___/_/ |_/___/ /_/ Space and Time * * * * This file is part of VAST. It is subject to the license terms in the * * LICENSE file found in the top-level directory of this distribution and at * * http://vast.io/license. No part of VAST, including this file, may be * * copied, modified, propagated, or distributed except according to the terms * * contained in the LICENSE file. * ******************************************************************************/ #include "vast/system/table_index.hpp" #include "vast/detail/overload.hpp" #include "vast/expression_visitors.hpp" #include "vast/load.hpp" #include "vast/logger.hpp" #include "vast/save.hpp" namespace vast::system { caf::expected<table_index> make_table_index(path base_dir, type event_type) { caf::error err; table_index result{event_type, base_dir}; result.columns_.resize(table_index::meta_column_count + flat_size(event_type)); return result; } // -- constructors, destructors, and assignment operators ---------------------- table_index::~table_index() noexcept { // nop } // -- persistency -------------------------------------------------------------- caf::error table_index::flush_to_disk() { // Unless `add` was called at least once there's nothing to flush. if (!fully_initialized_) return caf::none; for (auto& col : columns_) { VAST_ASSERT(col != nullptr); auto err = col->flush_to_disk(); if (err) return err; } return caf::none; } /// -- properties -------------------------------------------------------------- column_index& table_index::at(size_t column_index) { return *columns_[column_index]; } column_index* table_index::by_name(std::string_view column_name) { // TODO: support string_view in path's operator / auto fname = base_dir_ / std::string{column_name}; auto pred = [&](const column_index_ptr& ptr) { return ptr->filename() == fname; }; auto i = std::find_if(columns_.begin(), columns_.end(), pred); return i != columns_.end() ? i->get() : nullptr; } caf::error table_index::add(const event& x) { if (fully_initialized_) { for (auto& col : columns_) { VAST_ASSERT(col != nullptr); col->add(x); } return caf::none; } auto fun = [&](column_index& col) -> caf::error { col.add(x); return caf::none; }; auto mk_time = [&] { return make_time_index(meta_dir()); }; auto mk_type = [&] { return make_type_index(meta_dir()); }; return caf::error::eval( [&] { // Column 0 is our meta index for the time. return with_meta_column(0, mk_time, fun); }, [&] { // Column 1 is our meta index for the event type. return with_meta_column(1, mk_type, fun); }, [&]() -> caf::error { // Coluns 2-N are our data fields. auto r = get_if<record_type>(event_type_); if (!r) { auto fac = [&] { return make_flat_data_index(data_dir(), event_type_); }; return with_data_column(0, fac, fun); } // Iterate all types of the record. size_t i = 0; for (auto&& f : record_type::each{*r}) { auto& value_type = f.trace.back()->type; if (!has_skip_attribute(event_type_)) { auto dir = data_dir(); for (auto& k : f.key()) dir /= k; auto fac = [&] { VAST_DEBUG("make field indexer at offset", f.offset, "with type", value_type); return make_field_data_index(data_dir(), value_type, f.offset); }; auto err = with_data_column(i++, fac, fun); if (err) return err; } } return caf::none; }, [&]() -> caf::error { fully_initialized_ = true; return caf::none; }); } path table_index::meta_dir() const { return base_dir_ / "meta"; } path table_index::data_dir() const { return base_dir_ / "data"; } caf::expected<bitmap> table_index::lookup(const predicate& pred) { // For now, we require that the predicate is part of a normalized expression, // i.e., LHS an extractor type and RHS of type data. auto rhs = get_if<data>(pred.rhs); if (!rhs) return ec::invalid_query; // Specialize the predicate for the type. auto resolved = type_resolver{event_type_}(pred); if (!resolved) return std::move(resolved.error()); return lookup(*resolved); } caf::expected<bitmap> table_index::lookup(const expression& expr) { return visit( detail::overload( [&](const disjunction& dis) -> expected<bitmap> { bitmap result; for (auto& op : dis) { auto sub_result = lookup(op); if (!sub_result) return std::move(sub_result.error()); result |= *sub_result; } return result; }, [&](const predicate& p) { return visit( detail::overload( [&](const attribute_extractor& ex, const data& x) { return lookup(p, ex, x); }, [&](const data_extractor& dx, const data& x) { return lookup(p, dx, x); }, [&](const auto&, const auto&) -> expected<bitmap> { // Ignore unexpected lhs/rhs combinations. return bitmap{}; } ), p.lhs, p.rhs); }, [&](const auto&) -> expected<bitmap> { // Ignore unexpected expressions. return bitmap{}; } ), expr); } caf::expected<bitmap> table_index::lookup(const predicate& pred, const attribute_extractor& ex, const data& x) { VAST_IGNORE_UNUSED(x); // We know that the columns vector contains two meta fields: time at index // 0 and type at index 1. static_assert(table_index::meta_column_count == 2); VAST_ASSERT(columns_.size() >= table_index::meta_column_count); if (ex.attr == "time") { VAST_ASSERT(is<timestamp>(x)); auto fac = [&] { return make_time_index(meta_dir()); }; return with_meta_column(0, fac, [&](column_index& col) { return col.lookup(pred); }); } else if (ex.attr == "type") { VAST_ASSERT(is<std::string>(x)); auto fac = [&] { return make_type_index(meta_dir()); }; return with_meta_column(1, fac, [&](column_index& col) { return col.lookup(pred); }); } VAST_WARNING("unsupported attribute:", ex.attr); return ec::invalid_query; } caf::expected<bitmap> table_index::lookup(const predicate& pred, const data_extractor& dx, const data& x) { VAST_IGNORE_UNUSED(x); if (dx.offset.empty()) { VAST_ASSERT(num_data_columns() == 1); auto fac = [&] { return make_flat_data_index(data_dir(), event_type_); }; return with_data_column(0, fac, [&](column_index& col) { return col.lookup(pred); }); } else { auto r = get<record_type>(dx.type); auto k = r.resolve(dx.offset); VAST_ASSERT(k); auto t = r.at(dx.offset); VAST_ASSERT(t); auto fac = [&] { auto p = data_dir(); for (auto& x : *k) p /= x; return make_field_data_index(p, *t, dx.offset); }; auto index = r.flat_index_at(dx.offset); if (!index) { VAST_DEBUG("invalid offset for record type", dx.type); return bitmap{}; } return with_data_column(*index, fac, [&](column_index& col) { return col.lookup(pred); }); } return bitmap{}; } // -- constructors, destructors, and assignment operators ---------------------- table_index::table_index(type event_type, path base_dir) : event_type_(std::move(event_type)), base_dir_(std::move(base_dir)), fully_initialized_(false) { // nop } } // namespace vast::system <commit_msg>Fix column base directory in factory<commit_after>/****************************************************************************** * _ _____ __________ * * | | / / _ | / __/_ __/ Visibility * * | |/ / __ |_\ \ / / Across * * |___/_/ |_/___/ /_/ Space and Time * * * * This file is part of VAST. It is subject to the license terms in the * * LICENSE file found in the top-level directory of this distribution and at * * http://vast.io/license. No part of VAST, including this file, may be * * copied, modified, propagated, or distributed except according to the terms * * contained in the LICENSE file. * ******************************************************************************/ #include "vast/system/table_index.hpp" #include "vast/detail/overload.hpp" #include "vast/expression_visitors.hpp" #include "vast/load.hpp" #include "vast/logger.hpp" #include "vast/save.hpp" namespace vast::system { caf::expected<table_index> make_table_index(path base_dir, type event_type) { caf::error err; table_index result{event_type, base_dir}; result.columns_.resize(table_index::meta_column_count + flat_size(event_type)); return result; } // -- constructors, destructors, and assignment operators ---------------------- table_index::~table_index() noexcept { // nop } // -- persistency -------------------------------------------------------------- caf::error table_index::flush_to_disk() { // Unless `add` was called at least once there's nothing to flush. if (!fully_initialized_) return caf::none; for (auto& col : columns_) { VAST_ASSERT(col != nullptr); auto err = col->flush_to_disk(); if (err) return err; } return caf::none; } /// -- properties -------------------------------------------------------------- column_index& table_index::at(size_t column_index) { return *columns_[column_index]; } column_index* table_index::by_name(std::string_view column_name) { // TODO: support string_view in path's operator / auto fname = base_dir_ / std::string{column_name}; auto pred = [&](const column_index_ptr& ptr) { return ptr->filename() == fname; }; auto i = std::find_if(columns_.begin(), columns_.end(), pred); return i != columns_.end() ? i->get() : nullptr; } caf::error table_index::add(const event& x) { if (fully_initialized_) { for (auto& col : columns_) { VAST_ASSERT(col != nullptr); col->add(x); } return caf::none; } auto fun = [&](column_index& col) -> caf::error { col.add(x); return caf::none; }; auto mk_time = [&] { return make_time_index(meta_dir()); }; auto mk_type = [&] { return make_type_index(meta_dir()); }; return caf::error::eval( [&] { // Column 0 is our meta index for the time. return with_meta_column(0, mk_time, fun); }, [&] { // Column 1 is our meta index for the event type. return with_meta_column(1, mk_type, fun); }, [&]() -> caf::error { // Coluns 2-N are our data fields. auto r = get_if<record_type>(event_type_); if (!r) { auto fac = [&] { return make_flat_data_index(data_dir(), event_type_); }; return with_data_column(0, fac, fun); } // Iterate all types of the record. size_t i = 0; for (auto&& f : record_type::each{*r}) { auto& value_type = f.trace.back()->type; if (!has_skip_attribute(event_type_)) { auto dir = data_dir(); for (auto& k : f.key()) dir /= k; auto fac = [&] { VAST_DEBUG("make field indexer at offset", f.offset, "with type", value_type); return make_field_data_index(dir, value_type, f.offset); }; auto err = with_data_column(i++, fac, fun); if (err) return err; } } return caf::none; }, [&]() -> caf::error { fully_initialized_ = true; return caf::none; }); } path table_index::meta_dir() const { return base_dir_ / "meta"; } path table_index::data_dir() const { return base_dir_ / "data"; } caf::expected<bitmap> table_index::lookup(const predicate& pred) { // For now, we require that the predicate is part of a normalized expression, // i.e., LHS an extractor type and RHS of type data. auto rhs = get_if<data>(pred.rhs); if (!rhs) return ec::invalid_query; // Specialize the predicate for the type. auto resolved = type_resolver{event_type_}(pred); if (!resolved) return std::move(resolved.error()); return lookup(*resolved); } caf::expected<bitmap> table_index::lookup(const expression& expr) { return visit( detail::overload( [&](const disjunction& dis) -> expected<bitmap> { bitmap result; for (auto& op : dis) { auto sub_result = lookup(op); if (!sub_result) return std::move(sub_result.error()); result |= *sub_result; } return result; }, [&](const predicate& p) { return visit( detail::overload( [&](const attribute_extractor& ex, const data& x) { return lookup(p, ex, x); }, [&](const data_extractor& dx, const data& x) { return lookup(p, dx, x); }, [&](const auto&, const auto&) -> expected<bitmap> { // Ignore unexpected lhs/rhs combinations. return bitmap{}; } ), p.lhs, p.rhs); }, [&](const auto&) -> expected<bitmap> { // Ignore unexpected expressions. return bitmap{}; } ), expr); } caf::expected<bitmap> table_index::lookup(const predicate& pred, const attribute_extractor& ex, const data& x) { VAST_IGNORE_UNUSED(x); // We know that the columns vector contains two meta fields: time at index // 0 and type at index 1. static_assert(table_index::meta_column_count == 2); VAST_ASSERT(columns_.size() >= table_index::meta_column_count); if (ex.attr == "time") { VAST_ASSERT(is<timestamp>(x)); auto fac = [&] { return make_time_index(meta_dir()); }; return with_meta_column(0, fac, [&](column_index& col) { return col.lookup(pred); }); } else if (ex.attr == "type") { VAST_ASSERT(is<std::string>(x)); auto fac = [&] { return make_type_index(meta_dir()); }; return with_meta_column(1, fac, [&](column_index& col) { return col.lookup(pred); }); } VAST_WARNING("unsupported attribute:", ex.attr); return ec::invalid_query; } caf::expected<bitmap> table_index::lookup(const predicate& pred, const data_extractor& dx, const data& x) { VAST_IGNORE_UNUSED(x); if (dx.offset.empty()) { VAST_ASSERT(num_data_columns() == 1); auto fac = [&] { return make_flat_data_index(data_dir(), event_type_); }; return with_data_column(0, fac, [&](column_index& col) { return col.lookup(pred); }); } else { auto r = get<record_type>(dx.type); auto k = r.resolve(dx.offset); VAST_ASSERT(k); auto t = r.at(dx.offset); VAST_ASSERT(t); auto fac = [&] { auto p = data_dir(); for (auto& x : *k) p /= x; return make_field_data_index(p, *t, dx.offset); }; auto index = r.flat_index_at(dx.offset); if (!index) { VAST_DEBUG("invalid offset for record type", dx.type); return bitmap{}; } return with_data_column(*index, fac, [&](column_index& col) { return col.lookup(pred); }); } return bitmap{}; } // -- constructors, destructors, and assignment operators ---------------------- table_index::table_index(type event_type, path base_dir) : event_type_(std::move(event_type)), base_dir_(std::move(base_dir)), fully_initialized_(false) { // nop } } // namespace vast::system <|endoftext|>
<commit_before>/* * Copyright (C) 2007-2011 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 CPACS fuselages handling routines. */ #include "CCPACSFuselages.h" #include "CCPACSFuselage.h" #include "CTiglError.h" #include <iostream> #include <sstream> namespace tigl { // Constructor CCPACSFuselages::CCPACSFuselages(CCPACSConfiguration* config) : configuration(config) { Cleanup(); } // Destructor CCPACSFuselages::~CCPACSFuselages(void) { Cleanup(); } // Invalidates internal state void CCPACSFuselages::Invalidate(void) { profiles.Invalidate(); for (int i = 1; i <= GetFuselageCount(); i++) { GetFuselage(i).Invalidate(); } } // Cleanup routine void CCPACSFuselages::Cleanup(void) { for (CCPACSFuselageContainer::size_type i = 0; i < fuselages.size(); i++) { delete fuselages[i]; } fuselages.clear(); } // Read CPACS fuselages element void CCPACSFuselages::ReadCPACS(TixiDocumentHandle tixiHandle, char* configurationUID) { Cleanup(); char *fuselagesXPathPrt = NULL; char *tmpString = NULL; if (tixiUIDGetXPath(tixiHandle, configurationUID, &tmpString) != SUCCESS) throw CTiglError("XML error: tixiUIDGetXPath failed in CCPACSFuselages::ReadCPACS", TIGL_XML_ERROR); fuselagesXPathPrt = (char *) malloc(sizeof(char) * (strlen(tmpString) + 50)); strcpy(fuselagesXPathPrt, tmpString); strcat(fuselagesXPathPrt, "[@uID=\""); strcat(fuselagesXPathPrt, configurationUID); strcat(fuselagesXPathPrt, "\"]/fuselages"); // Read fuselage profiles profiles.ReadCPACS(tixiHandle); if (tixiCheckElement(tixiHandle, fuselagesXPathPrt) != SUCCESS) return; /* Get fuselage element count */ int fuselageCount; if (tixiGetNamedChildrenCount(tixiHandle, fuselagesXPathPrt, "fuselage", &fuselageCount) != SUCCESS) throw CTiglError("XML error: tixiGetNamedChildrenCount failed in CCPACSFuselages::ReadCPACS", TIGL_XML_ERROR); // Loop over all fuselages for (int i = 1; i <= fuselageCount; i++) { CCPACSFuselage* fuselage = new CCPACSFuselage(configuration); fuselages.push_back(fuselage); std::ostringstream xpath; xpath << fuselagesXPathPrt << "/fuselage[" << i << "]"; fuselage->ReadCPACS(tixiHandle, xpath.str()); } free(fuselagesXPathPrt); } // Returns the total count of fuselage profiles in this configuration int CCPACSFuselages::GetProfileCount(void) const { return profiles.GetProfileCount(); } // Returns the fuselage profile for a given index. CCPACSFuselageProfile& CCPACSFuselages::GetProfile(int index) const { return profiles.GetProfile(index); } // Returns the fuselage profile for a given uid. CCPACSFuselageProfile& CCPACSFuselages::GetProfile(std::string uid) const { return profiles.GetProfile(uid); } // Returns the total count of fuselages in a configuration int CCPACSFuselages::GetFuselageCount(void) const { return (static_cast<int>(fuselages.size())); } // Returns the fuselage for a given index. CCPACSFuselage& CCPACSFuselages::GetFuselage(int index) const { index--; if (index < 0 || index >= GetFuselageCount()) throw CTiglError("Error: Invalid index in CCPACSFuselages::GetFuselage", TIGL_INDEX_ERROR); return (*fuselages[index]); } // Returns the fuselage for a given index. CCPACSFuselage& CCPACSFuselages::GetFuselage(std::string UID) const { for(int i=0; i < GetFuselageCount(); i++) { const std::string tmpUID((*fuselages[i]).GetUIDPtr()); if(tmpUID == UID) { return (*fuselages[i]); } } // UID not there throw CTiglError("Error: Invalid index in CCPACSFuselages::GetFuselage", TIGL_INDEX_ERROR); } } // end namespace tigl <commit_msg>Fixed memory leak in CCPACSFuselages<commit_after>/* * Copyright (C) 2007-2011 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 CPACS fuselages handling routines. */ #include "CCPACSFuselages.h" #include "CCPACSFuselage.h" #include "CTiglError.h" #include <iostream> #include <sstream> namespace tigl { // Constructor CCPACSFuselages::CCPACSFuselages(CCPACSConfiguration* config) : configuration(config) { Cleanup(); } // Destructor CCPACSFuselages::~CCPACSFuselages(void) { Cleanup(); } // Invalidates internal state void CCPACSFuselages::Invalidate(void) { profiles.Invalidate(); for (int i = 1; i <= GetFuselageCount(); i++) { GetFuselage(i).Invalidate(); } } // Cleanup routine void CCPACSFuselages::Cleanup(void) { for (CCPACSFuselageContainer::size_type i = 0; i < fuselages.size(); i++) { delete fuselages[i]; } fuselages.clear(); } // Read CPACS fuselages element void CCPACSFuselages::ReadCPACS(TixiDocumentHandle tixiHandle, char* configurationUID) { Cleanup(); char *fuselagesXPathPrt = NULL; char *tmpString = NULL; if (tixiUIDGetXPath(tixiHandle, configurationUID, &tmpString) != SUCCESS) throw CTiglError("XML error: tixiUIDGetXPath failed in CCPACSFuselages::ReadCPACS", TIGL_XML_ERROR); fuselagesXPathPrt = (char *) malloc(sizeof(char) * (strlen(tmpString) + 50)); strcpy(fuselagesXPathPrt, tmpString); strcat(fuselagesXPathPrt, "[@uID=\""); strcat(fuselagesXPathPrt, configurationUID); strcat(fuselagesXPathPrt, "\"]/fuselages"); // Read fuselage profiles profiles.ReadCPACS(tixiHandle); if (tixiCheckElement(tixiHandle, fuselagesXPathPrt) != SUCCESS){ free(fuselagesXPathPrt); return; } /* Get fuselage element count */ int fuselageCount; if (tixiGetNamedChildrenCount(tixiHandle, fuselagesXPathPrt, "fuselage", &fuselageCount) != SUCCESS) throw CTiglError("XML error: tixiGetNamedChildrenCount failed in CCPACSFuselages::ReadCPACS", TIGL_XML_ERROR); // Loop over all fuselages for (int i = 1; i <= fuselageCount; i++) { CCPACSFuselage* fuselage = new CCPACSFuselage(configuration); fuselages.push_back(fuselage); std::ostringstream xpath; xpath << fuselagesXPathPrt << "/fuselage[" << i << "]"; fuselage->ReadCPACS(tixiHandle, xpath.str()); } free(fuselagesXPathPrt); } // Returns the total count of fuselage profiles in this configuration int CCPACSFuselages::GetProfileCount(void) const { return profiles.GetProfileCount(); } // Returns the fuselage profile for a given index. CCPACSFuselageProfile& CCPACSFuselages::GetProfile(int index) const { return profiles.GetProfile(index); } // Returns the fuselage profile for a given uid. CCPACSFuselageProfile& CCPACSFuselages::GetProfile(std::string uid) const { return profiles.GetProfile(uid); } // Returns the total count of fuselages in a configuration int CCPACSFuselages::GetFuselageCount(void) const { return (static_cast<int>(fuselages.size())); } // Returns the fuselage for a given index. CCPACSFuselage& CCPACSFuselages::GetFuselage(int index) const { index--; if (index < 0 || index >= GetFuselageCount()) throw CTiglError("Error: Invalid index in CCPACSFuselages::GetFuselage", TIGL_INDEX_ERROR); return (*fuselages[index]); } // Returns the fuselage for a given index. CCPACSFuselage& CCPACSFuselages::GetFuselage(std::string UID) const { for(int i=0; i < GetFuselageCount(); i++) { const std::string tmpUID((*fuselages[i]).GetUIDPtr()); if(tmpUID == UID) { return (*fuselages[i]); } } // UID not there throw CTiglError("Error: Invalid index in CCPACSFuselages::GetFuselage", TIGL_INDEX_ERROR); } } // end namespace tigl <|endoftext|>
<commit_before>#include <AlpinoCorpus/DbCorpusWriter.hh> #include <AlpinoCorpus/Error.hh> #include <QtGlobal> namespace db = DbXml; namespace alpinocorpus { DbCorpusWriter::DbCorpusWriter(QString const &qpath, bool overwrite) : mgr(), container() { try { db::XmlContainerConfig config; config.setReadOnly(false); std::string path(qpath.toLocal8Bit().data()); if (overwrite) container = mgr.createContainer(path, config); else container = mgr.openContainer(path, config); } catch (XmlException const &e) { throw OpenError(e.what()); } } db::XmlUpdateContext &DbCorpusWriter::mkUpdateContext( db::XmlUpdateContext &ctx) { // Note: this function may be unnecessary; no exceptions are listed // for XmlManager::createUpdateContext() or the copy constructor, // but the don't have no-throw guarantee either. try { return ctx = mgr.createUpdateContext(); } catch (db::XmlException const &e) { std::ostringstream msg; msg << "cannot create XML database update context \"" << name << "\": " << e.what(); throw Error(msg.str()); } } void DbCorpusWriter::write(QString const &name, QString const &content) { write(name, content, mkUpdateContext()); } void DbCorpusWriter::write(CorpusReader const &corpus) { QVector<QString> entry(corpus.entries); db::XmlUpdateContext ctx(mkUpdateContext()); for (size_t i=0; i<entry.size(); i++) write(entry[i], corpus.read(entry[i]), ctx); } void DbCorpusWriter::write(QString const &name, QString const &content, XmlUpdateContext &ctx) { try { std::string canonical(name.fromNativeSeparators().toUtf8().data()); container.putDocument(name, content, ctx, db::WELL_FORMED_ONLY); } catch (XmlException const &e) { std::ostringstream msg; msg << "cannot write document \"" << name << "\": " << e.what(); throw Error(msg.str()); } } } <commit_msg>Use QDir properly<commit_after>#include <AlpinoCorpus/DbCorpusWriter.hh> #include <AlpinoCorpus/Error.hh> #include <QDir> namespace db = DbXml; namespace alpinocorpus { DbCorpusWriter::DbCorpusWriter(QString const &qpath, bool overwrite) : mgr(), container() { try { db::XmlContainerConfig config; config.setReadOnly(false); std::string path(qpath.toLocal8Bit().data()); if (overwrite) container = mgr.createContainer(path, config); else container = mgr.openContainer(path, config); } catch (XmlException const &e) { throw OpenError(e.what()); } } db::XmlUpdateContext &DbCorpusWriter::mkUpdateContext( db::XmlUpdateContext &ctx) { // Note: this function may be unnecessary; no exceptions are listed // for XmlManager::createUpdateContext() or the copy constructor, // but they don't have a no-throw guarantee either. try { return ctx = mgr.createUpdateContext(); } catch (db::XmlException const &e) { std::ostringstream msg; msg << "cannot create XML database update context \"" << name << "\": " << e.what(); throw Error(msg.str()); } } void DbCorpusWriter::write(QString const &name, QString const &content) { write(name, content, mkUpdateContext()); } void DbCorpusWriter::write(CorpusReader const &corpus) { QVector<QString> entry(corpus.entries); db::XmlUpdateContext ctx(mkUpdateContext()); for (size_t i=0; i<entry.size(); i++) write(entry[i], corpus.read(entry[i]), ctx); } void DbCorpusWriter::write(QString const &name, QString const &content, XmlUpdateContext &ctx) { try { std::string canonical(QDir::fromNativeSeparators(name) .toUtf8() .data()); container.putDocument(name, content, ctx, db::WELL_FORMED_ONLY); } catch (XmlException const &e) { std::ostringstream msg; msg << "cannot write document \"" << name << "\": " << e.what(); throw Error(msg.str()); } } } <|endoftext|>
<commit_before>/* DepotsSettings.cpp * Copyright 2016 Brian Hill * All rights reserved. Distributed under the terms of the BSD License. */ #include "constants.h" #include "DepotsSettings.h" #include <FindDirectory.h> #include <StringList.h> #undef B_TRANSLATION_CONTEXT #define B_TRANSLATION_CONTEXT "DepotsSettings" const char* settingsFilename = "Depots_settings"; DepotsSettings::DepotsSettings() { status_t status = find_directory(B_USER_SETTINGS_DIRECTORY, &fFilePath); if (status == B_OK) { status = fFilePath.Append(settingsFilename); } fInitStatus = status; } BRect DepotsSettings::GetFrame() { BMessage settings(_ReadFromFile()); BRect frame; settings.FindRect(key_frame, &frame); return frame; } void DepotsSettings::SetFrame(BRect frame) { BMessage settings(_ReadFromFile()); settings.RemoveData(key_frame); settings.AddRect(key_frame, frame); _SaveToFile(settings); } status_t DepotsSettings::GetRepositories(int32 &repoCount, BStringList &nameList, BStringList &urlList) { BMessage settings(_ReadFromFile()); type_code type; int32 count; settings.GetInfo(key_name, &type, &count); status_t result = B_OK; int32 index, total=0; BString foundName, foundUrl; // get each repository and add to lists for(index = 0; index < count; index++) { status_t result1 = settings.FindString(key_name, index, &foundName); status_t result2 = settings.FindString(key_url, index, &foundUrl); if(result1 == B_OK && result2 == B_OK) { nameList.Add(foundName); urlList.Add(foundUrl); total++; } else result = B_ERROR; } repoCount = total; return result; } void DepotsSettings::SetRepositories(BStringList &nameList, BStringList &urlList) { BMessage settings(_ReadFromFile()); settings.RemoveName(key_name); settings.RemoveName(key_url); int32 index, count = nameList.CountStrings(); for(index=0; index < count; index++) { settings.AddString(key_name, nameList.StringAt(index)); settings.AddString(key_url, urlList.StringAt(index)); } _SaveToFile(settings); } BMessage DepotsSettings::_ReadFromFile() { BMessage settings; status_t status = fFile.SetTo(fFilePath.Path(), B_READ_ONLY); if (status == B_OK) status = settings.Unflatten(&fFile); fFile.Unset(); return settings; } status_t DepotsSettings::_SaveToFile(BMessage settings) { status_t status = fFile.SetTo(fFilePath.Path(), B_WRITE_ONLY | B_CREATE_FILE | B_ERASE_FILE); if (status == B_OK) status = settings.Flatten(&fFile); fFile.Unset(); return status; } <commit_msg>Set default window frame when no settings found<commit_after>/* DepotsSettings.cpp * Copyright 2016 Brian Hill * All rights reserved. Distributed under the terms of the BSD License. */ #include "constants.h" #include "DepotsSettings.h" #include <FindDirectory.h> #include <StringList.h> #undef B_TRANSLATION_CONTEXT #define B_TRANSLATION_CONTEXT "DepotsSettings" const char* settingsFilename = "Depots_settings"; DepotsSettings::DepotsSettings() { status_t status = find_directory(B_USER_SETTINGS_DIRECTORY, &fFilePath); if (status == B_OK) { status = fFilePath.Append(settingsFilename); } fInitStatus = status; } BRect DepotsSettings::GetFrame() { BMessage settings(_ReadFromFile()); BRect frame; status_t status = settings.FindRect(key_frame, &frame); // Set deafault off screen so it will center itself if(status != B_OK) frame.Set(-10, -10, 750, 300); return frame; } void DepotsSettings::SetFrame(BRect frame) { BMessage settings(_ReadFromFile()); settings.RemoveData(key_frame); settings.AddRect(key_frame, frame); _SaveToFile(settings); } status_t DepotsSettings::GetRepositories(int32 &repoCount, BStringList &nameList, BStringList &urlList) { BMessage settings(_ReadFromFile()); type_code type; int32 count; settings.GetInfo(key_name, &type, &count); status_t result = B_OK; int32 index, total=0; BString foundName, foundUrl; // get each repository and add to lists for(index = 0; index < count; index++) { status_t result1 = settings.FindString(key_name, index, &foundName); status_t result2 = settings.FindString(key_url, index, &foundUrl); if(result1 == B_OK && result2 == B_OK) { nameList.Add(foundName); urlList.Add(foundUrl); total++; } else result = B_ERROR; } repoCount = total; return result; } void DepotsSettings::SetRepositories(BStringList &nameList, BStringList &urlList) { BMessage settings(_ReadFromFile()); settings.RemoveName(key_name); settings.RemoveName(key_url); int32 index, count = nameList.CountStrings(); for(index=0; index < count; index++) { settings.AddString(key_name, nameList.StringAt(index)); settings.AddString(key_url, urlList.StringAt(index)); } _SaveToFile(settings); } BMessage DepotsSettings::_ReadFromFile() { BMessage settings; status_t status = fFile.SetTo(fFilePath.Path(), B_READ_ONLY); if (status == B_OK) status = settings.Unflatten(&fFile); fFile.Unset(); return settings; } status_t DepotsSettings::_SaveToFile(BMessage settings) { status_t status = fFile.SetTo(fFilePath.Path(), B_WRITE_ONLY | B_CREATE_FILE | B_ERASE_FILE); if (status == B_OK) status = settings.Flatten(&fFile); fFile.Unset(); return status; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: flags.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: jb $ $Date: 2002-02-15 14:34:33 $ * * 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: 2002 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef INCLUDED_DATA_FLAGS_HXX #define INCLUDED_DATA_FLAGS_HXX #ifndef _SAL_TYPES_H_ #include <sal/types.h> #endif namespace configmgr { //----------------------------------------------------------------------------- namespace data { //----------------------------------------------------------------------------- // node type + value type selector - fits into a byte (bit 5 currently unassigned) namespace Type { enum Type { // Primitive Data Type is stored in bits 0-4 (bit 3 currently unused) // base data types value_any, // = 0 value_string, // = 1 value_boolean, // = 2 value_short, // = 3 value_int, // = 4 value_long, // = 5 value_double, // = 6 value_binary, // = 7 mask_basetype = 0x0F, // sequence data types flag_sequence = 0x10, value_invalid = value_any | flag_sequence, value_string_list = value_string | flag_sequence, value_boolean_list = value_boolean | flag_sequence, value_short_list = value_short | flag_sequence, value_int_list = value_int | flag_sequence, value_long_list = value_long | flag_sequence, value_double_list = value_double | flag_sequence, value_binary_list = value_binary | flag_sequence, mask_valuetype = mask_basetype | flag_sequence, // 0x1F // Node Type is stored in bits 6+7 nodetype_shift_ = 6, mask_nodetype = 0x03 << nodetype_shift_, // 0xC0 // maybe we should use 0 for node type 'value' // to make the complete type be the valuetype ? nodetype_invalid= 0x00, nodetype_value = 0x01 << nodetype_shift_, // 0x40 nodetype_group = 0x02 << nodetype_shift_, // 0x80 nodetype_set = 0x03 << nodetype_shift_, // 0xC0 flag_innernode = 0x02 << nodetype_shift_, // 0x80 flag_setnode = 0x01 << nodetype_shift_ // 0x40 }; typedef sal_uInt8 Field; } //----------------------------------------------------------------------------- // node attributes namespace Flags { enum Type { readonly = 0x01, finalized = 0x02, nullable = 0x04, localized = 0x08, valueAvailable = 0x10, // only used for value nodes defaultAvailable = 0x20, // only used for value nodes defaulted = 0x40, // somewhat redundant with State defaultable = 0x80 // redundant with State (merged || defaulted) }; typedef sal_uInt8 Field; } //----------------------------------------------------------------------------- // set element or tree state namespace State { enum Type { merged, // = 0, - result of merging defaults + changes defaulted, // = 1, - result of copying defaults unchanged replaced, // = 2, - result of copying new layer unchanged added, // = 3, - same as 'replaced', but it is known, // that there is no corresponding default mask_state = 0x0F, // leaves bits 3+4 reserved for states flag_mandatory = 0x10, // marks this element as non-removable/replacable flag_readonly = 0x20, // marks this element as read-only flag_default_avail = 0x40 // marks this element as containing default values }; typedef sal_uInt8 Field; } //----------------------------------------------------------------------------- } //----------------------------------------------------------------------------- } #endif // INCLUDED_DATA_FLAGS_HXX <commit_msg>INTEGRATION: CWS cfg01 (1.2.24); FILE MERGED 2003/02/28 16:33:15 ssmith 1.2.24.1: #107403# #107403# adding support for mandatory flag and changing dynamic properties semantics<commit_after>/************************************************************************* * * $RCSfile: flags.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: vg $ $Date: 2003-04-01 13:32:49 $ * * 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: 2002 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef INCLUDED_DATA_FLAGS_HXX #define INCLUDED_DATA_FLAGS_HXX #ifndef _SAL_TYPES_H_ #include <sal/types.h> #endif namespace configmgr { //----------------------------------------------------------------------------- namespace data { //----------------------------------------------------------------------------- // node type + value type selector - fits into a byte (bit 5 currently unassigned) namespace Type { enum Type { // Primitive Data Type is stored in bits 0-4 (bit 3 currently unused) // base data types value_any, // = 0 value_string, // = 1 value_boolean, // = 2 value_short, // = 3 value_int, // = 4 value_long, // = 5 value_double, // = 6 value_binary, // = 7 mask_basetype = 0x0F, // sequence data types flag_sequence = 0x10, value_invalid = value_any | flag_sequence, value_string_list = value_string | flag_sequence, value_boolean_list = value_boolean | flag_sequence, value_short_list = value_short | flag_sequence, value_int_list = value_int | flag_sequence, value_long_list = value_long | flag_sequence, value_double_list = value_double | flag_sequence, value_binary_list = value_binary | flag_sequence, mask_valuetype = mask_basetype | flag_sequence, // 0x1F // Node Type is stored in bits 6+7 nodetype_shift_ = 6, mask_nodetype = 0x03 << nodetype_shift_, // 0xC0 // maybe we should use 0 for node type 'value' // to make the complete type be the valuetype ? nodetype_invalid= 0x00, nodetype_value = 0x01 << nodetype_shift_, // 0x40 nodetype_group = 0x02 << nodetype_shift_, // 0x80 nodetype_set = 0x03 << nodetype_shift_, // 0xC0 flag_innernode = 0x02 << nodetype_shift_, // 0x80 flag_setnode = 0x01 << nodetype_shift_ // 0x40 }; typedef sal_uInt8 Field; } //----------------------------------------------------------------------------- // node attributes namespace Flags { enum Type { readonly = 0x01, finalized = 0x02, nullable = 0x04, localized = 0x08, valueAvailable = 0x10, // only used for value nodes defaultAvailable = 0x20, // only used for value nodes defaulted = 0x40, // somewhat redundant with State defaultable = 0x80 // redundant with State (merged || defaulted) }; typedef sal_uInt8 Field; } //----------------------------------------------------------------------------- // set element or tree state namespace State { enum Type { merged, // = 0, - result of merging defaults + changes defaulted, // = 1, - result of copying defaults unchanged replaced, // = 2, - result of copying new layer unchanged added, // = 3, - same as 'replaced', but it is known, // that there is no corresponding default mask_state = 0x0F, // leaves bits 3+4 reserved for states flag_mandatory = 0x10, // marks this element as non-removable/replacable flag_readonly = 0x20, // marks this element as read-only flag_default_avail = 0x40, // marks this element as containing default values flag_removable = 0x80 // marks this element as removable }; typedef sal_uInt8 Field; } //----------------------------------------------------------------------------- } //----------------------------------------------------------------------------- } #endif // INCLUDED_DATA_FLAGS_HXX <|endoftext|>
<commit_before>#include "InterpolatedScorer.h" #include "ScorerFactory.h" #include "Util.h" using namespace std; // TODO: This is too long. Consider creating a function for // initialization such as Init(). InterpolatedScorer::InterpolatedScorer(const string& name, const string& config) : Scorer(name,config) { // name would be: HAMMING,BLEU or similar string scorers = name; while (scorers.length() > 0) { string scorertype = ""; getNextPound(scorers, scorertype,","); Scorer *scorer = ScorerFactory::getScorer(scorertype,config); m_scorers.push_back(scorer); } if (m_scorers.size() == 0) { throw runtime_error("There are no scorers"); } cerr << "Number of scorers: " << m_scorers.size() << endl; //TODO debug this string wtype = getConfig("weights",""); //Default weights set to uniform ie. if two weights 0.5 each //weights should add to 1 if (wtype.length() == 0) { float weight = 1.0 / m_scorers.size() ; //cout << " Default weights:" << weight << endl; for (size_t i = 0; i < m_scorers.size(); i ++) { m_scorer_weights.push_back(weight); } } else { float tot=0; //cout << "Defined weights:" << endl; while (wtype.length() > 0) { string scoreweight = ""; getNextPound(wtype,scoreweight,"+"); float weight = atof(scoreweight.c_str()); m_scorer_weights.push_back(weight); tot += weight; //cout << " :" << weight ; } //cout << endl; if (tot != float(1)) { // TODO: fix this checking in terms of readability. for (vector<float>::iterator it = m_scorer_weights.begin(); it != m_scorer_weights.end(); ++it) { *it /= tot; } } if (m_scorers.size() != m_scorer_weights.size()) { throw runtime_error("The number of weights does not equal the number of scorers!"); } } cerr << "The weights for the interpolated scorers are: " << endl; for (vector<float>::iterator it = m_scorer_weights.begin(); it < m_scorer_weights.end(); it++) { cerr << *it << " " ; } cerr <<endl; } void InterpolatedScorer::setScoreData(ScoreData* data) { size_t last = 0; m_score_data = data; for (ScopedVector<Scorer>::iterator itsc = m_scorers.begin(); itsc != m_scorers.end(); ++itsc) { int numScoresScorer = (*itsc)->NumberOfScores(); ScoreData* newData =new ScoreData(*itsc); for (size_t i = 0; i < data->size(); i++) { ScoreArray scoreArray = data->get(i); ScoreArray newScoreArray; std::string istr; std::stringstream out; out << i; istr = out.str(); size_t numNBest = scoreArray.size(); //cout << " Datasize " << data->size() << " NumNBest " << numNBest << endl ; for (size_t j = 0; j < numNBest ; j++) { ScoreStats scoreStats = data->get(i, j); //cout << "Scorestats " << scoreStats << " i " << i << " j " << j << endl; ScoreStats newScoreStats; for (size_t k = last; k < size_t(numScoresScorer + last); k++) { ScoreStatsType score = scoreStats.get(k); newScoreStats.add(score); } //cout << " last " << last << " NumScores " << numScoresScorer << "newScorestats " << newScoreStats << endl; newScoreArray.add(newScoreStats); } newScoreArray.setIndex(istr); newData->add(newScoreArray); } //newData->dump(); // NOTE: This class takes the ownership of the heap allocated // ScoreData objects to avoid the memory leak issues. m_scorers_score_data.push_back(newData); (*itsc)->setScoreData(newData); last += numScoresScorer; } } /** The interpolated scorer calls a vector of scorers and combines them with weights **/ void InterpolatedScorer::score(const candidates_t& candidates, const diffs_t& diffs, statscores_t& scores) const { //cout << "*******InterpolatedScorer::score" << endl; size_t scorerNum = 0; for (ScopedVector<Scorer>::const_iterator itsc = m_scorers.begin(); itsc != m_scorers.end(); ++itsc) { //int numScores = (*itsc)->NumberOfScores(); statscores_t tscores; (*itsc)->score(candidates,diffs,tscores); size_t inc = 0; for (statscores_t::iterator itstatsc = tscores.begin(); itstatsc != tscores.end(); ++itstatsc) { //cout << "Scores " << (*itstatsc) << endl; float weight = m_scorer_weights[scorerNum]; if (weight == 0) { stringstream msg; msg << "No weights for scorer" << scorerNum ; throw runtime_error(msg.str()); } if (scorerNum == 0) { scores.push_back(weight * (*itstatsc)); } else { scores[inc] += weight * (*itstatsc); } //cout << "Scorer:" << scorerNum << " scoreNum:" << inc << " score: " << (*itstatsc) << " weight:" << weight << endl; inc++; } scorerNum++; } } void InterpolatedScorer::setReferenceFiles(const vector<string>& referenceFiles) { for (ScopedVector<Scorer>::iterator itsc = m_scorers.begin(); itsc != m_scorers.end(); ++itsc) { (*itsc)->setReferenceFiles(referenceFiles); } } void InterpolatedScorer::prepareStats(size_t sid, const string& text, ScoreStats& entry) { stringstream buff; int i = 0; for (ScopedVector<Scorer>::iterator itsc = m_scorers.begin(); itsc != m_scorers.end(); ++itsc) { ScoreStats tempEntry; (*itsc)->prepareStats(sid, text, tempEntry); if (i > 0) buff << " "; buff << tempEntry; i++; } //cout << " Scores for interpolated: " << buff << endl; string str = buff.str(); entry.set(str); } void InterpolatedScorer::setFactors(const string& factors) { if (factors.empty()) return; vector<string> fsplit; split(factors, ',', fsplit); if (fsplit.size() != m_scorers.size()) throw runtime_error("Number of factor specifications does not equal number of interpolated scorers."); for (size_t i = 0; i < m_scorers.size(); ++i) { m_scorers[i]->setFactors(fsplit[i]); } } void InterpolatedScorer::setFilter(const string& filterCommand) { for (size_t i = 0; i < m_scorers.size(); ++i) { m_scorers[i]->setFilter(filterCommand); } } <commit_msg>Fixed interpolated scorer<commit_after>#include "InterpolatedScorer.h" #include "ScorerFactory.h" #include "Util.h" using namespace std; // TODO: This is too long. Consider creating a function for // initialization such as Init(). InterpolatedScorer::InterpolatedScorer(const string& name, const string& config) : Scorer(name,config) { // name would be: HAMMING,BLEU or similar string scorers = name; while (scorers.length() > 0) { string scorertype = ""; getNextPound(scorers, scorertype,","); Scorer *scorer = ScorerFactory::getScorer(scorertype,config); m_scorers.push_back(scorer); } if (m_scorers.size() == 0) { throw runtime_error("There are no scorers"); } cerr << "Number of scorers: " << m_scorers.size() << endl; //TODO debug this string wtype = getConfig("weights",""); //Default weights set to uniform ie. if two weights 0.5 each //weights should add to 1 if (wtype.length() == 0) { float weight = 1.0 / m_scorers.size() ; //cout << " Default weights:" << weight << endl; for (size_t i = 0; i < m_scorers.size(); i ++) { m_scorer_weights.push_back(weight); } } else { float tot=0; //cout << "Defined weights:" << endl; while (wtype.length() > 0) { string scoreweight = ""; getNextPound(wtype,scoreweight,"+"); float weight = atof(scoreweight.c_str()); m_scorer_weights.push_back(weight); tot += weight; //cout << " :" << weight ; } //cout << endl; if (tot != float(1)) { // TODO: fix this checking in terms of readability. for (vector<float>::iterator it = m_scorer_weights.begin(); it != m_scorer_weights.end(); ++it) { *it /= tot; } } if (m_scorers.size() != m_scorer_weights.size()) { throw runtime_error("The number of weights does not equal the number of scorers!"); } } cerr << "The weights for the interpolated scorers are: " << endl; for (vector<float>::iterator it = m_scorer_weights.begin(); it < m_scorer_weights.end(); it++) { cerr << *it << " " ; } cerr <<endl; } void InterpolatedScorer::setScoreData(ScoreData* data) { size_t last = 0; m_score_data = data; for (ScopedVector<Scorer>::iterator itsc = m_scorers.begin(); itsc != m_scorers.end(); ++itsc) { int numScoresScorer = (*itsc)->NumberOfScores(); ScoreData* newData =new ScoreData(*itsc); for (size_t i = 0; i < data->size(); i++) { ScoreArray scoreArray = data->get(i); ScoreArray newScoreArray; std::string istr; std::stringstream out; out << i; istr = out.str(); size_t numNBest = scoreArray.size(); //cout << " Datasize " << data->size() << " NumNBest " << numNBest << endl ; for (size_t j = 0; j < numNBest ; j++) { ScoreStats scoreStats = data->get(i, j); //cout << "Scorestats " << scoreStats << " i " << i << " j " << j << endl; ScoreStats newScoreStats; for (size_t k = last; k < size_t(numScoresScorer + last); k++) { ScoreStatsType score = scoreStats.get(k); newScoreStats.add(score); } //cout << " last " << last << " NumScores " << numScoresScorer << "newScorestats " << newScoreStats << endl; newScoreArray.add(newScoreStats); } newScoreArray.setIndex(istr); newData->add(newScoreArray); } //newData->dump(); // NOTE: This class takes the ownership of the heap allocated // ScoreData objects to avoid the memory leak issues. m_scorers_score_data.push_back(newData); (*itsc)->setScoreData(newData); last += numScoresScorer; } } /** The interpolated scorer calls a vector of scorers and combines them with weights **/ void InterpolatedScorer::score(const candidates_t& candidates, const diffs_t& diffs, statscores_t& scores) const { //cout << "*******InterpolatedScorer::score" << endl; size_t scorerNum = 0; for (ScopedVector<Scorer>::const_iterator itsc = m_scorers.begin(); itsc != m_scorers.end(); ++itsc) { //int numScores = (*itsc)->NumberOfScores(); statscores_t tscores; (*itsc)->score(candidates,diffs,tscores); size_t inc = 0; for (statscores_t::iterator itstatsc = tscores.begin(); itstatsc != tscores.end(); ++itstatsc) { //cout << "Scores " << (*itstatsc) << endl; float weight = m_scorer_weights[scorerNum]; if (weight == 0) { stringstream msg; msg << "No weights for scorer" << scorerNum ; throw runtime_error(msg.str()); } if (scorerNum == 0) { scores.push_back(weight * (*itstatsc)); } else { scores[inc] += weight * (*itstatsc); } //cout << "Scorer:" << scorerNum << " scoreNum:" << inc << " score: " << (*itstatsc) << " weight:" << weight << endl; inc++; } scorerNum++; } } void InterpolatedScorer::setReferenceFiles(const vector<string>& referenceFiles) { for (ScopedVector<Scorer>::iterator itsc = m_scorers.begin(); itsc != m_scorers.end(); ++itsc) { (*itsc)->setReferenceFiles(referenceFiles); } } void InterpolatedScorer::prepareStats(size_t sid, const string& text, ScoreStats& entry) { stringstream buff; int i = 0; for (ScopedVector<Scorer>::iterator itsc = m_scorers.begin(); itsc != m_scorers.end(); ++itsc) { ScoreStats tempEntry; (*itsc)->prepareStats(sid, text, tempEntry); if (i > 0) buff << " "; buff << tempEntry; i++; } //cout << " Scores for interpolated: " << buff << endl; string str = buff.str(); entry.set(str); } void InterpolatedScorer::setFactors(const string& factors) { if (factors.empty()) return; vector<string> fsplit; split(factors, ',', fsplit); if (fsplit.size() != m_scorers.size()) throw runtime_error("Number of factor specifications does not equal number of interpolated scorers."); for (size_t i = 0; i < m_scorers.size(); ++i) { m_scorers[i]->setFactors(fsplit[i]); } } void InterpolatedScorer::setFilter(const string& filterCommand) { if (filterCommand.empty()) return; vector<string> csplit; split(filterCommand, ',', csplit); if (csplit.size() != m_scorers.size()) throw runtime_error("Number of command specifications does not equal number of interpolated scorers."); for (size_t i = 0; i < m_scorers.size(); ++i) { m_scorers[i]->setFilter(csplit[i]); } } <|endoftext|>
<commit_before>#include "../LessParser.h" #include "gtest/gtest.h" // At rules TEST(LessParserTest, AtRule) { istringstream in("@x: 10; selector {key: @x}"); LessTokenizer t(&in); LessParser p(&t); Stylesheet s; p.parseStylesheet(&s); Ruleset* set; Declaration* d; p.parseStylesheet(&s); ASSERT_EQ(1, s.getRulesets()->size()); ASSERT_EQ(1, s.getRulesets()->at(0)->getDeclarations()->size()); d = s.getRulesets()->at(0)->getDeclarations()->at(0); ASSERT_STREQ("key", d->getProperty()->c_str()); ASSERT_STREQ("10", d->getValue()->toString()->c_str()); } <commit_msg>Added tests for variables, mixins, nested rules and mixins with parameters.<commit_after>#include "../LessParser.h" #include "gtest/gtest.h" TEST(LessParserTest, Variable) { istringstream in("@x: 10; selector {key: @x}"); LessTokenizer t(&in); LessParser p(&t); Stylesheet s; Declaration* d; p.parseStylesheet(&s); ASSERT_EQ((uint)1, s.getRulesets()->size()); ASSERT_EQ((uint)1, s.getRulesets()->at(0)->getDeclarations()->size()); d = s.getRulesets()->at(0)->getDeclarations()->at(0); EXPECT_STREQ("key", d->getProperty()->c_str()); EXPECT_STREQ("10", d->getValue()->toString()->c_str()); } // mixin TEST(LessParserTest, Mixin) { istringstream in("mixin {key: 10} selector {mixin}"); LessTokenizer t(&in); LessParser p(&t); Stylesheet s; Ruleset* set; Declaration* d; p.parseStylesheet(&s); ASSERT_EQ((uint)2, s.getRulesets()->size()); set = s.getRulesets()->at(1); ASSERT_STREQ("selector", set->getSelector()->toString()->c_str()); ASSERT_EQ((uint)1, set->getDeclarations()->size()); d = set->getDeclarations()->at(0); EXPECT_STREQ("key", d->getProperty()->c_str()); EXPECT_STREQ("10", d->getValue()->toString()->c_str()); } // nested rule TEST(LessParserTest, NestedRule) { istringstream in("selector { nested {key: value} }"); LessTokenizer t(&in); LessParser p(&t); Stylesheet s; Ruleset* set; Declaration* d; p.parseStylesheet(&s); ASSERT_EQ((uint)2, s.getRulesets()->size()); // Check for 'selector {}' set = s.getRulesets()->at(0); ASSERT_STREQ("selector", set->getSelector()->toString()->c_str()); ASSERT_EQ((uint)0, set->getDeclarations()->size()); // Check for 'selector nested {key: value}' set = s.getRulesets()->at(1); ASSERT_STREQ("selector nested", set->getSelector()->toString()->c_str()); ASSERT_EQ((uint)1, set->getDeclarations()->size()); d = set->getDeclarations()->at(0); EXPECT_STREQ("key", d->getProperty()->c_str()); EXPECT_STREQ("value", d->getValue()->toString()->c_str()); } // parameter mixin TEST(LessParserTest, ParameterMixin) { istringstream in(".mixin(@x) {key: @x} selector {.mixin(10);}"); LessTokenizer t(&in); LessParser p(&t); Stylesheet s; Ruleset* set; Declaration* d; p.parseStylesheet(&s); ASSERT_EQ((uint)1, s.getRulesets()->size()); set = s.getRulesets()->at(0); ASSERT_STREQ("selector", set->getSelector()->toString()->c_str()); ASSERT_EQ((uint)1, set->getDeclarations()->size()); d = set->getDeclarations()->at(0); EXPECT_STREQ("key", d->getProperty()->c_str()); EXPECT_STREQ("10", d->getValue()->toString()->c_str()); } <|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. ==============================================================================*/ // This pass forms `tf_executor.island` per replica from a single // `tf_device.replicate` island. #include <memory> #include <utility> #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/None.h" #include "llvm/ADT/Optional.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/Sequence.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/Casting.h" #include "mlir/IR/Attributes.h" // from @llvm-project #include "mlir/IR/Block.h" // from @llvm-project #include "mlir/IR/BlockAndValueMapping.h" // from @llvm-project #include "mlir/IR/Builders.h" // from @llvm-project #include "mlir/IR/Diagnostics.h" // from @llvm-project #include "mlir/IR/Dialect.h" // from @llvm-project #include "mlir/IR/Visitors.h" // from @llvm-project #include "mlir/Pass/Pass.h" // from @llvm-project #include "mlir/Support/LogicalResult.h" // from @llvm-project #include "tensorflow/compiler/mlir/tensorflow/ir/tf_device.h" #include "tensorflow/compiler/mlir/tensorflow/ir/tf_executor.h" #include "tensorflow/compiler/mlir/tensorflow/ir/tf_ops.h" #include "tensorflow/compiler/mlir/tensorflow/utils/device_util.h" #include "tensorflow/compiler/mlir/tensorflow/utils/tpu_rewrite_device_util.h" namespace mlir { namespace TFDevice { namespace { constexpr char kDeviceAttr[] = "device"; constexpr char kReplicaIdAttr[] = "_xla_replica_id"; constexpr char kDeviceOrdinalAttr[] = "device_ordinal"; constexpr char kTPUCore0[] = "TPU_REPLICATED_CORE_0"; struct ReplicateToIslandPass : public PassWrapper<ReplicateToIslandPass, FunctionPass> { void runOnFunction() override; }; // Returns whether op requires `_xla_replica_id` attribute. bool RequiresReplicaIDAttribute(Operation* op) { return llvm::isa<TF::EnqueueTPUEmbeddingSparseTensorBatchOp, TF::EnqueueTPUEmbeddingRaggedTensorBatchOp>(op); } // Collects TPU device ordinal for outside compilation communication ops. This // currently assumes outside compilation only uses `TPU_REPLICATED_CORE_0` // aliased device for the device computation. llvm::Optional<int64_t> GetDeviceOrdinal( const llvm::Optional<DictionaryAttr>& devices, Location loc, unsigned replica_id) { int64_t device_ordinal = 0; if (devices.hasValue()) { if (auto tpu_replica_0 = devices.getValue().get(kTPUCore0)) { llvm::StringRef tpu_device = tpu_replica_0.cast<ArrayAttr>()[replica_id] .cast<StringAttr>() .getValue(); if (succeeded(tensorflow::GetDeviceOrdinalFromDeviceString( loc, tpu_device, &device_ordinal))) { return llvm::Optional<int64_t>(device_ordinal); } } } return llvm::None; } // Updates replica variant ops in a region based on replica `replica_id`. // TODO(b/157624749): Replace this with better abstraction to differentiate ops // for different replicas. Some ops, such as XlaHostCompute op or TPU Embedding // ops, require replica id to be added as an op attribute to be used during // execution. Handle such ops separately and add an integer attribute that // represents replica id. LogicalResult UpdateRegionReplicateVariantOps( OpBuilder& builder, Location loc, Region& region, int replica_id, const llvm::Optional<DictionaryAttr>& devices) { llvm::Optional<int64_t> device_ordinal = GetDeviceOrdinal(devices, loc, replica_id); auto result = region.walk([&](Operation* op) -> WalkResult { if (RequiresReplicaIDAttribute(op)) { op->setAttr(kReplicaIdAttr, builder.getI32IntegerAttr(replica_id)); return WalkResult::advance(); } if (isa<TF::_TPUDeviceOrdinalPlaceholderOp>(op)) { if (!device_ordinal.hasValue()) return op->emitOpError() << "requires device ordinal from device " << kTPUCore0 << " to be present in 'tf.device.replicate' op"; OpBuilder builder(op); auto const_op = builder.create<TF::ConstOp>( op->getLoc(), DenseIntElementsAttr::get( RankedTensorType::get({}, builder.getI64Type()), {device_ordinal.getValue()})); op->replaceAllUsesWith(const_op); op->erase(); return WalkResult::advance(); } if (!devices.hasValue()) return WalkResult::advance(); // Map aliased devices to explicit devices based on replica. if (auto launch = dyn_cast<tf_device::LaunchOp>(op)) if (auto device_by_replica = devices.getValue().get(launch.device())) launch.setAttr( kDeviceAttr, device_by_replica.cast<ArrayAttr>()[replica_id].cast<StringAttr>()); return WalkResult::advance(); }); return failure(result.wasInterrupted()); } // Creates islands per replica from `tf_device.replicate` region. If for a // `tf_device.launch` op the device is an aliased device of the // `tf_device.replicate`, the device will be remapped to an explicit device // for the associated replica island. LogicalResult ExpandReplicateIntoReplicas( const Dialect* tf_dialect, OpBuilder& builder, tf_executor::IslandOp island_op, tf_device::ReplicateOp replicate_op, int num_replicas, llvm::SmallVectorImpl<tf_executor::IslandOp>& replicas) { replicas.reserve(num_replicas); auto devices = replicate_op.devices(); // Collect result types and operands. Operation& terminator = replicate_op.GetBody().back(); llvm::SmallVector<Type, 8> output_types(terminator.getOperandTypes()); auto control_type = tf_executor::ControlType::get(island_op.getContext()); llvm::SmallVector<Value, 8> replica_inputs(island_op.controlInputs()); // Replace replicate terminator with YieldOp. builder.setInsertionPoint(&terminator); builder.create<tf_executor::YieldOp>(terminator.getLoc(), terminator.getOperands()); terminator.erase(); builder.setInsertionPoint(island_op); BlockAndValueMapping mapping; for (int i : llvm::seq<int>(0, num_replicas)) { // Create new island for replica. auto replica = builder.create<tf_executor::IslandOp>( island_op.getLoc(), output_types, control_type, replica_inputs); // Map block arg to replica arg. mapping.clear(); for (auto& block_arg : replicate_op.GetBody().getArguments()) mapping.map(block_arg, replicate_op.GetReplicaOperandForBlockArgument(block_arg, i)); // Copy over replicate region into replica island. replicate_op.body().cloneInto(&replica.body(), mapping); if (failed(UpdateRegionReplicateVariantOps(builder, replicate_op.getLoc(), replica.body(), /*replica_id=*/i, devices))) return failure(); replicas.push_back(replica); } return success(); } // Creates islands per replica from `tf_device.replicate` region and remap // replicate results with new island outputs. A single island is created to // forward control dependencies if there is a control dependency output from the // replicate island. Devices are remapped from aliased devices to explicit // devices, for `tf_device.launch` ops. // // For example, the following: // // %0:2 = tf_executor.island(%control) { // %1:4 = tf_device.replicate([%arg0, %arg1] as %ri: tensor<i1>) // {n = 2 : i32, // devices = {DEVICE_ALIAS_0 = ["/DEVICE:0", "/DEVICE:1"], // DEVICE_ALIAS_1 = ["/DEVICE:2", "/DEVICE:3"]}} { // %a = "tf_device.launch"() ( { // %2 = "tf.opA"(%ri) : (tensor<i1>) -> tensor<i1> // tf_device.return %2 : tensor<i1> // }) {device = "DEVICE_ALIAS_0"} : () -> tensor<i1> // %b = "tf_device.launch"() ( { // %3 = "tf.opB"(%a) : (tensor<i1>) -> tensor<i1> // tf_device.return %3 : tensor<i1> // }) {device = "DEVICE_ALIAS_1"} : () -> tensor<i1> // tf_device.return %a, %b : tensor<i1>, tensor<i1> // } // tf_executor.yield %1#0 : tensor<i1> // } // // gets lowered to: // // %0:3 = tf_executor.island(%control) { // %a0 = "tf_device.launch"() ( { // %1 = "tf.opA"(%arg0) : (tensor<i1>) -> tensor<i1> // tf_device.return %1 : tensor<i1> // }) {device = "/DEVICE:0"} : () -> tensor<i1> // %b0 = "tf_device.launch"() ( { // %2 = "tf.opB"(%a0) : (tensor<i1>) -> tensor<i1> // tf_device.return %2 : tensor<i1> // }) {device = "/DEVICE:2"} : () -> tensor<i1> // tf_executor.yield %a0, %b0 : tensor<i1>, tensor<i1> // } // %3:3 = tf_executor.island(%control) { // %a1 = "tf_device.launch"() ( { // %4 = "tf.opA"(%arg1) : (tensor<i1>) -> tensor<i1> // tf_device.return %4 : tensor<i1> // }) {device = "/DEVICE:1"} : () -> tensor<i1> // %b1 = "tf_device.launch"() ( { // %5 = "tf.opB"(%a1) : (tensor<i1>) -> tensor<i1> // tf_device.return %5 : tensor<i1> // }) {device = "/DEVICE:3"} : () -> tensor<i1> // tf_executor.yield %a1, %b1 : tensor<i1>, tensor<i1> // } LogicalResult CreateIslandsFromReplicate(const Dialect* tf_dialect, tf_executor::GraphOp graph_op, tf_executor::IslandOp island_op, tf_device::ReplicateOp replicate_op) { OpBuilder builder(island_op); const int num_replicas = replicate_op.n(); // Create islands per replica. llvm::SmallVector<tf_executor::IslandOp, 8> replicas; if (failed(ExpandReplicateIntoReplicas(tf_dialect, builder, island_op, replicate_op, num_replicas, replicas))) return failure(); // Collect all replica results. llvm::SmallVector<Value, 8> replicas_outputs(replicate_op.getNumResults(), nullptr); for (auto replica_and_idx : llvm::enumerate(replicas)) for (auto replica_result_and_idx : llvm::enumerate(replica_and_idx.value().outputs())) replicas_outputs[num_replicas * replica_result_and_idx.index() + replica_and_idx.index()] = replica_result_and_idx.value(); // Remap replicate results to per replica result. for (auto result : llvm::zip(island_op.outputs(), replicas_outputs)) std::get<0>(result).replaceAllUsesWith(std::get<1>(result)); // Add sink island to pin all replicas as a control dependency if there is a // control dependency leading from the replicate originally. if (!island_op.control().use_empty()) { llvm::SmallVector<Value, 8> island_operands; for (auto& replica : replicas) island_operands.push_back(replica.control()); builder.setInsertionPoint(island_op); auto island_sink = builder.create<tf_executor::IslandOp>( island_op.getLoc(), llvm::ArrayRef<Type>{}, tf_executor::ControlType::get(island_op.getContext()), island_operands); island_sink.body().push_back(new Block); builder.setInsertionPointToEnd(&island_sink.GetBody()); builder.create<tf_executor::YieldOp>(island_op.getLoc(), llvm::ArrayRef<Value>{}); island_op.control().replaceAllUsesWith(island_sink.control()); } // Replicas with no uses should be pinned to a graph fetch so they still // execute. llvm::SmallVector<Value, 8> unused_replica_controls; for (auto& replica : replicas) if (replica.use_empty()) unused_replica_controls.push_back(replica.control()); if (!unused_replica_controls.empty()) { tf_executor::FetchOp fetch = graph_op.GetFetch(); auto fetches = llvm::to_vector<8>(fetch.getOperands()); fetches.append(unused_replica_controls.begin(), unused_replica_controls.end()); builder.setInsertionPoint(fetch); builder.create<tf_executor::FetchOp>(fetch.getLoc(), fetches); fetch.erase(); } island_op.erase(); return success(); } void ReplicateToIslandPass::runOnFunction() { const Dialect* tf_dialect = getContext().getLoadedDialect("tf"); if (!tf_dialect) { getOperation().emitError() << "'tf' dialect is not registered"; return signalPassFailure(); } // Find islands with a single `tf_device.replicate` and create individual // islands per replica of the replicate. llvm::SmallVector<tf_executor::IslandOp, 4> replicate_op_islands; getOperation().walk([&](tf_executor::GraphOp graph_op) { for (auto island_op : graph_op.getOps<tf_executor::IslandOp>()) { if (!island_op.WrapsSingleOp()) continue; if (isa<tf_device::ReplicateOp>(&island_op.GetBody().front())) replicate_op_islands.push_back(island_op); } }); for (tf_executor::IslandOp island_op : replicate_op_islands) { auto graph_op = island_op.getParentOfType<tf_executor::GraphOp>(); auto replicate_op = cast<tf_device::ReplicateOp>(island_op.GetBody().front()); if (failed(CreateIslandsFromReplicate(tf_dialect, graph_op, island_op, replicate_op))) return signalPassFailure(); } } } // anonymous namespace std::unique_ptr<OperationPass<FuncOp>> CreateReplicateToIslandPass() { return std::make_unique<ReplicateToIslandPass>(); } static PassRegistration<ReplicateToIslandPass> pass( "tf-replicate-to-island", "Lowers device replicate to executor islands"); } // namespace TFDevice } // namespace mlir <commit_msg>Set _xla_replica_id attribute as a i64 attribute instead of a i32 (NFC).<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. ==============================================================================*/ // This pass forms `tf_executor.island` per replica from a single // `tf_device.replicate` island. #include <memory> #include <utility> #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/None.h" #include "llvm/ADT/Optional.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/Sequence.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/Casting.h" #include "mlir/IR/Attributes.h" // from @llvm-project #include "mlir/IR/Block.h" // from @llvm-project #include "mlir/IR/BlockAndValueMapping.h" // from @llvm-project #include "mlir/IR/Builders.h" // from @llvm-project #include "mlir/IR/Diagnostics.h" // from @llvm-project #include "mlir/IR/Dialect.h" // from @llvm-project #include "mlir/IR/Visitors.h" // from @llvm-project #include "mlir/Pass/Pass.h" // from @llvm-project #include "mlir/Support/LogicalResult.h" // from @llvm-project #include "tensorflow/compiler/mlir/tensorflow/ir/tf_device.h" #include "tensorflow/compiler/mlir/tensorflow/ir/tf_executor.h" #include "tensorflow/compiler/mlir/tensorflow/ir/tf_ops.h" #include "tensorflow/compiler/mlir/tensorflow/utils/device_util.h" #include "tensorflow/compiler/mlir/tensorflow/utils/tpu_rewrite_device_util.h" namespace mlir { namespace TFDevice { namespace { constexpr char kDeviceAttr[] = "device"; constexpr char kReplicaIdAttr[] = "_xla_replica_id"; constexpr char kDeviceOrdinalAttr[] = "device_ordinal"; constexpr char kTPUCore0[] = "TPU_REPLICATED_CORE_0"; struct ReplicateToIslandPass : public PassWrapper<ReplicateToIslandPass, FunctionPass> { void runOnFunction() override; }; // Returns whether op requires `_xla_replica_id` attribute. bool RequiresReplicaIDAttribute(Operation* op) { return llvm::isa<TF::EnqueueTPUEmbeddingSparseTensorBatchOp, TF::EnqueueTPUEmbeddingRaggedTensorBatchOp>(op); } // Collects TPU device ordinal for outside compilation communication ops. This // currently assumes outside compilation only uses `TPU_REPLICATED_CORE_0` // aliased device for the device computation. llvm::Optional<int64_t> GetDeviceOrdinal( const llvm::Optional<DictionaryAttr>& devices, Location loc, unsigned replica_id) { int64_t device_ordinal = 0; if (devices.hasValue()) { if (auto tpu_replica_0 = devices.getValue().get(kTPUCore0)) { llvm::StringRef tpu_device = tpu_replica_0.cast<ArrayAttr>()[replica_id] .cast<StringAttr>() .getValue(); if (succeeded(tensorflow::GetDeviceOrdinalFromDeviceString( loc, tpu_device, &device_ordinal))) { return llvm::Optional<int64_t>(device_ordinal); } } } return llvm::None; } // Updates replica variant ops in a region based on replica `replica_id`. // TODO(b/157624749): Replace this with better abstraction to differentiate ops // for different replicas. Some ops, such as XlaHostCompute op or TPU Embedding // ops, require replica id to be added as an op attribute to be used during // execution. Handle such ops separately and add an integer attribute that // represents replica id. LogicalResult UpdateRegionReplicateVariantOps( OpBuilder& builder, Location loc, Region& region, int replica_id, const llvm::Optional<DictionaryAttr>& devices) { llvm::Optional<int64_t> device_ordinal = GetDeviceOrdinal(devices, loc, replica_id); auto result = region.walk([&](Operation* op) -> WalkResult { if (RequiresReplicaIDAttribute(op)) { op->setAttr(kReplicaIdAttr, builder.getI64IntegerAttr(replica_id)); return WalkResult::advance(); } if (isa<TF::_TPUDeviceOrdinalPlaceholderOp>(op)) { if (!device_ordinal.hasValue()) return op->emitOpError() << "requires device ordinal from device " << kTPUCore0 << " to be present in 'tf.device.replicate' op"; OpBuilder builder(op); auto const_op = builder.create<TF::ConstOp>( op->getLoc(), DenseIntElementsAttr::get( RankedTensorType::get({}, builder.getI64Type()), {device_ordinal.getValue()})); op->replaceAllUsesWith(const_op); op->erase(); return WalkResult::advance(); } if (!devices.hasValue()) return WalkResult::advance(); // Map aliased devices to explicit devices based on replica. if (auto launch = dyn_cast<tf_device::LaunchOp>(op)) if (auto device_by_replica = devices.getValue().get(launch.device())) launch.setAttr( kDeviceAttr, device_by_replica.cast<ArrayAttr>()[replica_id].cast<StringAttr>()); return WalkResult::advance(); }); return failure(result.wasInterrupted()); } // Creates islands per replica from `tf_device.replicate` region. If for a // `tf_device.launch` op the device is an aliased device of the // `tf_device.replicate`, the device will be remapped to an explicit device // for the associated replica island. LogicalResult ExpandReplicateIntoReplicas( const Dialect* tf_dialect, OpBuilder& builder, tf_executor::IslandOp island_op, tf_device::ReplicateOp replicate_op, int num_replicas, llvm::SmallVectorImpl<tf_executor::IslandOp>& replicas) { replicas.reserve(num_replicas); auto devices = replicate_op.devices(); // Collect result types and operands. Operation& terminator = replicate_op.GetBody().back(); llvm::SmallVector<Type, 8> output_types(terminator.getOperandTypes()); auto control_type = tf_executor::ControlType::get(island_op.getContext()); llvm::SmallVector<Value, 8> replica_inputs(island_op.controlInputs()); // Replace replicate terminator with YieldOp. builder.setInsertionPoint(&terminator); builder.create<tf_executor::YieldOp>(terminator.getLoc(), terminator.getOperands()); terminator.erase(); builder.setInsertionPoint(island_op); BlockAndValueMapping mapping; for (int i : llvm::seq<int>(0, num_replicas)) { // Create new island for replica. auto replica = builder.create<tf_executor::IslandOp>( island_op.getLoc(), output_types, control_type, replica_inputs); // Map block arg to replica arg. mapping.clear(); for (auto& block_arg : replicate_op.GetBody().getArguments()) mapping.map(block_arg, replicate_op.GetReplicaOperandForBlockArgument(block_arg, i)); // Copy over replicate region into replica island. replicate_op.body().cloneInto(&replica.body(), mapping); if (failed(UpdateRegionReplicateVariantOps(builder, replicate_op.getLoc(), replica.body(), /*replica_id=*/i, devices))) return failure(); replicas.push_back(replica); } return success(); } // Creates islands per replica from `tf_device.replicate` region and remap // replicate results with new island outputs. A single island is created to // forward control dependencies if there is a control dependency output from the // replicate island. Devices are remapped from aliased devices to explicit // devices, for `tf_device.launch` ops. // // For example, the following: // // %0:2 = tf_executor.island(%control) { // %1:4 = tf_device.replicate([%arg0, %arg1] as %ri: tensor<i1>) // {n = 2 : i32, // devices = {DEVICE_ALIAS_0 = ["/DEVICE:0", "/DEVICE:1"], // DEVICE_ALIAS_1 = ["/DEVICE:2", "/DEVICE:3"]}} { // %a = "tf_device.launch"() ( { // %2 = "tf.opA"(%ri) : (tensor<i1>) -> tensor<i1> // tf_device.return %2 : tensor<i1> // }) {device = "DEVICE_ALIAS_0"} : () -> tensor<i1> // %b = "tf_device.launch"() ( { // %3 = "tf.opB"(%a) : (tensor<i1>) -> tensor<i1> // tf_device.return %3 : tensor<i1> // }) {device = "DEVICE_ALIAS_1"} : () -> tensor<i1> // tf_device.return %a, %b : tensor<i1>, tensor<i1> // } // tf_executor.yield %1#0 : tensor<i1> // } // // gets lowered to: // // %0:3 = tf_executor.island(%control) { // %a0 = "tf_device.launch"() ( { // %1 = "tf.opA"(%arg0) : (tensor<i1>) -> tensor<i1> // tf_device.return %1 : tensor<i1> // }) {device = "/DEVICE:0"} : () -> tensor<i1> // %b0 = "tf_device.launch"() ( { // %2 = "tf.opB"(%a0) : (tensor<i1>) -> tensor<i1> // tf_device.return %2 : tensor<i1> // }) {device = "/DEVICE:2"} : () -> tensor<i1> // tf_executor.yield %a0, %b0 : tensor<i1>, tensor<i1> // } // %3:3 = tf_executor.island(%control) { // %a1 = "tf_device.launch"() ( { // %4 = "tf.opA"(%arg1) : (tensor<i1>) -> tensor<i1> // tf_device.return %4 : tensor<i1> // }) {device = "/DEVICE:1"} : () -> tensor<i1> // %b1 = "tf_device.launch"() ( { // %5 = "tf.opB"(%a1) : (tensor<i1>) -> tensor<i1> // tf_device.return %5 : tensor<i1> // }) {device = "/DEVICE:3"} : () -> tensor<i1> // tf_executor.yield %a1, %b1 : tensor<i1>, tensor<i1> // } LogicalResult CreateIslandsFromReplicate(const Dialect* tf_dialect, tf_executor::GraphOp graph_op, tf_executor::IslandOp island_op, tf_device::ReplicateOp replicate_op) { OpBuilder builder(island_op); const int num_replicas = replicate_op.n(); // Create islands per replica. llvm::SmallVector<tf_executor::IslandOp, 8> replicas; if (failed(ExpandReplicateIntoReplicas(tf_dialect, builder, island_op, replicate_op, num_replicas, replicas))) return failure(); // Collect all replica results. llvm::SmallVector<Value, 8> replicas_outputs(replicate_op.getNumResults(), nullptr); for (auto replica_and_idx : llvm::enumerate(replicas)) for (auto replica_result_and_idx : llvm::enumerate(replica_and_idx.value().outputs())) replicas_outputs[num_replicas * replica_result_and_idx.index() + replica_and_idx.index()] = replica_result_and_idx.value(); // Remap replicate results to per replica result. for (auto result : llvm::zip(island_op.outputs(), replicas_outputs)) std::get<0>(result).replaceAllUsesWith(std::get<1>(result)); // Add sink island to pin all replicas as a control dependency if there is a // control dependency leading from the replicate originally. if (!island_op.control().use_empty()) { llvm::SmallVector<Value, 8> island_operands; for (auto& replica : replicas) island_operands.push_back(replica.control()); builder.setInsertionPoint(island_op); auto island_sink = builder.create<tf_executor::IslandOp>( island_op.getLoc(), llvm::ArrayRef<Type>{}, tf_executor::ControlType::get(island_op.getContext()), island_operands); island_sink.body().push_back(new Block); builder.setInsertionPointToEnd(&island_sink.GetBody()); builder.create<tf_executor::YieldOp>(island_op.getLoc(), llvm::ArrayRef<Value>{}); island_op.control().replaceAllUsesWith(island_sink.control()); } // Replicas with no uses should be pinned to a graph fetch so they still // execute. llvm::SmallVector<Value, 8> unused_replica_controls; for (auto& replica : replicas) if (replica.use_empty()) unused_replica_controls.push_back(replica.control()); if (!unused_replica_controls.empty()) { tf_executor::FetchOp fetch = graph_op.GetFetch(); auto fetches = llvm::to_vector<8>(fetch.getOperands()); fetches.append(unused_replica_controls.begin(), unused_replica_controls.end()); builder.setInsertionPoint(fetch); builder.create<tf_executor::FetchOp>(fetch.getLoc(), fetches); fetch.erase(); } island_op.erase(); return success(); } void ReplicateToIslandPass::runOnFunction() { const Dialect* tf_dialect = getContext().getLoadedDialect("tf"); if (!tf_dialect) { getOperation().emitError() << "'tf' dialect is not registered"; return signalPassFailure(); } // Find islands with a single `tf_device.replicate` and create individual // islands per replica of the replicate. llvm::SmallVector<tf_executor::IslandOp, 4> replicate_op_islands; getOperation().walk([&](tf_executor::GraphOp graph_op) { for (auto island_op : graph_op.getOps<tf_executor::IslandOp>()) { if (!island_op.WrapsSingleOp()) continue; if (isa<tf_device::ReplicateOp>(&island_op.GetBody().front())) replicate_op_islands.push_back(island_op); } }); for (tf_executor::IslandOp island_op : replicate_op_islands) { auto graph_op = island_op.getParentOfType<tf_executor::GraphOp>(); auto replicate_op = cast<tf_device::ReplicateOp>(island_op.GetBody().front()); if (failed(CreateIslandsFromReplicate(tf_dialect, graph_op, island_op, replicate_op))) return signalPassFailure(); } } } // anonymous namespace std::unique_ptr<OperationPass<FuncOp>> CreateReplicateToIslandPass() { return std::make_unique<ReplicateToIslandPass>(); } static PassRegistration<ReplicateToIslandPass> pass( "tf-replicate-to-island", "Lowers device replicate to executor islands"); } // namespace TFDevice } // namespace mlir <|endoftext|>
<commit_before>#include <boost/test/unit_test.hpp> #include <vector> #include "clotho/utility/bit_walker.hpp" typedef unsigned long block_type; typedef unsigned short sub_block_type; typedef clotho::utility::block_walker< block_type, sub_block_type > walker_type; struct set_bit_vector_op { set_bit_vector_op() {} void operator()( unsigned int idx ) { indices.push_back(idx); } void reset() { indices.clear(); } std::vector< unsigned int > indices; }; BOOST_AUTO_TEST_SUITE( test_utility ) /** * Verify bits_per_block are initialized appropriately */ BOOST_AUTO_TEST_CASE( test_bit_walker_bit_sizes ) { const unsigned int bpb = walker_type::bits_per_block; const unsigned int bpsb = walker_type::bits_per_subblock; BOOST_REQUIRE_MESSAGE( bpb == sizeof(block_type) * 8, "Unexpected bits_per_block: " << bpb << " (" << (sizeof(block_type) * 8) << ")"); BOOST_REQUIRE_MESSAGE( bpsb == sizeof(sub_block_type) * 8, "Unexpected bits_per_subblock: " << bpsb << " (" << (sizeof(sub_block_type) * 8) << ")"); } BOOST_AUTO_TEST_CASE( test_bit_node_init ) { walker_type::bit_walker_type bw; for( unsigned int i = 1; i < walker_type::bit_walker_type::max_nodes; ++i ) { unsigned int s = (i & (1 << bw.getNode()[i].bit_index)); BOOST_REQUIRE_MESSAGE( s != 0, "Unexpected bit state: " << i << " @ " << bw.getNode()[i].bit_index ); if( bw.getNode()[i].next ) { unsigned int k = (i >> bw.getNode()[i].bit_shift_next); BOOST_REQUIRE_MESSAGE( k == bw.getNode()[i].next, "Unexpected next node: " << i << " -> " << k << " (" << bw.getNode()[i].next << ")"); } } } /** * Initialize a block with every odd bit set, and initialize an expected index vector * * Apply the set_bit_vector_op * * Verify that the result vector matches the expected vector */ BOOST_AUTO_TEST_CASE( test_bit_walker_set_bits ) { std::vector< unsigned int > expected; block_type _bits = 0, mask = 1; for( unsigned int i = 0; i < walker_type::bits_per_block; ++i ) { if( i & 1 ) { expected.push_back( i ); _bits |= mask; } mask <<= 1; } set_bit_vector_op sbv; walker_type::apply( _bits, sbv ); BOOST_REQUIRE_MESSAGE( sbv.indices == expected, "Unexpected list of set bits was returned" ); } BOOST_AUTO_TEST_SUITE_END() <commit_msg>Testing type_trait specifications<commit_after>#include <boost/test/unit_test.hpp> #include <vector> #include <type_traits> #include "clotho/utility/bit_walker.hpp" typedef unsigned long block_type; typedef unsigned short sub_block_type; typedef clotho::utility::block_walker< block_type, sub_block_type > walker_type; typedef clotho::utility::block_walker< block_type, sub_block_type, clotho::utility::bit_block_walker< sizeof(block_type) * 8> > other_walker_type; struct set_bit_vector_op { set_bit_vector_op() {} void operator()( unsigned int idx ) { indices.push_back(idx); } void reset() { indices.clear(); } std::vector< unsigned int > indices; }; BOOST_AUTO_TEST_SUITE( test_utility ) /** * Verify bits_per_block are initialized appropriately */ BOOST_AUTO_TEST_CASE( test_bit_walker_bit_sizes ) { const unsigned int bpb = walker_type::bits_per_block; const unsigned int bpsb = walker_type::bits_per_subblock; BOOST_REQUIRE_MESSAGE( bpb == sizeof(block_type) * 8, "Unexpected bits_per_block: " << bpb << " (" << (sizeof(block_type) * 8) << ")"); BOOST_REQUIRE_MESSAGE( bpsb == sizeof(sub_block_type) * 8, "Unexpected bits_per_subblock: " << bpsb << " (" << (sizeof(sub_block_type) * 8) << ")"); } BOOST_AUTO_TEST_CASE( test_bit_node_init ) { walker_type::bit_walker_type bw; for( unsigned int i = 1; i < walker_type::bit_walker_type::max_nodes; ++i ) { unsigned int s = (i & (1 << bw.getNode()[i].bit_index)); BOOST_REQUIRE_MESSAGE( s != 0, "Unexpected bit state: " << i << " @ " << bw.getNode()[i].bit_index ); if( bw.getNode()[i].next ) { unsigned int k = (i >> bw.getNode()[i].bit_shift_next); BOOST_REQUIRE_MESSAGE( k == bw.getNode()[i].next, "Unexpected next node: " << i << " -> " << k << " (" << bw.getNode()[i].next << ")"); } } } /** * Initialize a block with every odd bit set, and initialize an expected index vector * * Apply the set_bit_vector_op * * Verify that the result vector matches the expected vector */ BOOST_AUTO_TEST_CASE( test_bit_walker_set_bits ) { std::vector< unsigned int > expected; block_type _bits = 0, mask = 1; for( unsigned int i = 0; i < walker_type::bits_per_block; ++i ) { if( i & 1 ) { expected.push_back( i ); _bits |= mask; } mask <<= 1; } set_bit_vector_op sbv; walker_type::apply( _bits, sbv ); BOOST_REQUIRE_MESSAGE( sbv.indices == expected, "Unexpected list of set bits was returned" ); } /** * Initialize a block with every odd bit set, and initialize an expected index vector * * Apply the set_bit_vector_op * * Verify that the result vector matches the expected vector */ BOOST_AUTO_TEST_CASE( test_other_bit_walker_set_bits ) { BOOST_REQUIRE_MESSAGE( (std::is_same< other_walker_type::bit_walker_type, clotho::utility::bit_block_walker< sizeof(block_type) * 8 > >::value), "Unexpected bit block walker (test 1)" ); BOOST_REQUIRE_MESSAGE( (!std::is_same< other_walker_type::bit_walker_type, clotho::utility::bit_block_walker< 16 > >::value), "Unexpected bit block walker (test 2)" ); std::vector< unsigned int > expected; block_type _bits = 0, mask = 1; for( unsigned int i = 0; i < walker_type::bits_per_block; ++i ) { if( i & 1 ) { expected.push_back( i ); _bits |= mask; } mask <<= 1; } set_bit_vector_op sbv; other_walker_type::apply( _bits, sbv ); BOOST_REQUIRE_MESSAGE( sbv.indices == expected, "Unexpected list of set bits was returned" ); } BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>//===- TypeTraitsTest.cpp -------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/Support/type_traits.h" namespace { // Compile-time tests using static assert. namespace triviality { // Helper for compile time checking trivially copy constructible and trivially // move constructible type traits. template <typename T, bool IsTriviallyCopyConstructible, bool IsTriviallyMoveConstructible> void TrivialityTester() { static_assert(llvm::is_trivially_copy_constructible<T>::value == IsTriviallyCopyConstructible, "Mismatch in expected trivial copy construction!"); static_assert(llvm::is_trivially_move_constructible<T>::value == IsTriviallyMoveConstructible, "Mismatch in expected trivial move construction!"); #if __clang__ || _MSC_VER || __GNUC__ > 5 // On compilers with support for the standard traits, make sure they agree. static_assert(std::is_trivially_copy_constructible<T>::value == IsTriviallyCopyConstructible, "Mismatch in expected trivial copy construction!"); static_assert(std::is_trivially_move_constructible<T>::value == IsTriviallyMoveConstructible, "Mismatch in expected trivial move construction!"); #endif }; template void TrivialityTester<int, true, true>(); template void TrivialityTester<void *, true, true>(); template void TrivialityTester<int &, true, true>(); template void TrivialityTester<int &&, false, true>(); struct X {}; struct Y { Y(const Y &); }; struct Z { Z(const Z &); Z(Z &&); }; struct A { A(const A &) = default; A(A &&); }; struct B { B(const B &); B(B &&) = default; }; template void TrivialityTester<X, true, true>(); template void TrivialityTester<Y, false, false>(); template void TrivialityTester<Z, false, false>(); template void TrivialityTester<A, true, false>(); template void TrivialityTester<B, false, true>(); template void TrivialityTester<Z &, true, true>(); template void TrivialityTester<A &, true, true>(); template void TrivialityTester<B &, true, true>(); template void TrivialityTester<Z &&, false, true>(); template void TrivialityTester<A &&, false, true>(); template void TrivialityTester<B &&, false, true>(); } // namespace triviality } // end anonymous namespace <commit_msg>[Support] This sanity check in the test only works with certain versions of libstdc++, not just certain versions of GCC. The original macros broke when using Clang + libstdc++4.9 sadly.<commit_after>//===- TypeTraitsTest.cpp -------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/Support/type_traits.h" namespace { // Compile-time tests using static assert. namespace triviality { // Helper for compile time checking trivially copy constructible and trivially // move constructible type traits. template <typename T, bool IsTriviallyCopyConstructible, bool IsTriviallyMoveConstructible> void TrivialityTester() { static_assert(llvm::is_trivially_copy_constructible<T>::value == IsTriviallyCopyConstructible, "Mismatch in expected trivial copy construction!"); static_assert(llvm::is_trivially_move_constructible<T>::value == IsTriviallyMoveConstructible, "Mismatch in expected trivial move construction!"); #if defined(_LIBCPP_VERSION) || defined(_MSC_VER) // On compilers with support for the standard traits, make sure they agree. static_assert(std::is_trivially_copy_constructible<T>::value == IsTriviallyCopyConstructible, "Mismatch in expected trivial copy construction!"); static_assert(std::is_trivially_move_constructible<T>::value == IsTriviallyMoveConstructible, "Mismatch in expected trivial move construction!"); #endif }; template void TrivialityTester<int, true, true>(); template void TrivialityTester<void *, true, true>(); template void TrivialityTester<int &, true, true>(); template void TrivialityTester<int &&, false, true>(); struct X {}; struct Y { Y(const Y &); }; struct Z { Z(const Z &); Z(Z &&); }; struct A { A(const A &) = default; A(A &&); }; struct B { B(const B &); B(B &&) = default; }; template void TrivialityTester<X, true, true>(); template void TrivialityTester<Y, false, false>(); template void TrivialityTester<Z, false, false>(); template void TrivialityTester<A, true, false>(); template void TrivialityTester<B, false, true>(); template void TrivialityTester<Z &, true, true>(); template void TrivialityTester<A &, true, true>(); template void TrivialityTester<B &, true, true>(); template void TrivialityTester<Z &&, false, true>(); template void TrivialityTester<A &&, false, true>(); template void TrivialityTester<B &&, false, true>(); } // namespace triviality } // end anonymous namespace <|endoftext|>
<commit_before>#include <algorithm> #include <chrono> #include <cmath> #include <iostream> #include <string> #include <sys/time.h> #include <thread> #include <rclcpp/rclcpp.hpp> #include <simple_msgs/AllBuiltinTypes.h> #include <simple_msgs/AllDynamicArrayTypes.h> #include <simple_msgs/AllPrimitiveTypes.h> #include <simple_msgs/AllStaticArrayTypes.h> #include <simple_msgs/Nested.h> #include <simple_msgs/String.h> #include <simple_msgs/Uint32.h> #include <userland_msgs/AddTwoInts.h> int main(int argc, char** argv) { rclcpp::init(argc, argv); auto node = rclcpp::Node::make_shared("add_two_ints_client"); auto client = node->create_client<userland_msgs::AddTwoInts>("add_two_ints"); auto request = std::make_shared<userland_msgs::AddTwoInts::Request>(); auto response = std::make_shared<userland_msgs::AddTwoInts::Response>(); request->a = 2; request->b = 3; auto f = client->async_send_request(request, response); std::future_status status; do { rclcpp::spin_some(node); status = f.wait_for(std::chrono::milliseconds(100)); } while(status != std::future_status::ready && rclcpp::ok()); if(std::future_status::ready == status) { std::cout << "FUTURE READY" << std::endl; std::cout << f.get()->sum << std::endl; } return 0; } <commit_msg>Added example for callback-based client<commit_after>#include <algorithm> #include <chrono> #include <cmath> #include <iostream> #include <string> #include <sys/time.h> #include <thread> #include <rclcpp/rclcpp.hpp> #include <simple_msgs/AllBuiltinTypes.h> #include <simple_msgs/AllDynamicArrayTypes.h> #include <simple_msgs/AllPrimitiveTypes.h> #include <simple_msgs/AllStaticArrayTypes.h> #include <simple_msgs/Nested.h> #include <simple_msgs/String.h> #include <simple_msgs/Uint32.h> #include <userland_msgs/AddTwoInts.h> int main(int argc, char** argv) { rclcpp::init(argc, argv); auto node = rclcpp::Node::make_shared("add_two_ints_client"); auto client = node->create_client<userland_msgs::AddTwoInts>("add_two_ints"); auto request = std::make_shared<userland_msgs::AddTwoInts::Request>(); auto response = std::make_shared<userland_msgs::AddTwoInts::Response>(); request->a = 2; request->b = 3; auto f = client->async_send_request(request, response); std::future_status status; do { rclcpp::spin_some(node); status = f.wait_for(std::chrono::milliseconds(100)); } while(status != std::future_status::ready && rclcpp::ok()); if(std::future_status::ready == status) { std::cout << "FUTURE READY" << std::endl; std::cout << f.get()->sum << std::endl; } client->async_send_request( request, response, [] (rclcpp::client::Client<userland_msgs::AddTwoInts>::SharedFuture f) { std::cout << "CALLBACK" << std::endl; }); rclcpp::spin(node); return 0; } <|endoftext|>
<commit_before>/** * This file is part of the CernVM File System. */ #include "cvmfs_config.h" #include "swissknife_lsrepo.h" #include "logging.h" namespace swissknife { CommandListCatalogs::CommandListCatalogs() : print_tree_(false), print_hash_(false), print_size_(false), print_entries_(false) {} ParameterList CommandListCatalogs::GetParams() { ParameterList r; r.push_back(Parameter::Mandatory( 'r', "repository URL (absolute local path or remote URL)")); r.push_back(Parameter::Optional('n', "fully qualified repository name")); r.push_back(Parameter::Optional('k', "repository master key(s)")); r.push_back(Parameter::Optional('l', "temporary directory")); r.push_back(Parameter::Switch('t', "print tree structure of catalogs")); r.push_back(Parameter::Switch('d', "print digest for each catalog")); r.push_back(Parameter::Switch('s', "print catalog file sizes")); r.push_back(Parameter::Switch('e', "print number of catalog entries")); return r; } int CommandListCatalogs::Main(const ArgumentList &args) { print_tree_ = (args.count('t') > 0); print_hash_ = (args.count('d') > 0); print_size_ = (args.count('s') > 0); print_entries_ = (args.count('e') > 0); const std::string &repo_url = *args.find('r')->second; const std::string &repo_name = (args.count('n') > 0) ? *args.find('n')->second : ""; const std::string &repo_keys = (args.count('k') > 0) ? *args.find('k')->second : ""; const std::string &tmp_dir = (args.count('l') > 0) ? *args.find('l')->second : "/tmp"; bool success = false; if (IsHttpUrl(repo_url)) { download::DownloadManager download_manager; signature::SignatureManager signature_manager; download_manager.Init(1, true, g_statistics); signature_manager.Init(); if (!signature_manager.LoadPublicRsaKeys(repo_keys)) { LogCvmfs(kLogCatalog, kLogStderr, "Failed to load public key(s)"); return 1; } HttpObjectFetcher<catalog::Catalog, history::SqliteHistory> fetcher(repo_name, repo_url, tmp_dir, &download_manager, &signature_manager); success = Run(&fetcher); download_manager.Fini(); signature_manager.Fini(); } else { LocalObjectFetcher<> fetcher(repo_url, tmp_dir); success = Run(&fetcher); } return (success) ? 0 : 1; } void CommandListCatalogs::CatalogCallback( const CatalogTraversalData<catalog::Catalog> &data) { std::string tree_indent; std::string hash_string; std::string clg_size; std::string clg_entries; std::string path; if (print_tree_) { for (unsigned int i = 1; i < data.tree_level; ++i) { tree_indent += "\u2502 "; } if (data.tree_level > 0) tree_indent += "\u251C\u2500 "; } if (print_hash_) { hash_string = data.catalog_hash.ToString() + " "; } if (print_size_) { clg_size = StringifyInt(data.file_size) + "B "; } if (print_entries_) { clg_entries = StringifyInt(data.catalog->GetNumEntries()) + " "; } path = data.catalog->path().ToString(); if (path.empty()) path = "/"; LogCvmfs(kLogCatalog, kLogStdout, "%s%s%s%s%s", tree_indent.c_str(), hash_string.c_str(), clg_size.c_str(), clg_entries.c_str(), path.c_str()); } } // namespace swissknife <commit_msg>Refactor: use centralised manifest fetching in lsrepo<commit_after>/** * This file is part of the CernVM File System. */ #include "cvmfs_config.h" #include "swissknife_lsrepo.h" #include "logging.h" namespace swissknife { CommandListCatalogs::CommandListCatalogs() : print_tree_(false), print_hash_(false), print_size_(false), print_entries_(false) {} ParameterList CommandListCatalogs::GetParams() { ParameterList r; r.push_back(Parameter::Mandatory( 'r', "repository URL (absolute local path or remote URL)")); r.push_back(Parameter::Optional('n', "fully qualified repository name")); r.push_back(Parameter::Optional('k', "repository master key(s)")); r.push_back(Parameter::Optional('l', "temporary directory")); r.push_back(Parameter::Switch('t', "print tree structure of catalogs")); r.push_back(Parameter::Switch('d', "print digest for each catalog")); r.push_back(Parameter::Switch('s', "print catalog file sizes")); r.push_back(Parameter::Switch('e', "print number of catalog entries")); return r; } int CommandListCatalogs::Main(const ArgumentList &args) { print_tree_ = (args.count('t') > 0); print_hash_ = (args.count('d') > 0); print_size_ = (args.count('s') > 0); print_entries_ = (args.count('e') > 0); const std::string &repo_url = *args.find('r')->second; const std::string &repo_name = (args.count('n') > 0) ? *args.find('n')->second : ""; const std::string &repo_keys = (args.count('k') > 0) ? *args.find('k')->second : ""; const std::string &tmp_dir = (args.count('l') > 0) ? *args.find('l')->second : "/tmp"; bool success = false; if (IsHttpUrl(repo_url)) { const bool follow_redirects = false; if (!this->InitDownloadManager(follow_redirects) || !this->InitSignatureManager(repo_keys)) { LogCvmfs(kLogCatalog, kLogStderr, "Failed to init remote connection"); return 1; } HttpObjectFetcher<catalog::Catalog, history::SqliteHistory> fetcher(repo_name, repo_url, tmp_dir, download_manager(), signature_manager()); success = Run(&fetcher); } else { LocalObjectFetcher<> fetcher(repo_url, tmp_dir); success = Run(&fetcher); } return (success) ? 0 : 1; } void CommandListCatalogs::CatalogCallback( const CatalogTraversalData<catalog::Catalog> &data) { std::string tree_indent; std::string hash_string; std::string clg_size; std::string clg_entries; std::string path; if (print_tree_) { for (unsigned int i = 1; i < data.tree_level; ++i) { tree_indent += "\u2502 "; } if (data.tree_level > 0) tree_indent += "\u251C\u2500 "; } if (print_hash_) { hash_string = data.catalog_hash.ToString() + " "; } if (print_size_) { clg_size = StringifyInt(data.file_size) + "B "; } if (print_entries_) { clg_entries = StringifyInt(data.catalog->GetNumEntries()) + " "; } path = data.catalog->path().ToString(); if (path.empty()) path = "/"; LogCvmfs(kLogCatalog, kLogStdout, "%s%s%s%s%s", tree_indent.c_str(), hash_string.c_str(), clg_size.c_str(), clg_entries.c_str(), path.c_str()); } } // namespace swissknife <|endoftext|>
<commit_before>#ifndef DIPLOMA_PAGE_ALLOCATOR_HPP #define DIPLOMA_PAGE_ALLOCATOR_HPP #include <cstddef> #include <cstdint> #include <cassert> #include <libprecisegc/details/allocators/allocator_tag.hpp> #include <libprecisegc/details/gc_hooks.hpp> #include <libprecisegc/details/constants.hpp> #include <libprecisegc/details/types.hpp> #include <libprecisegc/details/logging.hpp> namespace precisegc { namespace details { namespace allocators { /** * page_allocator - allocates memory regions which size is multiple of PAGE_SIZE, aligned by its size */ class page_allocator { public: typedef byte* pointer_type; typedef stateless_alloc_tag alloc_tag; page_allocator() = default; page_allocator(const page_allocator&) = default; page_allocator(page_allocator&&) = default; byte* allocate(size_t size, size_t alignment = 0) { assert(size != 0 /*&& size % PAGE_SIZE == 0*/); gc_initiation_point(initiation_point_type::HEAP_EXPANSION, initiation_point_data::create_heap_expansion_data(size)); byte* page = reinterpret_cast<byte*>(aligned_alloc(alignment, size)); gc_register_page(page, size); return page; } void deallocate(byte* ptr, size_t size, size_t alignment = 0) { assert(size != 0 && size % PAGE_SIZE == 0); gc_deregister_page(ptr, size); free(ptr); } }; }}} #endif //DIPLOMA_PAGE_ALLOCATOR_HPP <commit_msg>zeroing allocated memory<commit_after>#ifndef DIPLOMA_PAGE_ALLOCATOR_HPP #define DIPLOMA_PAGE_ALLOCATOR_HPP #include <cstddef> #include <cstdint> #include <cassert> #include <libprecisegc/details/allocators/allocator_tag.hpp> #include <libprecisegc/details/gc_hooks.hpp> #include <libprecisegc/details/constants.hpp> #include <libprecisegc/details/types.hpp> #include <libprecisegc/details/logging.hpp> namespace precisegc { namespace details { namespace allocators { /** * page_allocator - allocates memory regions which size is multiple of PAGE_SIZE, aligned by its size */ class page_allocator { public: typedef byte* pointer_type; typedef stateless_alloc_tag alloc_tag; page_allocator() = default; page_allocator(const page_allocator&) = default; page_allocator(page_allocator&&) = default; byte* allocate(size_t size, size_t alignment = 0) { assert(size != 0 /*&& size % PAGE_SIZE == 0*/); gc_initiation_point(initiation_point_type::HEAP_EXPANSION, initiation_point_data::create_heap_expansion_data(size)); byte* page = reinterpret_cast<byte*>(aligned_alloc(alignment, size)); memset(page, 0, size); gc_register_page(page, size); return page; } void deallocate(byte* ptr, size_t size, size_t alignment = 0) { assert(size != 0 && size % PAGE_SIZE == 0); gc_deregister_page(ptr, size); free(ptr); } }; }}} #endif //DIPLOMA_PAGE_ALLOCATOR_HPP <|endoftext|>
<commit_before>// Copyright (C) 2016 xaizek <xaizek@openmailbox.org> // // This file is part of uncov. // // uncov 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. // // uncov 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 uncov. If not, see <http://www.gnu.org/licenses/>. #include "FileComparator.hpp" #include <boost/multi_array.hpp> #include <cstddef> #include <deque> #include <string> #include <vector> FileComparator::FileComparator(const std::vector<std::string> &o, const std::vector<int> &oCov, const std::vector<std::string> &n, const std::vector<int> &nCov, bool considerHits) { valid = (o.size() == oCov.size() && n.size() == nCov.size()); if (!valid) { equal = false; return; } boost::multi_array<int, 2> d(boost::extents[o.size() + 1U][n.size() + 1U]); // Modified edit distance finding. using size_type = std::vector<std::string>::size_type; for (size_type i = 0U, nf = o.size(); i <= nf; ++i) { for (size_type j = 0U, ns = n.size(); j <= ns; ++j) { if (i == 0U) { d[i][j] = j; } else if (j == 0U) { d[i][j] = i; } else { d[i][j] = std::min(d[i - 1U][j] + 1, d[i][j - 1U] + 1); if (o[i - 1U] == n[j - 1U]) { d[i][j] = std::min(d[i - 1U][j - 1U], d[i][j]); } } } } std::size_t identicalLines = 0; auto foldIdentical = [this, &identicalLines](bool last) { if (identicalLines > 4) { int startContext = last ? 0 : 1; int endContext = identicalLines == diffSequence.size() ? 0 : 1; int context = startContext + endContext; diffSequence.erase(diffSequence.cbegin() + startContext, diffSequence.cbegin() + (identicalLines - endContext)); diffSequence.emplace(diffSequence.cbegin() + startContext, DiffLineType::Note, std::to_string(identicalLines - context) + " identical lines folded", -1, -1); } identicalLines = 0; }; auto maybeConsiderIdentical = [&identicalLines, &foldIdentical](int hits) { if (hits == -1) { ++identicalLines; } else { foldIdentical(false); } }; auto sign = [](int i) { if (i < 0) { return -1; } else if (i == 0) { return 0; } else { return +1; } }; // Compose results with folding of long runs of identical lines (longer // than two lines). int i = o.size(), j = n.size(); while (i != 0 || j != 0) { if (i == 0) { maybeConsiderIdentical(nCov[--j]); diffSequence.emplace_front(DiffLineType::Added, n[j], -1, j); } else if (j == 0) { maybeConsiderIdentical(oCov[--i]); diffSequence.emplace_front(DiffLineType::Removed, o[i], i, -1); } else if (d[i][j] == d[i][j - 1] + 1) { maybeConsiderIdentical(nCov[--j]); diffSequence.emplace_front(DiffLineType::Added, n[j], -1, j); } else if (d[i][j] == d[i - 1][j] + 1) { maybeConsiderIdentical(oCov[--i]); diffSequence.emplace_front(DiffLineType::Removed, o[i], i, -1); } else if (o[--i] == n[--j]) { const int oHits = considerHits ? oCov[i] : sign(oCov[i]); const int nHits = considerHits ? nCov[j] : sign(nCov[j]); if (oHits == nHits) { diffSequence.emplace_front(DiffLineType::Identical, o[i], i, j); ++identicalLines; } else { foldIdentical(false); diffSequence.emplace_front(DiffLineType::Common, o[i], i, j); } } } equal = (identicalLines == diffSequence.size()); foldIdentical(true); } bool FileComparator::isValidInput() const { return valid; } bool FileComparator::areEqual() const { return equal; } const std::deque<DiffLine> & FileComparator::getDiffSequence() const { return diffSequence; } <commit_msg>Don't say that we fold "identical lines"<commit_after>// Copyright (C) 2016 xaizek <xaizek@openmailbox.org> // // This file is part of uncov. // // uncov 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. // // uncov 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 uncov. If not, see <http://www.gnu.org/licenses/>. #include "FileComparator.hpp" #include <boost/multi_array.hpp> #include <cstddef> #include <deque> #include <string> #include <vector> FileComparator::FileComparator(const std::vector<std::string> &o, const std::vector<int> &oCov, const std::vector<std::string> &n, const std::vector<int> &nCov, bool considerHits) { valid = (o.size() == oCov.size() && n.size() == nCov.size()); if (!valid) { equal = false; return; } boost::multi_array<int, 2> d(boost::extents[o.size() + 1U][n.size() + 1U]); // Modified edit distance finding. using size_type = std::vector<std::string>::size_type; for (size_type i = 0U, nf = o.size(); i <= nf; ++i) { for (size_type j = 0U, ns = n.size(); j <= ns; ++j) { if (i == 0U) { d[i][j] = j; } else if (j == 0U) { d[i][j] = i; } else { d[i][j] = std::min(d[i - 1U][j] + 1, d[i][j - 1U] + 1); if (o[i - 1U] == n[j - 1U]) { d[i][j] = std::min(d[i - 1U][j - 1U], d[i][j]); } } } } std::size_t identicalLines = 0; auto foldIdentical = [this, &identicalLines](bool last) { if (identicalLines > 4) { int startContext = last ? 0 : 1; int endContext = identicalLines == diffSequence.size() ? 0 : 1; int context = startContext + endContext; diffSequence.erase(diffSequence.cbegin() + startContext, diffSequence.cbegin() + (identicalLines - endContext)); diffSequence.emplace(diffSequence.cbegin() + startContext, DiffLineType::Note, std::to_string(identicalLines - context) + " lines folded", -1, -1); } identicalLines = 0; }; auto maybeConsiderIdentical = [&identicalLines, &foldIdentical](int hits) { if (hits == -1) { ++identicalLines; } else { foldIdentical(false); } }; auto sign = [](int i) { if (i < 0) { return -1; } else if (i == 0) { return 0; } else { return +1; } }; // Compose results with folding of long runs of identical lines (longer // than two lines). int i = o.size(), j = n.size(); while (i != 0 || j != 0) { if (i == 0) { maybeConsiderIdentical(nCov[--j]); diffSequence.emplace_front(DiffLineType::Added, n[j], -1, j); } else if (j == 0) { maybeConsiderIdentical(oCov[--i]); diffSequence.emplace_front(DiffLineType::Removed, o[i], i, -1); } else if (d[i][j] == d[i][j - 1] + 1) { maybeConsiderIdentical(nCov[--j]); diffSequence.emplace_front(DiffLineType::Added, n[j], -1, j); } else if (d[i][j] == d[i - 1][j] + 1) { maybeConsiderIdentical(oCov[--i]); diffSequence.emplace_front(DiffLineType::Removed, o[i], i, -1); } else if (o[--i] == n[--j]) { const int oHits = considerHits ? oCov[i] : sign(oCov[i]); const int nHits = considerHits ? nCov[j] : sign(nCov[j]); if (oHits == nHits) { diffSequence.emplace_front(DiffLineType::Identical, o[i], i, j); ++identicalLines; } else { foldIdentical(false); diffSequence.emplace_front(DiffLineType::Common, o[i], i, j); } } } equal = (identicalLines == diffSequence.size()); foldIdentical(true); } bool FileComparator::isValidInput() const { return valid; } bool FileComparator::areEqual() const { return equal; } const std::deque<DiffLine> & FileComparator::getDiffSequence() const { return diffSequence; } <|endoftext|>
<commit_before>// Copyright 2016 Alessio Sclocco <a.sclocco@vu.nl> // // 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 <vector> #include <iostream> #include <exception> #include <iomanip> #include <ctime> #include <algorithm> #include <configuration.hpp> #include <ArgumentList.hpp> #include <InitializeOpenCL.hpp> #include <Kernel.hpp> #include <Correlator.hpp> #include <utils.hpp> #include <Timer.hpp> #include <Stats.hpp> const unsigned int magicValue = 42; void initializeDeviceMemory(cl::Context & clContext, cl::CommandQueue * clQueue, std::vector< inputDataType > * input, cl::Buffer * input_d, const unsigned int outputSize, cl::Buffer * output_d, std::vector< unsigned int > * baselineMap, cl::Buffer * baselineMap_d); int main(int argc, char * argv[]) { bool reInit = true; unsigned int padding = 0; unsigned int nrIterations = 0; unsigned int clPlatformID = 0; unsigned int clDeviceID = 0; unsigned int vectorSize = 0; unsigned int maxThreads = 0; unsigned int maxItems = 0; unsigned int nrChannels = 0; unsigned int nrStations = 0; unsigned int nrSamples = 0; isa::OpenCL::KernelConf conf; try { isa::utils::ArgumentList args(argc, argv); clPlatformID = args.getSwitchArgument< unsigned int >("-opencl_platform"); clDeviceID = args.getSwitchArgument< unsigned int >("-opencl_device"); padding = args.getSwitchArgument< unsigned int >("-padding"); nrIterations = args.getSwitchArgument< unsigned int >("-iterations"); vectorSize = args.getSwitchArgument< unsigned int >("-vector"); maxThreads = args.getSwitchArgument< unsigned int >("-max_threads"); maxItems = args.getSwitchArgument< unsigned int >("-max_items"); nrChannels = args.getSwitchArgument< unsigned int >("-channels"); nrStations = args.getSwitchArgument< unsigned int >("-stations"); nrSamples = args.getSwitchArgument< unsigned int >("-samples"); } catch ( isa::utils::EmptyCommandLine & err ) { std::cerr << argv[0] << " -opencl_platform ... -opencl_device ... -padding ... -iterations ... -vector ... -max_threads ... -max_items ... -channels ... -stations ... -samples ..." << std::endl; return 1; } catch ( std::exception & err ) { std::cerr << err.what() << std::endl; return 1; } cl::Context clContext; std::vector< cl::Platform > * clPlatforms = new std::vector< cl::Platform >(); std::vector< cl::Device > * clDevices = new std::vector< cl::Device >(); std::vector< std::vector< cl::CommandQueue > > * clQueues = 0; // Allocate host memory unsigned int nrBaselines = (nrStations * (nrStations + 1)) / 2; std::vector< inputDataType > input(nrChannels * nrStations * nrSamples * nrPolarizations * 2); std::vector< inputDataType > output(nrChannels * nrBaselines * nrPolarizations * nrPolarizations * 2), output_c(nrChannels * nrBaselines * nrPolarizations * nrPolarizations * 2); std::vector< unsigned int > baselineMap(nrBaselines * 2); cl::Buffer input_d, output_d, baselineMap_d; // Populate data structures srand(time(0)); for ( unsigned int channel = 0; channel < nrChannels; channel++ ) { for ( unsigned int station = 0; station < nrStations; station++ ) { for ( unsigned int sample = 0; sample < nrSamples; sample++ ) { for ( unsigned int polarization = 0; polarization < nrPolarizations; polarization++ ) { input[(channel * nrStations * nrSamples * nrPolarizations * 2) + (station * nrSamples * nrPolarizations * 2) + (sample * nrPolarizations * 2) + (polarization * 2)] = rand() % magicValue; input[(channel * nrStations * nrSamples * nrPolarizations * 2) + (station * nrSamples * nrPolarizations * 2) + (sample * nrPolarizations * 2) + (polarization * 2) + 1] = rand() % magicValue; } } } } // Compute CPU control results std::fill(output.begin(), output.end(), 0); TuneBench::correlator(input, output_c, nrChannels, nrStations, nrSamples, nrPolarizations); TuneBench::generateBaselineMap(baselineMap, nrStations); std::cout << std::fixed << std::endl; std::cout << "# nrChannels nrStations nrSamples nrPolarizations nrThreadsD0 nrItemsD0 nrItemsD1 GFLOP/s time stdDeviation COV" << std::endl << std::endl; for ( unsigned int threads = vectorSize; threads <= maxThreads; threads += vectorSize ) { conf.setNrThreadsD0(threads); for ( unsigned int threads = 1; (conf.getNrThreadsD0() * threads) <= maxThreads; threads++ ) { conf.setNrThreadsD2(threads); if ( nrChannels % conf.getNrThreadsD2() != 0 ) { continue; } for ( unsigned int items = 1; items <= maxItems; items++ ) { conf.setNrItemsD0(items); if ( nrSamples % (conf.getNrThreadsD0() * conf.getNrItemsD0()) != 0 ) { continue; } for ( unsigned int items = 1; items * 18 <= maxItems; items++ ) { conf.setNrItemsD1(items); if ( nrStations % conf.getNrItemsD1() != 0 ) { continue; } // Generate kernel double gflops = isa::utils::giga(static_cast< uint64_t >(nrChannels) * nrSamples * nrBaselines * 32); cl::Event clEvent; cl::Kernel * kernel; isa::utils::Timer timer; std::string * code = TuneBench::getCorrelatorOpenCL(conf, inputDataName, padding, nrChannels, nrStations, nrSamples, nrPolarizations); if ( reInit ) { delete clQueues; clQueues = new std::vector< std::vector< cl::CommandQueue > >(); isa::OpenCL::initializeOpenCL(clPlatformID, 1, clPlatforms, &clContext, clDevices, clQueues); try { initializeDeviceMemory(clContext, &(clQueues->at(clDeviceID)[0]), &input, &input_d, nrChannels * nrBaselines * nrPolarizations * nrPolarizations * 2, &output_d, &baselineMap, &baselineMap_d); } catch ( cl::Error & err ) { return -1; } reInit = false; } try { kernel = isa::OpenCL::compile("correlator", *code, "-cl-mad-enable -Werror", clContext, clDevices->at(clDeviceID)); } catch ( isa::OpenCL::OpenCLError & err ) { std::cerr << err.what() << std::endl; delete code; break; } delete code; cl::NDRange global(nrSamples / conf.getNrItemsD0(), nrBaselines / conf.getNrItemsD1(), nrChannels); cl::NDRange local(conf.getNrThreadsD0(), 1, conf.getNrThreadsD2()); kernel->setArg(0, input_d); kernel->setArg(1, output_d); try { // Warm-up run clQueues->at(clDeviceID)[0].finish(); clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &clEvent); clEvent.wait(); // Tuning runs for ( unsigned int iteration = 0; iteration < nrIterations; iteration++ ) { timer.start(); clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &clEvent); clEvent.wait(); timer.stop(); } clQueues->at(clDeviceID)[0].enqueueReadBuffer(output_d, CL_TRUE, 0, output.size() * sizeof(inputDataType), reinterpret_cast< void * >(output.data()), 0, &clEvent); clEvent.wait(); } catch ( cl::Error & err ) { reInit = true; std::cerr << "OpenCL kernel execution error ("; std::cerr << conf.print(); std::cerr << "): "; std::cerr << std::to_string(err.err()) << std::endl; delete kernel; if ( err.err() == -4 || err.err() == -61 ) { return -1; } break; } delete kernel; bool error = false; for ( unsigned int item = 0; item < output_c.size(); item++ ) { if ( !isa::utils::same(output[item], output_c[item]) ) { std::cerr << "Output error (" << conf.print() << ")." << std::endl; error = true; break; } } if ( error ) { continue; } std::cout << nrChannels << " " << nrStations << " " << nrSamples << " " << nrPolarizations << " " ; std::cout << conf.print() << " "; std::cout << std::setprecision(3); std::cout << gflops / timer.getAverageTime() << " "; std::cout << std::setprecision(6); std::cout << timer.getAverageTime() << " " << timer.getStandardDeviation() << " " << timer.getCoefficientOfVariation() << std::endl; } } } } std::cout << std::endl; return 0; } void initializeDeviceMemory(cl::Context & clContext, cl::CommandQueue * clQueue, std::vector< inputDataType > * input, cl::Buffer * input_d, const unsigned int outputSize, cl::Buffer * output_d, std::vector< unsigned int > * baselineMap, cl::Buffer * baselineMap_d) { try { *input_d = cl::Buffer(clContext, CL_MEM_READ_ONLY, input->size() * sizeof(inputDataType), 0, 0); *output_d = cl::Buffer(clContext, CL_MEM_WRITE_ONLY, outputSize * sizeof(inputDataType), 0, 0); *baselineMap_d = cl::Buffer(clContext, CL_MEM_READ_ONLY, baselineMap->size() * sizeof(unsigned int), 0, 0); clQueue->enqueueWriteBuffer(*input_d, CL_FALSE, 0, input->size() * sizeof(inputDataType), reinterpret_cast< void * >(input->data())); clQueue->enqueueWriteBuffer(*baselineMap_d, CL_FALSE, 0, baselineMap->size() * sizeof(unsigned int), reinterpret_cast< void * >(baselineMap->data())); clQueue->finish(); } catch ( cl::Error & err ) { std::cerr << "OpenCL error (memory initialization): " << std::to_string(err.err()) << "." << std::endl; throw; } } <commit_msg>Forgot to set the last kernel's argument.<commit_after>// Copyright 2016 Alessio Sclocco <a.sclocco@vu.nl> // // 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 <vector> #include <iostream> #include <exception> #include <iomanip> #include <ctime> #include <algorithm> #include <configuration.hpp> #include <ArgumentList.hpp> #include <InitializeOpenCL.hpp> #include <Kernel.hpp> #include <Correlator.hpp> #include <utils.hpp> #include <Timer.hpp> #include <Stats.hpp> const unsigned int magicValue = 42; void initializeDeviceMemory(cl::Context & clContext, cl::CommandQueue * clQueue, std::vector< inputDataType > * input, cl::Buffer * input_d, const unsigned int outputSize, cl::Buffer * output_d, std::vector< unsigned int > * baselineMap, cl::Buffer * baselineMap_d); int main(int argc, char * argv[]) { bool reInit = true; unsigned int padding = 0; unsigned int nrIterations = 0; unsigned int clPlatformID = 0; unsigned int clDeviceID = 0; unsigned int vectorSize = 0; unsigned int maxThreads = 0; unsigned int maxItems = 0; unsigned int nrChannels = 0; unsigned int nrStations = 0; unsigned int nrSamples = 0; isa::OpenCL::KernelConf conf; try { isa::utils::ArgumentList args(argc, argv); clPlatformID = args.getSwitchArgument< unsigned int >("-opencl_platform"); clDeviceID = args.getSwitchArgument< unsigned int >("-opencl_device"); padding = args.getSwitchArgument< unsigned int >("-padding"); nrIterations = args.getSwitchArgument< unsigned int >("-iterations"); vectorSize = args.getSwitchArgument< unsigned int >("-vector"); maxThreads = args.getSwitchArgument< unsigned int >("-max_threads"); maxItems = args.getSwitchArgument< unsigned int >("-max_items"); nrChannels = args.getSwitchArgument< unsigned int >("-channels"); nrStations = args.getSwitchArgument< unsigned int >("-stations"); nrSamples = args.getSwitchArgument< unsigned int >("-samples"); } catch ( isa::utils::EmptyCommandLine & err ) { std::cerr << argv[0] << " -opencl_platform ... -opencl_device ... -padding ... -iterations ... -vector ... -max_threads ... -max_items ... -channels ... -stations ... -samples ..." << std::endl; return 1; } catch ( std::exception & err ) { std::cerr << err.what() << std::endl; return 1; } cl::Context clContext; std::vector< cl::Platform > * clPlatforms = new std::vector< cl::Platform >(); std::vector< cl::Device > * clDevices = new std::vector< cl::Device >(); std::vector< std::vector< cl::CommandQueue > > * clQueues = 0; // Allocate host memory unsigned int nrBaselines = (nrStations * (nrStations + 1)) / 2; std::vector< inputDataType > input(nrChannels * nrStations * nrSamples * nrPolarizations * 2); std::vector< inputDataType > output(nrChannels * nrBaselines * nrPolarizations * nrPolarizations * 2), output_c(nrChannels * nrBaselines * nrPolarizations * nrPolarizations * 2); std::vector< unsigned int > baselineMap(nrBaselines * 2); cl::Buffer input_d, output_d, baselineMap_d; // Populate data structures srand(time(0)); for ( unsigned int channel = 0; channel < nrChannels; channel++ ) { for ( unsigned int station = 0; station < nrStations; station++ ) { for ( unsigned int sample = 0; sample < nrSamples; sample++ ) { for ( unsigned int polarization = 0; polarization < nrPolarizations; polarization++ ) { input[(channel * nrStations * nrSamples * nrPolarizations * 2) + (station * nrSamples * nrPolarizations * 2) + (sample * nrPolarizations * 2) + (polarization * 2)] = rand() % magicValue; input[(channel * nrStations * nrSamples * nrPolarizations * 2) + (station * nrSamples * nrPolarizations * 2) + (sample * nrPolarizations * 2) + (polarization * 2) + 1] = rand() % magicValue; } } } } // Compute CPU control results std::fill(output.begin(), output.end(), 0); TuneBench::correlator(input, output_c, nrChannels, nrStations, nrSamples, nrPolarizations); TuneBench::generateBaselineMap(baselineMap, nrStations); std::cout << std::fixed << std::endl; std::cout << "# nrChannels nrStations nrSamples nrPolarizations nrThreadsD0 nrItemsD0 nrItemsD1 GFLOP/s time stdDeviation COV" << std::endl << std::endl; for ( unsigned int threads = vectorSize; threads <= maxThreads; threads += vectorSize ) { conf.setNrThreadsD0(threads); for ( unsigned int threads = 1; (conf.getNrThreadsD0() * threads) <= maxThreads; threads++ ) { conf.setNrThreadsD2(threads); if ( nrChannels % conf.getNrThreadsD2() != 0 ) { continue; } for ( unsigned int items = 1; items <= maxItems; items++ ) { conf.setNrItemsD0(items); if ( nrSamples % (conf.getNrThreadsD0() * conf.getNrItemsD0()) != 0 ) { continue; } for ( unsigned int items = 1; items * 18 <= maxItems; items++ ) { conf.setNrItemsD1(items); if ( nrStations % conf.getNrItemsD1() != 0 ) { continue; } // Generate kernel double gflops = isa::utils::giga(static_cast< uint64_t >(nrChannels) * nrSamples * nrBaselines * 32); cl::Event clEvent; cl::Kernel * kernel; isa::utils::Timer timer; std::string * code = TuneBench::getCorrelatorOpenCL(conf, inputDataName, padding, nrChannels, nrStations, nrSamples, nrPolarizations); if ( reInit ) { delete clQueues; clQueues = new std::vector< std::vector< cl::CommandQueue > >(); isa::OpenCL::initializeOpenCL(clPlatformID, 1, clPlatforms, &clContext, clDevices, clQueues); try { initializeDeviceMemory(clContext, &(clQueues->at(clDeviceID)[0]), &input, &input_d, nrChannels * nrBaselines * nrPolarizations * nrPolarizations * 2, &output_d, &baselineMap, &baselineMap_d); } catch ( cl::Error & err ) { return -1; } reInit = false; } try { kernel = isa::OpenCL::compile("correlator", *code, "-cl-mad-enable -Werror", clContext, clDevices->at(clDeviceID)); } catch ( isa::OpenCL::OpenCLError & err ) { std::cerr << err.what() << std::endl; delete code; break; } delete code; cl::NDRange global(nrSamples / conf.getNrItemsD0(), nrBaselines / conf.getNrItemsD1(), nrChannels); cl::NDRange local(conf.getNrThreadsD0(), 1, conf.getNrThreadsD2()); kernel->setArg(0, input_d); kernel->setArg(1, output_d); kernel->setArg(2, baselineMap_d); try { // Warm-up run clQueues->at(clDeviceID)[0].finish(); clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &clEvent); clEvent.wait(); // Tuning runs for ( unsigned int iteration = 0; iteration < nrIterations; iteration++ ) { timer.start(); clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &clEvent); clEvent.wait(); timer.stop(); } clQueues->at(clDeviceID)[0].enqueueReadBuffer(output_d, CL_TRUE, 0, output.size() * sizeof(inputDataType), reinterpret_cast< void * >(output.data()), 0, &clEvent); clEvent.wait(); } catch ( cl::Error & err ) { reInit = true; std::cerr << "OpenCL kernel execution error ("; std::cerr << conf.print(); std::cerr << "): "; std::cerr << std::to_string(err.err()) << std::endl; delete kernel; if ( err.err() == -4 || err.err() == -61 ) { return -1; } break; } delete kernel; bool error = false; for ( unsigned int item = 0; item < output_c.size(); item++ ) { if ( !isa::utils::same(output[item], output_c[item]) ) { std::cerr << "Output error (" << conf.print() << ")." << std::endl; error = true; break; } } if ( error ) { continue; } std::cout << nrChannels << " " << nrStations << " " << nrSamples << " " << nrPolarizations << " " ; std::cout << conf.print() << " "; std::cout << std::setprecision(3); std::cout << gflops / timer.getAverageTime() << " "; std::cout << std::setprecision(6); std::cout << timer.getAverageTime() << " " << timer.getStandardDeviation() << " " << timer.getCoefficientOfVariation() << std::endl; } } } } std::cout << std::endl; return 0; } void initializeDeviceMemory(cl::Context & clContext, cl::CommandQueue * clQueue, std::vector< inputDataType > * input, cl::Buffer * input_d, const unsigned int outputSize, cl::Buffer * output_d, std::vector< unsigned int > * baselineMap, cl::Buffer * baselineMap_d) { try { *input_d = cl::Buffer(clContext, CL_MEM_READ_ONLY, input->size() * sizeof(inputDataType), 0, 0); *output_d = cl::Buffer(clContext, CL_MEM_WRITE_ONLY, outputSize * sizeof(inputDataType), 0, 0); *baselineMap_d = cl::Buffer(clContext, CL_MEM_READ_ONLY, baselineMap->size() * sizeof(unsigned int), 0, 0); clQueue->enqueueWriteBuffer(*input_d, CL_FALSE, 0, input->size() * sizeof(inputDataType), reinterpret_cast< void * >(input->data())); clQueue->enqueueWriteBuffer(*baselineMap_d, CL_FALSE, 0, baselineMap->size() * sizeof(unsigned int), reinterpret_cast< void * >(baselineMap->data())); clQueue->finish(); } catch ( cl::Error & err ) { std::cerr << "OpenCL error (memory initialization): " << std::to_string(err.err()) << "." << std::endl; throw; } } <|endoftext|>
<commit_before>/* * Copyright (C) 2008-2011, Gostai S.A.S. * * This software is provided "as is" without warranty of any kind, * either expressed or implied, including but not limited to the * implied warranties of fitness for a particular purpose. * * See the LICENSE file for more information. */ /** ** \file libport/path.cc ** \brief Implement libport::path. */ #include <cctype> #include <iostream> #include <libport/cstdio> #include <libport/debug.hh> #include <libport/detect-win32.h> #include <libport/exception.hh> #include <libport/fcntl.h> #include <libport/format.hh> #include <libport/path.hh> #include <libport/sys/stat.h> #include <libport/sys/types.h> #include <libport/unistd.h> GD_CATEGORY(Libport.Path); // Implementation detail: if components() is empty and not absolute // then the path is '.'. namespace boostfs = boost::filesystem; namespace libport { path::path(const std::string& p) { init(p); } path::path(const char* p) { init(p); } path::path(const value_type& p) { init(p.file_string()); } void path::init(const std::string& p) { if (p.empty()) throw invalid_path("Path can't be empty."); #ifdef WIN32 // We want "/" to mean "the root of the current volume" on windows. if (p[0] == '/') value_ = boost::filesystem::current_path().root_name() + p; else #endif value_ = p; value_ = clean(); } path& path::operator=(const path& rhs) { value_ = rhs.value_; return *this; } path& path::operator/=(const path& rhs) { if (rhs.absolute_get()) throw invalid_path( "Rhs of concatenation is absolute: " + rhs.to_string()); #ifdef WIN32 if (!rhs.volume_get().empty()) throw invalid_path("concatenation of path with volume: " + rhs.to_string()); #endif value_ /= rhs.value_; value_ = clean(); return *this; } path path::operator/(const path& rhs) const { path res = *this; return res /= rhs; } std::string path::to_string() const { if (!value_.is_complete() && components().empty()) return WIN32_IF(volume_get().empty() ? "." : volume_get(), "."); return value_.file_string(); } bool path::operator==(const path& rhs) const { return (volume_get() == rhs.volume_get() && absolute_get() == rhs.absolute_get() && components() == rhs.components()); } std::ostream& path::dump(std::ostream& o) const { return o << operator std::string(); } bool path::is_dir() const { return boostfs::is_directory(to_string()); } bool path::is_reg() const { return boostfs::is_regular_file(to_string()); } std::string path::clean() const { std::string res; value_type::iterator i = value_.begin(); value_type::iterator i_end = value_.end(); if (i == i_end) return "."; bool first = true; if (absolute_get()) { res = *i; ++i; #ifdef WIN32 // Add a "\" after the drive letter or network share. first = false; #endif } for (;i != i_end; ++i) { // Remove the "." and empty components. if (!i->empty() && *i != ".") { if (!first) res += separator_; first = false; res += *i; } } return res.empty() ? "." : res; } std::string path::volume_get() const { #ifndef WIN32 return ""; #else std::string res = value_.root_name(); if (res.find("//") == 0) res.replace(0, 2, "\\\\"); return res; #endif } path path::dirname() const { // dirname of / is /, dirname of . is . if (components().empty()) return *this; std::string res = value_.parent_path().directory_string(); return path(res.empty() ? "." : res); } bool path::exists() const { bool res; try { res = boost::filesystem::exists(value_); } catch (...) { res = false; } GD_FINFO_DUMP("exists: %-5s: %s", res ? "true" : "false", to_string()); return res; } path path::cwd() { return path(boost::filesystem::current_path().string()); } bool path::is_root() const { return to_string() == (volume_get() + separator_); } path path::parent() const { if (is_root()) return path(volume_get().append(1, separator_)); const std::string parent_path = boost::filesystem::path(to_string()).parent_path().string(); if (parent_path.empty()) return cwd(); return parent_path; } std::time_t path::last_write_time() const { return boost::filesystem::last_write_time( boost::filesystem::path(to_string())); } bool path::create() const { int fd = open(to_string().c_str(), O_WRONLY | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR); if (fd == -1) return false; close(fd); return true; } path path::temporary_file() { #ifndef WIN32 char tmp_name[] = "/tmp/tmp.XXXXXX"; int fd = mkstemp(tmp_name); close (fd); #else char tmp_dir[MAX_PATH]; char tmp_name[MAX_PATH]; if(GetTempPathA(sizeof(tmp_dir), tmp_dir) == 0 || GetTempFileNameA(tmp_dir, "$$$", 0, tmp_name) == 0) throw Exception("cannot generate path for temporary file"); #endif return path(tmp_name); } void path::remove() const { if (!boost::filesystem::remove(value_)) throw Exception(libport::format("cannot unlink file %s", *this)); } void path::rename(const std::string& dst) { try { boost::filesystem::rename(value_, dst); } catch (Exception& e) { throw Exception(libport::format("cannot rename directory %s: %s", *this, format_boost_fs_error(e.what()))); } *this = dst; } path::path_type path::components() const { path_type path_; value_type::iterator i = value_.begin(), i_end = value_.end(); if (i == i_end) return path_; // Skip volume information. if (absolute_get()) { ++i; #ifdef WIN32 // Skip a / after the volume information. ++i; #endif } for (;i != i_end; ++i) if (!i->empty() && *i != ".") path_.push_back(*i); return path_; } std::string format_boost_fs_error(const char* what) { static const std::string ns = "boost::filesystem::"; // Get rid of function namespace. std::string error = std::string(what).substr(ns.size()); // Get rid of function name and ": ". error = error.substr(error.find(":") + 2); // Urbi errors begin with a lower case letter. error[0] = tolower(error[0]); return error; } } <commit_msg>libport: use boostfs instead of boost::filesytem.<commit_after>/* * Copyright (C) 2008-2011, Gostai S.A.S. * * This software is provided "as is" without warranty of any kind, * either expressed or implied, including but not limited to the * implied warranties of fitness for a particular purpose. * * See the LICENSE file for more information. */ /** ** \file libport/path.cc ** \brief Implement libport::path. */ #include <cctype> #include <iostream> #include <libport/cstdio> #include <libport/debug.hh> #include <libport/detect-win32.h> #include <libport/exception.hh> #include <libport/fcntl.h> #include <libport/format.hh> #include <libport/path.hh> #include <libport/sys/stat.h> #include <libport/sys/types.h> #include <libport/unistd.h> GD_CATEGORY(Libport.Path); // Implementation detail: if components() is empty and not absolute // then the path is '.'. namespace boostfs = boost::filesystem; namespace libport { path::path(const std::string& p) { init(p); } path::path(const char* p) { init(p); } path::path(const value_type& p) { init(p.file_string()); } void path::init(const std::string& p) { if (p.empty()) throw invalid_path("Path can't be empty."); #ifdef WIN32 // We want "/" to mean "the root of the current volume" on windows. if (p[0] == '/') value_ = boostfs::current_path().root_name() + p; else #endif value_ = p; value_ = clean(); } path& path::operator=(const path& rhs) { value_ = rhs.value_; return *this; } path& path::operator/=(const path& rhs) { if (rhs.absolute_get()) throw invalid_path( "Rhs of concatenation is absolute: " + rhs.to_string()); #ifdef WIN32 if (!rhs.volume_get().empty()) throw invalid_path("concatenation of path with volume: " + rhs.to_string()); #endif value_ /= rhs.value_; value_ = clean(); return *this; } path path::operator/(const path& rhs) const { path res = *this; return res /= rhs; } std::string path::to_string() const { if (!value_.is_complete() && components().empty()) return WIN32_IF(volume_get().empty() ? "." : volume_get(), "."); return value_.file_string(); } bool path::operator==(const path& rhs) const { return (volume_get() == rhs.volume_get() && absolute_get() == rhs.absolute_get() && components() == rhs.components()); } std::ostream& path::dump(std::ostream& o) const { return o << operator std::string(); } bool path::is_dir() const { return boostfs::is_directory(to_string()); } bool path::is_reg() const { return boostfs::is_regular_file(to_string()); } std::string path::clean() const { std::string res; value_type::iterator i = value_.begin(); value_type::iterator i_end = value_.end(); if (i == i_end) return "."; bool first = true; if (absolute_get()) { res = *i; ++i; #ifdef WIN32 // Add a "\" after the drive letter or network share. first = false; #endif } for (;i != i_end; ++i) { // Remove the "." and empty components. if (!i->empty() && *i != ".") { if (!first) res += separator_; first = false; res += *i; } } return res.empty() ? "." : res; } std::string path::volume_get() const { #ifndef WIN32 return ""; #else std::string res = value_.root_name(); if (res.find("//") == 0) res.replace(0, 2, "\\\\"); return res; #endif } path path::dirname() const { // dirname of / is /, dirname of . is . if (components().empty()) return *this; std::string res = value_.parent_path().directory_string(); return path(res.empty() ? "." : res); } bool path::exists() const { bool res; try { res = boostfs::exists(value_); } catch (...) { res = false; } GD_FINFO_DUMP("exists: %-5s: %s", res ? "true" : "false", to_string()); return res; } path path::cwd() { return path(boostfs::current_path().string()); } bool path::is_root() const { return to_string() == (volume_get() + separator_); } path path::parent() const { if (is_root()) return path(volume_get().append(1, separator_)); const std::string parent_path = boostfs::path(to_string()).parent_path().string(); if (parent_path.empty()) return cwd(); return parent_path; } std::time_t path::last_write_time() const { return boostfs::last_write_time( boostfs::path(to_string())); } bool path::create() const { int fd = open(to_string().c_str(), O_WRONLY | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR); if (fd == -1) return false; close(fd); return true; } path path::temporary_file() { #ifndef WIN32 char tmp_name[] = "/tmp/tmp.XXXXXX"; int fd = mkstemp(tmp_name); close (fd); #else char tmp_dir[MAX_PATH]; char tmp_name[MAX_PATH]; if(GetTempPathA(sizeof(tmp_dir), tmp_dir) == 0 || GetTempFileNameA(tmp_dir, "$$$", 0, tmp_name) == 0) throw Exception("cannot generate path for temporary file"); #endif return path(tmp_name); } void path::remove() const { if (!boostfs::remove(value_)) throw Exception(libport::format("cannot unlink file %s", *this)); } void path::rename(const std::string& dst) { try { boostfs::rename(value_, dst); } catch (Exception& e) { throw Exception(libport::format("cannot rename directory %s: %s", *this, format_boost_fs_error(e.what()))); } *this = dst; } path::path_type path::components() const { path_type path_; value_type::iterator i = value_.begin(), i_end = value_.end(); if (i == i_end) return path_; // Skip volume information. if (absolute_get()) { ++i; #ifdef WIN32 // Skip a / after the volume information. ++i; #endif } for (;i != i_end; ++i) if (!i->empty() && *i != ".") path_.push_back(*i); return path_; } std::string format_boost_fs_error(const char* what) { static const std::string ns = "boost::filesystem::"; // Get rid of function namespace. std::string error = std::string(what).substr(ns.size()); // Get rid of function name and ": ". error = error.substr(error.find(":") + 2); // Urbi errors begin with a lower case letter. error[0] = tolower(error[0]); return error; } } <|endoftext|>
<commit_before>/* GG is a GUI for SDL and OpenGL. Copyright (C) 2003 T. Zachary Laine 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 If you do not wish to comply with the terms of the LGPL please contact the author as other terms are available for a fee. Zach Laine whatwasthataddress@hotmail.com */ /* $Header$ */ #include "GGDropDownList.h" #include <GGScroll.h> #include <GGApp.h> #include <GGDrawUtil.h> #include <XMLValidators.h> using namespace GG; namespace { const int BORDER_THICK = 2; // should be the same as the BORDER_THICK value in GGListBox.h class ModalListPicker : public Wnd { public: ModalListPicker(DropDownList* drop_wnd, ListBox* lb_wnd) : Wnd(0, 0, GG::App::GetApp()->AppWidth() - 1, GG::App::GetApp()->AppHeight() - 1, CLICKABLE | MODAL), m_drop_wnd(drop_wnd), m_lb_wnd(lb_wnd), m_old_lb_ul(m_lb_wnd->UpperLeft()) { Connect(m_lb_wnd->SelChangedSignal(), &ModalListPicker::LBSelChangedSlot, this); Connect(m_lb_wnd->LeftClickedSignal(), &ModalListPicker::LBLeftClickSlot, this); m_lb_wnd->OffsetMove(m_drop_wnd->Parent() ? m_drop_wnd->Parent()->UpperLeft() : Pt()); AttachChild(m_lb_wnd); } ~ModalListPicker() {m_lb_wnd->MoveTo(m_old_lb_ul); DetachChild(m_lb_wnd);} protected: virtual void LClick(const Pt& pt, Uint32 keys) {m_done = true;} private: void LBSelChangedSlot(const set<int>& rows) { if (!rows.empty()) { m_drop_wnd->Select(*rows.begin()); m_done = true; } } void LBLeftClickSlot(int, const ListBox::Row*, const Pt&) { m_done = true; } DropDownList* m_drop_wnd; ListBox* m_lb_wnd; Pt m_old_lb_ul; }; } DropDownList::DropDownList(int x, int y, int w, int row_ht, int drop_ht, Clr color, ListBox* lb/* = 0*/, Uint32 flags/* = CLICKABLE*/) : Control(x, y, w, row_ht, flags), m_current_item_idx(-1), m_LB(lb) { if (!m_LB) m_LB = new ListBox(x, y, w, drop_ht, color, color, flags); m_LB->SetRowHeight(row_ht); SetStyle(LB_SINGLESEL); // adjust size to keep correct height based on row height, etc. Resize(Size().x, row_ht + 2 * m_LB->CellMargin() + 2 * BORDER_THICK); m_LB->MoveTo(x, y + Height()); } DropDownList::DropDownList(int x, int y, int w, int row_ht, int drop_ht, Clr color, Clr interior, ListBox* lb/* = 0*/, Uint32 flags/* = CLICKABLE*/) : Control(x, y, w, row_ht, flags), m_current_item_idx(-1), m_LB(lb) { if (!m_LB) m_LB = new ListBox(x, y, w, drop_ht, color, interior, flags); m_LB->SetRowHeight(row_ht); SetStyle(LB_SINGLESEL); // adjust size to keep correct height based on row height, etc. Resize(Size().x, row_ht + 2 * m_LB->CellMargin() + 2 * BORDER_THICK); m_LB->MoveTo(x, y + Height()); } DropDownList::DropDownList(const XMLElement& elem) : Control(elem.Child("GG::Control")) { if (elem.Tag() != "GG::DropDownList") throw std::invalid_argument("Attempted to construct a GG::DropDownList from an XMLElement that had a tag other than \"GG::DropDownList\""); m_current_item_idx = lexical_cast<int>(elem.Child("m_current_item_idx").Text()); if (ListBox* lb = dynamic_cast<ListBox*>(App::GetApp()->GenerateWnd(elem.Child("m_LB").Child(0)))) { m_LB = lb; } else { throw std::runtime_error("DropDownList::DropDownList : Attempted to use a non-ListBox object as the drop-down list."); } } DropDownList::~DropDownList() { delete m_LB; } const DropDownList::Row* DropDownList::CurrentItem() const { return m_current_item_idx == -1 ? 0 : &m_LB->GetRow(m_current_item_idx); } bool DropDownList::Render() { // draw beveled rectangle around client area Pt ul = UpperLeft(), lr = LowerRight(); Clr color_to_use = Disabled() ? DisabledColor(m_LB->Color()) : m_LB->Color(); Clr int_color_to_use = Disabled() ? DisabledColor(m_LB->m_int_color) : m_LB->m_int_color; BeveledRectangle(ul.x, ul.y, lr.x, lr.y, int_color_to_use, color_to_use, false, BORDER_THICK); // draw ListBox::Row of currently displayed item, if any const Row* current_item = CurrentItem(); if (current_item) { // clip row to viewable area, and save old scissor state glPushAttrib(GL_SCISSOR_BIT); glEnable(GL_SCISSOR_TEST); glScissor(ul.x + BORDER_THICK, App::GetApp()->AppHeight() - lr.y + BORDER_THICK, lr.x - ul.x - 2 * BORDER_THICK, lr.y - ul.y - 2 * BORDER_THICK); m_LB->RenderRow(current_item, ul.x + BORDER_THICK, ul.y + BORDER_THICK, m_LB->LastVisibleCol()); // restore previous scissor-clipping state glPopAttrib(); } return true; } void DropDownList::LClick(const Pt& pt, Uint32 keys) { if (!Disabled()) { ModalListPicker picker(this, m_LB); const set<int>& LB_sels = m_LB->Selections(); if (!LB_sels.empty()) { if (m_LB->m_vscroll) m_LB->m_vscroll->ScrollTo(*LB_sels.begin() * m_LB->RowHeight()); } m_LB->m_first_col_shown = 0; picker.Run(); } } void DropDownList::Keypress(Key key, Uint32 key_mods) { if (!Disabled()) { switch (key) { case GGK_UP: // arrow-up (not numpad arrow) if (1 <= m_current_item_idx) Select(std::max(0, m_current_item_idx - 1)); break; case GGK_DOWN: // arrow-down (not numpad arrow) if (m_current_item_idx < m_LB->NumRows()) Select(std::min(m_current_item_idx + 1, m_LB->NumRows() - 1)); break; case GGK_PAGEUP: // page up key (not numpad key) if (m_LB->NumRows()) Select(std::max(0, m_current_item_idx - 10)); break; case GGK_PAGEDOWN: // page down key (not numpad key) if (m_LB->NumRows()) Select(std::min(m_current_item_idx + 10, m_LB->NumRows() - 1)); break; case GGK_HOME: // home key (not numpad) if (m_LB->NumRows()) Select(0); break; case GGK_END: // end key (not numpad) if (m_LB->NumRows()) Select(m_LB->NumRows() - 1); break; default: // any other key gets passed along to the parent if (Parent()) Parent()->Keypress(key, key_mods); } } else { if (Parent()) Parent()->Keypress(key, key_mods); } } void DropDownList::SizeMove(int x1, int y1, int x2, int y2) { // adjust size to keep correct height based on row height, etc. Wnd::SizeMove(x1, y1, x2, y1 + m_LB->RowHeight() + 2 * m_LB->CellMargin() + 2 * BORDER_THICK); m_LB->Resize(Width(), m_LB->Height()); m_LB->MoveTo(x1, y1 + Height()); } int DropDownList::Insert(Row* row, int at/* = -1*/) { row->height = m_LB->RowHeight(); row->sub_rows.clear(); return m_LB->Insert(row, at); } void DropDownList::Delete(int idx) { if (idx == m_current_item_idx) m_current_item_idx = -1; else if (idx < m_current_item_idx) --m_current_item_idx; m_LB->Delete(idx); } void DropDownList::Clear() { m_current_item_idx = -1; m_LB->Clear(); } void DropDownList::Select(int row) { int old_m_current_item_idx = m_current_item_idx; if (row <= -1 || m_LB->NumRows() <= row) { m_current_item_idx = -1; m_LB->ClearSelection(); } else { m_current_item_idx = row; m_LB->SelectRow(m_current_item_idx); } if (m_current_item_idx != old_m_current_item_idx) m_sel_changed_sig(m_current_item_idx); } void DropDownList::SetStyle(Uint32 s) { s &= ~(LB_NOSEL | LB_QUICKSEL | LB_DRAGDROP | LB_USERDELETE | LB_BROWSEUPDATES); s |= LB_SINGLESEL; m_LB->SetStyle(s); m_current_item_idx = -1; } void DropDownList::SetSortCol(int n) { m_LB->SetSortCol(n); m_current_item_idx = -1; } XMLElement DropDownList::XMLEncode() const { XMLElement retval("GG::DropDownList"); retval.AppendChild(Control::XMLEncode()); retval.AppendChild(XMLElement("m_current_item_idx", lexical_cast<string>(m_current_item_idx))); retval.AppendChild(XMLElement("m_LB", m_LB->XMLEncode())); return retval; } XMLElementValidator DropDownList::XMLValidator() const { XMLElementValidator retval("GG::DropDownList"); retval.AppendChild(Control::XMLValidator()); retval.AppendChild(XMLElementValidator("m_current_item_idx", new Validator<int>())); retval.AppendChild(XMLElementValidator("m_LB", m_LB->XMLValidator())); return retval; } <commit_msg>Corrected the placement of the drop-list, so DropDownLists work equally well as stand-alone controls and in ListBox::Row cells.<commit_after>/* GG is a GUI for SDL and OpenGL. Copyright (C) 2003 T. Zachary Laine 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 If you do not wish to comply with the terms of the LGPL please contact the author as other terms are available for a fee. Zach Laine whatwasthataddress@hotmail.com */ /* $Header$ */ #include "GGDropDownList.h" #include <GGScroll.h> #include <GGApp.h> #include <GGDrawUtil.h> #include <XMLValidators.h> using namespace GG; namespace { const int BORDER_THICK = 2; // should be the same as the BORDER_THICK value in GGListBox.h class ModalListPicker : public Wnd { public: ModalListPicker(DropDownList* drop_wnd, ListBox* lb_wnd) : Wnd(0, 0, GG::App::GetApp()->AppWidth() - 1, GG::App::GetApp()->AppHeight() - 1, CLICKABLE | MODAL), m_drop_wnd(drop_wnd), m_lb_wnd(lb_wnd), m_old_lb_ul(m_lb_wnd->UpperLeft()) { Connect(m_lb_wnd->SelChangedSignal(), &ModalListPicker::LBSelChangedSlot, this); Connect(m_lb_wnd->LeftClickedSignal(), &ModalListPicker::LBLeftClickSlot, this); m_lb_wnd->OffsetMove(m_drop_wnd->ClientUpperLeft()); AttachChild(m_lb_wnd); } ~ModalListPicker() {m_lb_wnd->MoveTo(m_old_lb_ul); DetachChild(m_lb_wnd);} protected: virtual void LClick(const Pt& pt, Uint32 keys) {m_done = true;} private: void LBSelChangedSlot(const set<int>& rows) { if (!rows.empty()) { m_drop_wnd->Select(*rows.begin()); m_done = true; } } void LBLeftClickSlot(int, const ListBox::Row*, const Pt&) { m_done = true; } DropDownList* m_drop_wnd; ListBox* m_lb_wnd; Pt m_old_lb_ul; }; } DropDownList::DropDownList(int x, int y, int w, int row_ht, int drop_ht, Clr color, ListBox* lb/* = 0*/, Uint32 flags/* = CLICKABLE*/) : Control(x, y, w, row_ht, flags), m_current_item_idx(-1), m_LB(lb) { if (!m_LB) m_LB = new ListBox(x, y, w, drop_ht, color, color, flags); m_LB->SetRowHeight(row_ht); SetStyle(LB_SINGLESEL); // adjust size to keep correct height based on row height, etc. Resize(Size().x, row_ht + 2 * m_LB->CellMargin() + 2 * BORDER_THICK); m_LB->MoveTo(x, y + Height()); } DropDownList::DropDownList(int x, int y, int w, int row_ht, int drop_ht, Clr color, Clr interior, ListBox* lb/* = 0*/, Uint32 flags/* = CLICKABLE*/) : Control(x, y, w, row_ht, flags), m_current_item_idx(-1), m_LB(lb) { if (!m_LB) m_LB = new ListBox(x, y, w, drop_ht, color, interior, flags); m_LB->SetRowHeight(row_ht); SetStyle(LB_SINGLESEL); // adjust size to keep correct height based on row height, etc. Resize(Size().x, row_ht + 2 * m_LB->CellMargin() + 2 * BORDER_THICK); m_LB->MoveTo(x, y + Height()); } DropDownList::DropDownList(const XMLElement& elem) : Control(elem.Child("GG::Control")) { if (elem.Tag() != "GG::DropDownList") throw std::invalid_argument("Attempted to construct a GG::DropDownList from an XMLElement that had a tag other than \"GG::DropDownList\""); m_current_item_idx = lexical_cast<int>(elem.Child("m_current_item_idx").Text()); if (ListBox* lb = dynamic_cast<ListBox*>(App::GetApp()->GenerateWnd(elem.Child("m_LB").Child(0)))) { m_LB = lb; } else { throw std::runtime_error("DropDownList::DropDownList : Attempted to use a non-ListBox object as the drop-down list."); } } DropDownList::~DropDownList() { delete m_LB; } const DropDownList::Row* DropDownList::CurrentItem() const { return m_current_item_idx == -1 ? 0 : &m_LB->GetRow(m_current_item_idx); } bool DropDownList::Render() { // draw beveled rectangle around client area Pt ul = UpperLeft(), lr = LowerRight(); Clr color_to_use = Disabled() ? DisabledColor(m_LB->Color()) : m_LB->Color(); Clr int_color_to_use = Disabled() ? DisabledColor(m_LB->m_int_color) : m_LB->m_int_color; BeveledRectangle(ul.x, ul.y, lr.x, lr.y, int_color_to_use, color_to_use, false, BORDER_THICK); // draw ListBox::Row of currently displayed item, if any const Row* current_item = CurrentItem(); if (current_item) { // clip row to viewable area, and save old scissor state glPushAttrib(GL_SCISSOR_BIT); glEnable(GL_SCISSOR_TEST); glScissor(ul.x + BORDER_THICK, App::GetApp()->AppHeight() - lr.y + BORDER_THICK, lr.x - ul.x - 2 * BORDER_THICK, lr.y - ul.y - 2 * BORDER_THICK); m_LB->RenderRow(current_item, ul.x + BORDER_THICK, ul.y + BORDER_THICK, m_LB->LastVisibleCol()); // restore previous scissor-clipping state glPopAttrib(); } return true; } void DropDownList::LClick(const Pt& pt, Uint32 keys) { if (!Disabled()) { ModalListPicker picker(this, m_LB); const set<int>& LB_sels = m_LB->Selections(); if (!LB_sels.empty()) { if (m_LB->m_vscroll) m_LB->m_vscroll->ScrollTo(*LB_sels.begin() * m_LB->RowHeight()); } m_LB->m_first_col_shown = 0; picker.Run(); } } void DropDownList::Keypress(Key key, Uint32 key_mods) { if (!Disabled()) { switch (key) { case GGK_UP: // arrow-up (not numpad arrow) if (1 <= m_current_item_idx) Select(std::max(0, m_current_item_idx - 1)); break; case GGK_DOWN: // arrow-down (not numpad arrow) if (m_current_item_idx < m_LB->NumRows()) Select(std::min(m_current_item_idx + 1, m_LB->NumRows() - 1)); break; case GGK_PAGEUP: // page up key (not numpad key) if (m_LB->NumRows()) Select(std::max(0, m_current_item_idx - 10)); break; case GGK_PAGEDOWN: // page down key (not numpad key) if (m_LB->NumRows()) Select(std::min(m_current_item_idx + 10, m_LB->NumRows() - 1)); break; case GGK_HOME: // home key (not numpad) if (m_LB->NumRows()) Select(0); break; case GGK_END: // end key (not numpad) if (m_LB->NumRows()) Select(m_LB->NumRows() - 1); break; default: // any other key gets passed along to the parent if (Parent()) Parent()->Keypress(key, key_mods); } } else { if (Parent()) Parent()->Keypress(key, key_mods); } } void DropDownList::SizeMove(int x1, int y1, int x2, int y2) { // adjust size to keep correct height based on row height, etc. Wnd::SizeMove(x1, y1, x2, y1 + m_LB->RowHeight() + 2 * m_LB->CellMargin() + 2 * BORDER_THICK); m_LB->SizeMove(0, Height(), Width(), Height() + m_LB->Height()); } int DropDownList::Insert(Row* row, int at/* = -1*/) { row->height = m_LB->RowHeight(); row->sub_rows.clear(); return m_LB->Insert(row, at); } void DropDownList::Delete(int idx) { if (idx == m_current_item_idx) m_current_item_idx = -1; else if (idx < m_current_item_idx) --m_current_item_idx; m_LB->Delete(idx); } void DropDownList::Clear() { m_current_item_idx = -1; m_LB->Clear(); } void DropDownList::Select(int row) { int old_m_current_item_idx = m_current_item_idx; if (row <= -1 || m_LB->NumRows() <= row) { m_current_item_idx = -1; m_LB->ClearSelection(); } else { m_current_item_idx = row; m_LB->SelectRow(m_current_item_idx); } if (m_current_item_idx != old_m_current_item_idx) m_sel_changed_sig(m_current_item_idx); } void DropDownList::SetStyle(Uint32 s) { s &= ~(LB_NOSEL | LB_QUICKSEL | LB_DRAGDROP | LB_USERDELETE | LB_BROWSEUPDATES); s |= LB_SINGLESEL; m_LB->SetStyle(s); m_current_item_idx = -1; } void DropDownList::SetSortCol(int n) { m_LB->SetSortCol(n); m_current_item_idx = -1; } XMLElement DropDownList::XMLEncode() const { XMLElement retval("GG::DropDownList"); retval.AppendChild(Control::XMLEncode()); retval.AppendChild(XMLElement("m_current_item_idx", lexical_cast<string>(m_current_item_idx))); retval.AppendChild(XMLElement("m_LB", m_LB->XMLEncode())); return retval; } XMLElementValidator DropDownList::XMLValidator() const { XMLElementValidator retval("GG::DropDownList"); retval.AppendChild(Control::XMLValidator()); retval.AppendChild(XMLElementValidator("m_current_item_idx", new Validator<int>())); retval.AppendChild(XMLElementValidator("m_LB", m_LB->XMLValidator())); return retval; } <|endoftext|>
<commit_before>// @(#)root/qtgsi:$Id$ // Author: Denis Bertini, M. Al-Turany 01/11/2000 /************************************************************************* * Copyright (C) 1995-2006, 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 "Riostream.h" #include "qevent.h" #include "qdialog.h" #include "qpushbutton.h" #include "qlabel.h" #include "qpainter.h" #if (QT_VERSION > 0x039999) // Added by cholm@nbi.dk - for Qt 4 # include "qmenu.h" # include "q3popupmenu.h" typedef Q3PopupMenu QPopupMenu; #else # include "qpopupmenu.h" #endif #include "TQCanvasMenu.h" #include "TClass.h" #include "TROOT.h" #include "TMethod.h" #include "TMethodCall.h" #include "TMethodArg.h" #include "TCanvas.h" #include "TDataType.h" #include "TQRootDialog.h" ClassImp(TQCanvasMenu) //______________________________________________________________________________ TQCanvasMenu::TQCanvasMenu(QWidget* parent, TCanvas *canvas) { // ctor, create the popup menu fc = canvas; fPopup = new QPopupMenu; fCurrObj = 0; fParent = parent; fTabWin = 0; fDialog = 0; fMousePosX = fMousePosY = 0; } //______________________________________________________________________________ TQCanvasMenu::TQCanvasMenu(QWidget* parent, QWidget *tabWin, TCanvas *canvas) { // ctor, create the popup menu fc = canvas; fPopup = new QPopupMenu; fParent = parent; fTabWin = tabWin; fCurrObj = 0; fDialog = 0; fMousePosX = fMousePosY = 0; } //______________________________________________________________________________ TQCanvasMenu::~TQCanvasMenu() { // dtor if (fPopup) delete fPopup; } //______________________________________________________________________________ char *TQCanvasMenu::CreateDialogTitle( TObject *object, TMethod *method ) { // Create title for dialog box retrieving argument values. static char methodTitle[128]; if (object && method) snprintf(methodTitle, 127, "%s::%s", object->ClassName(), method->GetName()); else *methodTitle = 0; return methodTitle; } //______________________________________________________________________________ char *TQCanvasMenu::CreateArgumentTitle(TMethodArg *argument) { // Create string describing argument (for use in dialog box). static Char_t argTitle[128]; if (argument) { snprintf(argTitle, 127, "(%s) %s", argument->GetTitle(), argument->GetName()); const char *arg_def = argument->GetDefault(); if (arg_def && *arg_def) { strncat(argTitle, " [default: ", 127 - strlen(argTitle)); strncat(argTitle, arg_def, 127 - strlen(argTitle)); strncat(argTitle, "]", 127 - strlen(argTitle)); } } else *argTitle = 0; return argTitle; } //______________________________________________________________________________ void TQCanvasMenu::Popup(TObject *obj, double x, double y, QMouseEvent *e) { // Perform the corresponding selected TObject popup // in the position defined // by x, y coordinates (in user coordinate system). // @param obj (TObject*) // @param p (QPoint&) TClass *klass=obj->IsA(); Int_t curId=-1; fCurrObj=obj; fPopup->clear(); fMethods.Clear(); QString buffer=klass->GetName(); buffer+="::"; buffer+=obj->GetName(); fPopup->insertItem(buffer, this, SLOT( Execute(int) ), 0,curId); curId++; klass->GetMenuItems(&fMethods); fPopup->insertSeparator(); TIter iter(&fMethods); TMethod *method=0; while ( (method = dynamic_cast<TMethod*>(iter())) != 0) { buffer=method->GetName(); fPopup->insertItem(buffer, this, SLOT( Execute(int) ), 0,curId); curId++; } // hold the position where the mouse was clicked fMousePosX= x; fMousePosY= y; // let Qt decide how to draw the popup Menu otherwise we have a problem that // the visible rectangle can get outside the screen (M.T. 03.06.02) fPopup->popup(e->globalPos(), 0); } //______________________________________________________________________________ void TQCanvasMenu::Execute(int id) { // Slot defined to execute a method from a selected TObject // using TObject::Execute() function. QString text=""; TVirtualPad *psave = gROOT->GetSelectedPad(); TMethod *method=(TMethod *)fMethods.At(id); fc->HandleInput(kButton3Up,gPad->XtoAbsPixel(fMousePosX), gPad->YtoAbsPixel(fMousePosY) ); if ( method->GetListOfMethodArgs()->First() ) { Dialog(fCurrObj,method); } else { gROOT->SetFromPopUp(kTRUE); fCurrObj->Execute((char *) method->GetName(), ""); } fc->GetPadSave()->Update(); fc->GetPadSave()->Modified(); gROOT->SetSelectedPad(psave); gROOT->GetSelectedPad()->Update(); gROOT->GetSelectedPad()->Modified(); fc->Modified(); fc->ForceUpdate(); gROOT->SetFromPopUp( kFALSE ); } //______________________________________________________________________________ void TQCanvasMenu::Dialog(TObject* object, TMethod* method) { // Create dialog object with OK and Cancel buttons. This dialog // prompts for the arguments of "method". if (!(object && method)) return; fDialog = new TQRootDialog(fParent,CreateDialogTitle(object, method),0,object ,method); fDialog->SetTCanvas(fc); // iterate through all arguments and create apropriate input-data objects: // inputlines, option menus... TMethodArg *argument = 0; TIter next(method->GetListOfMethodArgs()); while ((argument = (TMethodArg *) next())) { char *argname = CreateArgumentTitle(argument); const char *type = argument->GetTypeName(); TDataType *datatype = gROOT->GetType(type); const char *charstar = "char*"; char basictype [32]; if (datatype) { strlcpy(basictype, datatype->GetTypeName(),32); } else { if (strncmp(type, "enum", 4) != 0) cout << "*** Warning in Dialog(): data type is not basic type, assuming (int)\n"; strcpy(basictype, "int"); } if (strchr(argname, '*')) { strcat(basictype, "*"); type = charstar; } TDataMember *m = argument->GetDataMember(); if (m && m->GetterMethod()) { char gettername[256] = ""; strlcpy(gettername, m->GetterMethod()->GetMethodName(),256); m->GetterMethod()->Init(object->IsA(), gettername, ""); // Get the current value and form it as a text: char val[256]; if (!strncmp(basictype, "char*", 5)) { char *tdefval; m->GetterMethod()->Execute(object, "", &tdefval); strlcpy(val, tdefval, 256); } else if (!strncmp(basictype, "float", 5) || !strncmp(basictype, "double", 6)) { Double_t ddefval = 0.0; m->GetterMethod()->Execute(object, "", ddefval); snprintf(val, 255, "%g", ddefval); } else if (!strncmp(basictype, "char", 4) || !strncmp(basictype, "int", 3) || !strncmp(basictype, "long", 4) || !strncmp(basictype, "short", 5)) { Long_t ldefval = 0L; m->GetterMethod()->Execute(object, "", ldefval); snprintf(val, 255, "%li", ldefval); } // Find out whether we have options ... TList *opt; if ((opt = m->GetOptions())) { cout << "*** Warning in Dialog(): option menu not yet implemented " << opt << endl; // should stop dialog return; } else { // we haven't got options - textfield ... fDialog->Add(argname, val, type); } } else { // if m not found ... char val[256] = ""; const char *tval = argument->GetDefault(); if (tval) strlcpy(val, tval, 256); fDialog->Add(argname, val, type); } } //end while fDialog->Popup(); } <commit_msg>Fix coverity #36613 Uninitialized pointer read<commit_after>// @(#)root/qtgsi:$Id$ // Author: Denis Bertini, M. Al-Turany 01/11/2000 /************************************************************************* * Copyright (C) 1995-2006, 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 "Riostream.h" #include "qevent.h" #include "qdialog.h" #include "qpushbutton.h" #include "qlabel.h" #include "qpainter.h" #if (QT_VERSION > 0x039999) // Added by cholm@nbi.dk - for Qt 4 # include "qmenu.h" # include "q3popupmenu.h" typedef Q3PopupMenu QPopupMenu; #else # include "qpopupmenu.h" #endif #include "TQCanvasMenu.h" #include "TClass.h" #include "TROOT.h" #include "TMethod.h" #include "TMethodCall.h" #include "TMethodArg.h" #include "TCanvas.h" #include "TDataType.h" #include "TQRootDialog.h" ClassImp(TQCanvasMenu) //______________________________________________________________________________ TQCanvasMenu::TQCanvasMenu(QWidget* parent, TCanvas *canvas) { // ctor, create the popup menu fc = canvas; fPopup = new QPopupMenu; fCurrObj = 0; fParent = parent; fTabWin = 0; fDialog = 0; fMousePosX = fMousePosY = 0; } //______________________________________________________________________________ TQCanvasMenu::TQCanvasMenu(QWidget* parent, QWidget *tabWin, TCanvas *canvas) { // ctor, create the popup menu fc = canvas; fPopup = new QPopupMenu; fParent = parent; fTabWin = tabWin; fCurrObj = 0; fDialog = 0; fMousePosX = fMousePosY = 0; } //______________________________________________________________________________ TQCanvasMenu::~TQCanvasMenu() { // dtor if (fPopup) delete fPopup; } //______________________________________________________________________________ char *TQCanvasMenu::CreateDialogTitle( TObject *object, TMethod *method ) { // Create title for dialog box retrieving argument values. static char methodTitle[128]; if (object && method) snprintf(methodTitle, 127, "%s::%s", object->ClassName(), method->GetName()); else *methodTitle = 0; return methodTitle; } //______________________________________________________________________________ char *TQCanvasMenu::CreateArgumentTitle(TMethodArg *argument) { // Create string describing argument (for use in dialog box). static Char_t argTitle[128]; if (argument) { snprintf(argTitle, 127, "(%s) %s", argument->GetTitle(), argument->GetName()); const char *arg_def = argument->GetDefault(); if (arg_def && *arg_def) { strncat(argTitle, " [default: ", 127 - strlen(argTitle)); strncat(argTitle, arg_def, 127 - strlen(argTitle)); strncat(argTitle, "]", 127 - strlen(argTitle)); } } else *argTitle = 0; return argTitle; } //______________________________________________________________________________ void TQCanvasMenu::Popup(TObject *obj, double x, double y, QMouseEvent *e) { // Perform the corresponding selected TObject popup // in the position defined // by x, y coordinates (in user coordinate system). // @param obj (TObject*) // @param p (QPoint&) TClass *klass=obj->IsA(); Int_t curId=-1; fCurrObj=obj; fPopup->clear(); fMethods.Clear(); QString buffer=klass->GetName(); buffer+="::"; buffer+=obj->GetName(); fPopup->insertItem(buffer, this, SLOT( Execute(int) ), 0,curId); curId++; klass->GetMenuItems(&fMethods); fPopup->insertSeparator(); TIter iter(&fMethods); TMethod *method=0; while ( (method = dynamic_cast<TMethod*>(iter())) != 0) { buffer=method->GetName(); fPopup->insertItem(buffer, this, SLOT( Execute(int) ), 0,curId); curId++; } // hold the position where the mouse was clicked fMousePosX= x; fMousePosY= y; // let Qt decide how to draw the popup Menu otherwise we have a problem that // the visible rectangle can get outside the screen (M.T. 03.06.02) fPopup->popup(e->globalPos(), 0); } //______________________________________________________________________________ void TQCanvasMenu::Execute(int id) { // Slot defined to execute a method from a selected TObject // using TObject::Execute() function. QString text=""; TVirtualPad *psave = gROOT->GetSelectedPad(); TMethod *method=(TMethod *)fMethods.At(id); fc->HandleInput(kButton3Up,gPad->XtoAbsPixel(fMousePosX), gPad->YtoAbsPixel(fMousePosY) ); if ( method->GetListOfMethodArgs()->First() ) { Dialog(fCurrObj,method); } else { gROOT->SetFromPopUp(kTRUE); fCurrObj->Execute((char *) method->GetName(), ""); } fc->GetPadSave()->Update(); fc->GetPadSave()->Modified(); gROOT->SetSelectedPad(psave); gROOT->GetSelectedPad()->Update(); gROOT->GetSelectedPad()->Modified(); fc->Modified(); fc->ForceUpdate(); gROOT->SetFromPopUp( kFALSE ); } //______________________________________________________________________________ void TQCanvasMenu::Dialog(TObject* object, TMethod* method) { // Create dialog object with OK and Cancel buttons. This dialog // prompts for the arguments of "method". if (!(object && method)) return; fDialog = new TQRootDialog(fParent,CreateDialogTitle(object, method),0,object ,method); fDialog->SetTCanvas(fc); // iterate through all arguments and create apropriate input-data objects: // inputlines, option menus... TMethodArg *argument = 0; TIter next(method->GetListOfMethodArgs()); while ((argument = (TMethodArg *) next())) { char *argname = CreateArgumentTitle(argument); const char *type = argument->GetTypeName(); TDataType *datatype = gROOT->GetType(type); const char *charstar = "char*"; char basictype [32]; if (datatype) { strlcpy(basictype, datatype->GetTypeName(),32); } else { if (strncmp(type, "enum", 4) != 0) cout << "*** Warning in Dialog(): data type is not basic type, assuming (int)\n"; strcpy(basictype, "int"); } if (strchr(argname, '*')) { strcat(basictype, "*"); type = charstar; } TDataMember *m = argument->GetDataMember(); if (m && m->GetterMethod()) { char gettername[256] = ""; strlcpy(gettername, m->GetterMethod()->GetMethodName(),256); m->GetterMethod()->Init(object->IsA(), gettername, ""); // Get the current value and form it as a text: char val[256]; if (!strncmp(basictype, "char*", 5)) { char *tdefval = 0; m->GetterMethod()->Execute(object, "", &tdefval); if (tdefval && strlen(tdefval)) strlcpy(val, tdefval, 256); } else if (!strncmp(basictype, "float", 5) || !strncmp(basictype, "double", 6)) { Double_t ddefval = 0.0; m->GetterMethod()->Execute(object, "", ddefval); snprintf(val, 255, "%g", ddefval); } else if (!strncmp(basictype, "char", 4) || !strncmp(basictype, "int", 3) || !strncmp(basictype, "long", 4) || !strncmp(basictype, "short", 5)) { Long_t ldefval = 0L; m->GetterMethod()->Execute(object, "", ldefval); snprintf(val, 255, "%li", ldefval); } // Find out whether we have options ... TList *opt; if ((opt = m->GetOptions())) { cout << "*** Warning in Dialog(): option menu not yet implemented " << opt << endl; // should stop dialog return; } else { // we haven't got options - textfield ... fDialog->Add(argname, val, type); } } else { // if m not found ... char val[256] = ""; const char *tval = argument->GetDefault(); if (tval) strlcpy(val, tval, 256); fDialog->Add(argname, val, type); } } //end while fDialog->Popup(); } <|endoftext|>
<commit_before>#include "gorgone.h" using namespace cv; using namespace ofxCv; int accum = 0; void gorgone::setup() { ofSetLogLevel(OF_LOG_NOTICE); masterIp = "Mac-Pro-de-10-52.local"; appName = "gorgone-1"; parseCmdLineOptions(); vidGrabber.setup(filename); svgInterp.setup(); jamoma.setup((void*) this, appName, masterIp); motionDetector.setup(&jamoma); irisDetector.setJamomaRef(&jamoma); counter = 0; } void gorgone::exit(){ setPwm(0); #ifdef TARGET_RASPBERRY_PI vidGrabber.led.switchOffIR(); #endif } void gorgone::update() { ofLogVerbose("gorgone") << ofGetFrameRate() << " fps" << endl; vidGrabber.update(); if ( vidGrabber.isFrameNew() ){ frame = vidGrabber.getFrame(); if ( bMotion ){ motionDetector.update(frame); } if( bTracking ){ if ( frame.cols == 0 ) return; cv::Mat gray; if ( frame.channels() == 1 ){ gray = frame.clone(); } else { cv::cvtColor(frame, gray, CV_RGB2GRAY); } ofLogVerbose("gorgone") << "new frame to process : " << gray.cols << "x" << gray.rows << endl; irisDetector.updateBool(gray); } } if (bComputeCode) { irisDetector.computeCode(); bComputeCode=false; jamoma.mComputeIrisCodeParameter.set("value", bComputeCode); /* // desactivated because Max doesn't handle list longer than 256 item, yes this still happens in 2015... TTValue v; Mat code = irisDetector.getIrisCode(); v.push_back(code.cols); v.push_back(code.rows); uchar* p; for (int i = 0; i < code.rows; i++ ){ p=code.ptr<uchar>(i); for (int j = 0; j < code.cols; j++ ){ v.push_back((int) p[j]); } } cout << "v size : " << v.size() << endl; jamoma.mTrackingIrisCodeReturn.set("value",v); */ } Mat img = irisDetector.getIrisCode(); if( bDisplaying && irisDetector.newCode && img.total() > 0 ) { if ( irisDetector.newCode ){ svgInterp.coeff.clear(); ofLogVerbose("gorgone") << "code image resolution : " << img.cols << "x" << img.rows << endl; uchar* p; for (int i = 0; i < img.rows; i++ ){ float avg=0; p=img.ptr<uchar>(i); for (int j = 0; j < img.cols; j++ ){ avg+=p[j] / 255.; } avg/=img.cols; svgInterp.coeff.push_back(avg); } irisDetector.newCode = false; TTValue v; for (int i = 0; i<svgInterp.coeff.size(); i++){ v.push_back(svgInterp.coeff[i]); } jamoma.mTrackingIrisCodeReturn.set("value", v); } } } void gorgone::draw() { //vidGrabber.draw(0,0); drawMat(frame,0,0); if ( svgInterp.updateBool() ){ TTValue x,y; ofPolyline line = svgInterp.interpolatedLine; ofLogNotice("gorgone") << "update drawing with " << line.size() << "points" << endl; for (int i=0; i<line.size(); i++){ x.push_back(line[i].x); y.push_back(line[i].y); } jamoma.mDrawingShapeXReturn.set("value", x); jamoma.mDrawingShapeYReturn.set("value", y); } if ( bTracking ) irisDetector.drawEyes(); if ( bDisplaying ) svgInterp.draw(); } void gorgone::keyPressed(int key) { ofLogVerbose("gorgone") << "keypressed : " << key << endl; switch (key){ case 's': irisDetector.save(); break; case ' ': irisDetector.reset(); break; case 'c': bComputeCode=true; break; case 'm': bMotion = !bMotion; break; case 't': bTracking = !bTracking; if ( bTracking ) irisDetector.reset(); #ifdef TARGET_RASPBERRY_PI if ( bTracking ) vidGrabber.led.switchOnIR(); else vidGrabber.led.switchOffIR(); #endif break; case 'd': bDisplaying = !bDisplaying; break; #ifdef TARGET_RASPBERRY_PI case 'i': vidGrabber.led.switchOnIR(); break; case 'o': vidGrabber.led.switchOffIR(); break; case 'w': vidGrabber.led.switchOnWhite(); break; case 'x': vidGrabber.led.switchOffWhite(); break; #endif case 357 : // arrow up svgInterp.selectedId = counter++; break; case 359: // arrow down svgInterp.selectedId = counter--; break; default : break; } } void gorgone::messageReceived(ofMessage& message) { } void gorgone::parseCmdLineOptions(){ vector<string> keys = ofxArgParser::allKeys(); for (int i = 0; i < keys.size(); i++) { if ( keys[i] == "f" ) filename = ofxArgParser::getValue(keys[i]); else if ( keys[i] == "name" ) appName = ofxArgParser::getValue(keys[i]); else if ( keys[i] == "masterIp" ) masterIp = ofxArgParser::getValue(keys[i]); else if ( keys[i] == "verbose" ) { // vebose level, value : 0..5, default 1 (OF_LOG_NOTICE) int logLevel; istringstream( ofxArgParser::getValue(keys[i]) ) >> logLevel; ofSetLogLevel((ofLogLevel) logLevel); } ofLogNotice("gorgone") << "key: " << keys[i] << ", value: " << ofxArgParser::getValue(keys[i]) << endl; } } void gorgone::setPwm(float pc){ #ifdef TARGET_RASPBERRY_PI ofstream file; file.open("/dev/servoblaster", ios::in); file << "0=" << pc << "%" << endl; file.close(); #endif } <commit_msg>print enabled step on screen<commit_after>#include "gorgone.h" using namespace cv; using namespace ofxCv; int accum = 0; void gorgone::setup() { ofSetLogLevel(OF_LOG_NOTICE); masterIp = "Mac-Pro-de-10-52.local"; appName = "gorgone-1"; parseCmdLineOptions(); vidGrabber.setup(filename); svgInterp.setup(); jamoma.setup((void*) this, appName, masterIp); motionDetector.setup(&jamoma); irisDetector.setJamomaRef(&jamoma); counter = 0; } void gorgone::exit(){ setPwm(0); #ifdef TARGET_RASPBERRY_PI vidGrabber.led.switchOffIR(); #endif } void gorgone::update() { ofLogVerbose("gorgone") << ofGetFrameRate() << " fps" << endl; vidGrabber.update(); if ( vidGrabber.isFrameNew() ){ frame = vidGrabber.getFrame(); if ( bMotion ){ motionDetector.update(frame); } if( bTracking ){ if ( frame.cols == 0 ) return; cv::Mat gray; if ( frame.channels() == 1 ){ gray = frame.clone(); } else { cv::cvtColor(frame, gray, CV_RGB2GRAY); } ofLogVerbose("gorgone") << "new frame to process : " << gray.cols << "x" << gray.rows << endl; irisDetector.updateBool(gray); } } if (bComputeCode) { irisDetector.computeCode(); bComputeCode=false; jamoma.mComputeIrisCodeParameter.set("value", bComputeCode); /* // desactivated because Max doesn't handle list longer than 256 item, yes this still happens in 2015... TTValue v; Mat code = irisDetector.getIrisCode(); v.push_back(code.cols); v.push_back(code.rows); uchar* p; for (int i = 0; i < code.rows; i++ ){ p=code.ptr<uchar>(i); for (int j = 0; j < code.cols; j++ ){ v.push_back((int) p[j]); } } cout << "v size : " << v.size() << endl; jamoma.mTrackingIrisCodeReturn.set("value",v); */ } Mat img = irisDetector.getIrisCode(); if( bDisplaying && irisDetector.newCode && img.total() > 0 ) { if ( irisDetector.newCode ){ svgInterp.coeff.clear(); ofLogVerbose("gorgone") << "code image resolution : " << img.cols << "x" << img.rows << endl; uchar* p; for (int i = 0; i < img.rows; i++ ){ float avg=0; p=img.ptr<uchar>(i); for (int j = 0; j < img.cols; j++ ){ avg+=p[j] / 255.; } avg/=img.cols; svgInterp.coeff.push_back(avg); } irisDetector.newCode = false; TTValue v; for (int i = 0; i<svgInterp.coeff.size(); i++){ v.push_back(svgInterp.coeff[i]); } jamoma.mTrackingIrisCodeReturn.set("value", v); } } } void gorgone::draw() { //vidGrabber.draw(0,0); drawMat(frame,0,0); if ( svgInterp.updateBool() ){ TTValue x,y; ofPolyline line = svgInterp.interpolatedLine; ofLogNotice("gorgone") << "update drawing with " << line.size() << "points" << endl; for (int i=0; i<line.size(); i++){ x.push_back(line[i].x); y.push_back(line[i].y); } jamoma.mDrawingShapeXReturn.set("value", x); jamoma.mDrawingShapeYReturn.set("value", y); } if ( bTracking ) { ofDrawBitmapStringHighlight("eye tracking", 10, 400); irisDetector.drawEyes(); } if ( bDisplaying ) { ofDrawBitmapStringHighlight("laser drawing", 200, 400); svgInterp.draw(); } if ( bMotion ){ ofDrawBitmapStringHighlight("motion detection", 400, 400); } } void gorgone::keyPressed(int key) { ofLogVerbose("gorgone") << "keypressed : " << key << endl; switch (key){ case 's': irisDetector.save(); break; case ' ': irisDetector.reset(); break; case 'c': bComputeCode=true; break; case 'm': bMotion = !bMotion; break; case 't': bTracking = !bTracking; if ( bTracking ) irisDetector.reset(); #ifdef TARGET_RASPBERRY_PI if ( bTracking ) vidGrabber.led.switchOnIR(); else vidGrabber.led.switchOffIR(); #endif break; case 'd': bDisplaying = !bDisplaying; break; #ifdef TARGET_RASPBERRY_PI case 'i': vidGrabber.led.switchOnIR(); break; case 'o': vidGrabber.led.switchOffIR(); break; case 'w': vidGrabber.led.switchOnWhite(); break; case 'x': vidGrabber.led.switchOffWhite(); break; #endif case 357 : // arrow up svgInterp.selectedId = counter++; break; case 359: // arrow down svgInterp.selectedId = counter--; break; default : break; } } void gorgone::messageReceived(ofMessage& message) { } void gorgone::parseCmdLineOptions(){ vector<string> keys = ofxArgParser::allKeys(); for (int i = 0; i < keys.size(); i++) { if ( keys[i] == "f" ) filename = ofxArgParser::getValue(keys[i]); else if ( keys[i] == "name" ) appName = ofxArgParser::getValue(keys[i]); else if ( keys[i] == "masterIp" ) masterIp = ofxArgParser::getValue(keys[i]); else if ( keys[i] == "verbose" ) { // vebose level, value : 0..5, default 1 (OF_LOG_NOTICE) int logLevel; istringstream( ofxArgParser::getValue(keys[i]) ) >> logLevel; ofSetLogLevel((ofLogLevel) logLevel); } ofLogNotice("gorgone") << "key: " << keys[i] << ", value: " << ofxArgParser::getValue(keys[i]) << endl; } } void gorgone::setPwm(float pc){ #ifdef TARGET_RASPBERRY_PI ofstream file; file.open("/dev/servoblaster", ios::in); file << "0=" << pc << "%" << endl; file.close(); #endif } <|endoftext|>
<commit_before>// // Aspia Project // Copyright (C) 2018 Dmitry Chapyshev <dmitry@aspia.ru> // // 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 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 General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. // #include "net/network_channel_client.h" #include "base/cpuid.h" #include "base/logging.h" #include "build/build_config.h" #include "build/version.h" #include "crypto/cryptor_aes256_gcm.h" #include "crypto/cryptor_chacha20_poly1305.h" #include "crypto/secure_memory.h" #include "net/srp_client_context.h" #include <QNetworkProxy> #if defined(OS_WIN) #include <winsock2.h> #include <mstcpip.h> #endif // defined(OS_WIN) namespace net { namespace { QByteArray serializeMessage(const google::protobuf::MessageLite& message) { size_t size = message.ByteSizeLong(); if (!size) { LOG(LS_WARNING) << "Empty messages are not allowed"; return QByteArray(); } QByteArray buffer; buffer.resize(size); message.SerializeWithCachedSizesToArray(reinterpret_cast<uint8_t*>(buffer.data())); return buffer; } } // namespace ChannelClient::ChannelClient(QObject* parent) : Channel(ChannelType::CLIENT, new QTcpSocket(), parent) { // We must enable this option before the connection is established. socket_->setSocketOption(QTcpSocket::KeepAliveOption, 1); connect(socket_, &QTcpSocket::connected, this, &ChannelClient::onConnected); } ChannelClient::~ChannelClient() { crypto::memZero(&password_); } void ChannelClient::connectToHost(const QString& address, int port, const QString& username, const QString& password, proto::SessionType session_type) { username_ = username; password_ = password; session_type_ = session_type; socket_->setProxy(QNetworkProxy::NoProxy); socket_->connectToHost(address, port); } void ChannelClient::internalMessageReceived(const QByteArray& buffer) { switch (key_exchange_state_) { case KeyExchangeState::HELLO: readServerHello(buffer); break; case KeyExchangeState::KEY_EXCHANGE: readServerKeyExchange(buffer); break; case KeyExchangeState::SESSION: readSessionChallenge(buffer); break; default: break; } } void ChannelClient::internalMessageWritten() { switch (key_exchange_state_) { case KeyExchangeState::DONE: { channel_state_ = ChannelState::ENCRYPTED; srp_client_.reset(); emit connected(); } break; default: break; } } void ChannelClient::onConnected() { channel_state_ = ChannelState::CONNECTED; // Disable the Nagle algorithm for the socket. socket_->setSocketOption(QTcpSocket::LowDelayOption, 1); #if defined(OS_WIN) struct tcp_keepalive alive; alive.onoff = 1; // On. alive.keepalivetime = 30000; // 30 seconds. alive.keepaliveinterval = 5000; // 5 seconds. DWORD bytes_returned; if (WSAIoctl(socket_->socketDescriptor(), SIO_KEEPALIVE_VALS, &alive, sizeof(alive), nullptr, 0, &bytes_returned, nullptr, nullptr) == SOCKET_ERROR) { PLOG(LS_WARNING) << "WSAIoctl failed"; } #endif uint32_t methods = proto::METHOD_SRP_CHACHA20_POLY1305; if (base::CPUID::hasAesNi()) methods |= proto::METHOD_SRP_AES256_GCM; proto::ClientHello client_hello; client_hello.set_methods(methods); // Send ClientHello to server. sendInternal(serializeMessage(client_hello)); } void ChannelClient::readServerHello(const QByteArray& buffer) { key_exchange_state_ = KeyExchangeState::IDENTIFY; proto::ServerHello server_hello; if (!server_hello.ParseFromArray(buffer.constData(), buffer.size())) { emit errorOccurred(Error::PROTOCOL_FAILURE); return; } srp_client_.reset(SrpClientContext::create(server_hello.method(), username_, password_)); if (!srp_client_) { LOG(LS_WARNING) << "Unable to create SRP client"; emit errorOccurred(Error::UNKNOWN); return; } std::unique_ptr<proto::SrpIdentify> identify(srp_client_->identify()); if (!identify) { LOG(LS_WARNING) << "Error when creating identify"; emit errorOccurred(Error::UNKNOWN); return; } key_exchange_state_ = KeyExchangeState::KEY_EXCHANGE; sendInternal(serializeMessage(*identify)); } void ChannelClient::readServerKeyExchange(const QByteArray& buffer) { DCHECK(srp_client_); proto::SrpServerKeyExchange server_key_exchange; if (!server_key_exchange.ParseFromArray(buffer.constData(), buffer.size())) { emit errorOccurred(Error::PROTOCOL_FAILURE); return; } std::unique_ptr<proto::SrpClientKeyExchange> client_key_exchange( srp_client_->readServerKeyExchange(server_key_exchange)); if (!client_key_exchange) { LOG(LS_WARNING) << "Error when reading server key exchange"; emit errorOccurred(Error::UNKNOWN); return; } key_exchange_state_ = KeyExchangeState::SESSION; sendInternal(serializeMessage(*client_key_exchange)); } void ChannelClient::readSessionChallenge(const QByteArray& buffer) { DCHECK(srp_client_); switch (srp_client_->method()) { case proto::METHOD_SRP_AES256_GCM: { cryptor_.reset(crypto::CryptorAes256Gcm::create( srp_client_->key(), srp_client_->encryptIv(), srp_client_->decryptIv())); } break; case proto::METHOD_SRP_CHACHA20_POLY1305: { cryptor_.reset(crypto::CryptorChaCha20Poly1305::create( srp_client_->key(), srp_client_->encryptIv(), srp_client_->decryptIv())); } break; default: LOG(LS_WARNING) << "Unknown encryption method: " << srp_client_->method(); break; } if (!cryptor_) { LOG(LS_WARNING) << "Unable to create cryptor"; emit errorOccurred(Error::UNKNOWN); return; } QByteArray session_challenge_buffer; session_challenge_buffer.resize(cryptor_->decryptedDataSize(buffer.size())); if (!cryptor_->decrypt(buffer.constData(), buffer.size(), session_challenge_buffer.data())) { emit errorOccurred(Error::AUTHENTICATION_FAILURE); return; } proto::SessionChallenge session_challenge; if (!session_challenge.ParseFromArray(session_challenge_buffer.constData(), session_challenge_buffer.size())) { emit errorOccurred(Error::AUTHENTICATION_FAILURE); return; } if (!(session_challenge.session_types() & session_type_)) { emit errorOccurred(Error::SESSION_TYPE_NOT_ALLOWED); return; } const proto::Version& host_version = session_challenge.version(); peer_version_ = base::Version( host_version.major(), host_version.minor(), host_version.patch()); proto::SessionResponse session_response; session_response.set_session_type(session_type_); proto::Version* client_version = session_response.mutable_version(); client_version->set_major(ASPIA_VERSION_MAJOR); client_version->set_minor(ASPIA_VERSION_MINOR); client_version->set_patch(ASPIA_VERSION_PATCH); QByteArray session_response_buffer = serializeMessage(session_response); if (session_response_buffer.isEmpty()) { LOG(LS_WARNING) << "Error when creating session response"; emit errorOccurred(Error::UNKNOWN); return; } QByteArray encrypted_buffer; encrypted_buffer.resize(cryptor_->encryptedDataSize(session_response_buffer.size())); if (!cryptor_->encrypt(session_response_buffer.constData(), session_response_buffer.size(), encrypted_buffer.data())) { emit errorOccurred(Error::ENCRYPTION_FAILURE); return; } // After the successful completion of the key exchange, we pause the channel. // To continue receiving messages, slot |start| must be called. pause(); key_exchange_state_ = KeyExchangeState::DONE; sendInternal(encrypted_buffer); } } // namespace net <commit_msg>- Set keep live timeout to 60 seconds.<commit_after>// // Aspia Project // Copyright (C) 2018 Dmitry Chapyshev <dmitry@aspia.ru> // // 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 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 General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. // #include "net/network_channel_client.h" #include "base/cpuid.h" #include "base/logging.h" #include "build/build_config.h" #include "build/version.h" #include "crypto/cryptor_aes256_gcm.h" #include "crypto/cryptor_chacha20_poly1305.h" #include "crypto/secure_memory.h" #include "net/srp_client_context.h" #include <QNetworkProxy> #if defined(OS_WIN) #include <winsock2.h> #include <mstcpip.h> #endif // defined(OS_WIN) namespace net { namespace { QByteArray serializeMessage(const google::protobuf::MessageLite& message) { size_t size = message.ByteSizeLong(); if (!size) { LOG(LS_WARNING) << "Empty messages are not allowed"; return QByteArray(); } QByteArray buffer; buffer.resize(size); message.SerializeWithCachedSizesToArray(reinterpret_cast<uint8_t*>(buffer.data())); return buffer; } } // namespace ChannelClient::ChannelClient(QObject* parent) : Channel(ChannelType::CLIENT, new QTcpSocket(), parent) { // We must enable this option before the connection is established. socket_->setSocketOption(QTcpSocket::KeepAliveOption, 1); connect(socket_, &QTcpSocket::connected, this, &ChannelClient::onConnected); } ChannelClient::~ChannelClient() { crypto::memZero(&password_); } void ChannelClient::connectToHost(const QString& address, int port, const QString& username, const QString& password, proto::SessionType session_type) { username_ = username; password_ = password; session_type_ = session_type; socket_->setProxy(QNetworkProxy::NoProxy); socket_->connectToHost(address, port); } void ChannelClient::internalMessageReceived(const QByteArray& buffer) { switch (key_exchange_state_) { case KeyExchangeState::HELLO: readServerHello(buffer); break; case KeyExchangeState::KEY_EXCHANGE: readServerKeyExchange(buffer); break; case KeyExchangeState::SESSION: readSessionChallenge(buffer); break; default: break; } } void ChannelClient::internalMessageWritten() { switch (key_exchange_state_) { case KeyExchangeState::DONE: { channel_state_ = ChannelState::ENCRYPTED; srp_client_.reset(); emit connected(); } break; default: break; } } void ChannelClient::onConnected() { channel_state_ = ChannelState::CONNECTED; // Disable the Nagle algorithm for the socket. socket_->setSocketOption(QTcpSocket::LowDelayOption, 1); #if defined(OS_WIN) struct tcp_keepalive alive; alive.onoff = 1; // On. alive.keepalivetime = 60000; // 60 seconds. alive.keepaliveinterval = 5000; // 5 seconds. DWORD bytes_returned; if (WSAIoctl(socket_->socketDescriptor(), SIO_KEEPALIVE_VALS, &alive, sizeof(alive), nullptr, 0, &bytes_returned, nullptr, nullptr) == SOCKET_ERROR) { PLOG(LS_WARNING) << "WSAIoctl failed"; } #endif uint32_t methods = proto::METHOD_SRP_CHACHA20_POLY1305; if (base::CPUID::hasAesNi()) methods |= proto::METHOD_SRP_AES256_GCM; proto::ClientHello client_hello; client_hello.set_methods(methods); // Send ClientHello to server. sendInternal(serializeMessage(client_hello)); } void ChannelClient::readServerHello(const QByteArray& buffer) { key_exchange_state_ = KeyExchangeState::IDENTIFY; proto::ServerHello server_hello; if (!server_hello.ParseFromArray(buffer.constData(), buffer.size())) { emit errorOccurred(Error::PROTOCOL_FAILURE); return; } srp_client_.reset(SrpClientContext::create(server_hello.method(), username_, password_)); if (!srp_client_) { LOG(LS_WARNING) << "Unable to create SRP client"; emit errorOccurred(Error::UNKNOWN); return; } std::unique_ptr<proto::SrpIdentify> identify(srp_client_->identify()); if (!identify) { LOG(LS_WARNING) << "Error when creating identify"; emit errorOccurred(Error::UNKNOWN); return; } key_exchange_state_ = KeyExchangeState::KEY_EXCHANGE; sendInternal(serializeMessage(*identify)); } void ChannelClient::readServerKeyExchange(const QByteArray& buffer) { DCHECK(srp_client_); proto::SrpServerKeyExchange server_key_exchange; if (!server_key_exchange.ParseFromArray(buffer.constData(), buffer.size())) { emit errorOccurred(Error::PROTOCOL_FAILURE); return; } std::unique_ptr<proto::SrpClientKeyExchange> client_key_exchange( srp_client_->readServerKeyExchange(server_key_exchange)); if (!client_key_exchange) { LOG(LS_WARNING) << "Error when reading server key exchange"; emit errorOccurred(Error::UNKNOWN); return; } key_exchange_state_ = KeyExchangeState::SESSION; sendInternal(serializeMessage(*client_key_exchange)); } void ChannelClient::readSessionChallenge(const QByteArray& buffer) { DCHECK(srp_client_); switch (srp_client_->method()) { case proto::METHOD_SRP_AES256_GCM: { cryptor_.reset(crypto::CryptorAes256Gcm::create( srp_client_->key(), srp_client_->encryptIv(), srp_client_->decryptIv())); } break; case proto::METHOD_SRP_CHACHA20_POLY1305: { cryptor_.reset(crypto::CryptorChaCha20Poly1305::create( srp_client_->key(), srp_client_->encryptIv(), srp_client_->decryptIv())); } break; default: LOG(LS_WARNING) << "Unknown encryption method: " << srp_client_->method(); break; } if (!cryptor_) { LOG(LS_WARNING) << "Unable to create cryptor"; emit errorOccurred(Error::UNKNOWN); return; } QByteArray session_challenge_buffer; session_challenge_buffer.resize(cryptor_->decryptedDataSize(buffer.size())); if (!cryptor_->decrypt(buffer.constData(), buffer.size(), session_challenge_buffer.data())) { emit errorOccurred(Error::AUTHENTICATION_FAILURE); return; } proto::SessionChallenge session_challenge; if (!session_challenge.ParseFromArray(session_challenge_buffer.constData(), session_challenge_buffer.size())) { emit errorOccurred(Error::AUTHENTICATION_FAILURE); return; } if (!(session_challenge.session_types() & session_type_)) { emit errorOccurred(Error::SESSION_TYPE_NOT_ALLOWED); return; } const proto::Version& host_version = session_challenge.version(); peer_version_ = base::Version( host_version.major(), host_version.minor(), host_version.patch()); proto::SessionResponse session_response; session_response.set_session_type(session_type_); proto::Version* client_version = session_response.mutable_version(); client_version->set_major(ASPIA_VERSION_MAJOR); client_version->set_minor(ASPIA_VERSION_MINOR); client_version->set_patch(ASPIA_VERSION_PATCH); QByteArray session_response_buffer = serializeMessage(session_response); if (session_response_buffer.isEmpty()) { LOG(LS_WARNING) << "Error when creating session response"; emit errorOccurred(Error::UNKNOWN); return; } QByteArray encrypted_buffer; encrypted_buffer.resize(cryptor_->encryptedDataSize(session_response_buffer.size())); if (!cryptor_->encrypt(session_response_buffer.constData(), session_response_buffer.size(), encrypted_buffer.data())) { emit errorOccurred(Error::ENCRYPTION_FAILURE); return; } // After the successful completion of the key exchange, we pause the channel. // To continue receiving messages, slot |start| must be called. pause(); key_exchange_state_ = KeyExchangeState::DONE; sendInternal(encrypted_buffer); } } // namespace net <|endoftext|>
<commit_before>/********************************************************************** * $Id$ * * GEOS - Geometry Engine Open Source * http://geos.refractions.net * * Copyright (C) 2001-2002 Vivid Solutions Inc. * * This is free software; you can redistribute and/or modify it under * the terms of the GNU Lesser General Public Licence as published * by the Free Software Foundation. * See the COPYING file for more information. * ********************************************************************** * $Log$ * Revision 1.11 2003/12/11 16:01:12 strk * made buffer operation return a cloned input geom when called with 0 as distance * * Revision 1.10 2003/11/07 17:51:02 strk * Memory leak fix in insertEdge() * * Revision 1.9 2003/11/07 01:23:42 pramsey * Add standard CVS headers licence notices and copyrights to all cpp and h * files. * * Revision 1.8 2003/11/06 18:47:55 strk * Added throw specification for BufferOp's ::buildSubgraphs() * and ::computeBuffer(). Cleanup on exception in computeBuffer(). * * Revision 1.7 2003/11/06 18:00:15 strk * Cleanup on exception in ::bufferOp() * * Revision 1.6 2003/10/15 16:39:03 strk * Made Edge::getCoordinates() return a 'const' value. Adapted code set. * **********************************************************************/ #include "../../headers/opBuffer.h" #include <algorithm> namespace geos { Geometry* BufferOp::bufferOp(Geometry *g, double distance){ if ( ! distance ) return g->clone(); BufferOp *gBuf=new BufferOp(g); Geometry *geomBuf; try { geomBuf=gBuf->getResultGeometry(distance); } catch (...) { delete gBuf; throw; } delete gBuf; return geomBuf; } Geometry* BufferOp::bufferOp(Geometry *g, double distance, int quadrantSegments){ if ( ! distance ) return g->clone(); BufferOp *gBuf=new BufferOp(g); Geometry *geomBuf; try { geomBuf=gBuf->getResultGeometry(distance, quadrantSegments); } catch (...) { delete gBuf; throw; } delete gBuf; return geomBuf; } /** *Compute the change in depth as an edge is crossed from R to L */ int BufferOp::depthDelta(Label *label){ int lLoc=label->getLocation(0,Position::LEFT); int rLoc=label->getLocation(0,Position::RIGHT); if (lLoc==Location::INTERIOR && rLoc==Location::EXTERIOR) return 1; else if (lLoc==Location::EXTERIOR && rLoc==Location::INTERIOR) return -1; return 0; } BufferOp::BufferOp(Geometry *g0): GeometryGraphOperation(g0) { resultGeom=NULL; edgeList=new EdgeList(); graph=new PlanarGraph(new OverlayNodeFactory()); geomFact=new GeometryFactory(g0->getPrecisionModel(),g0->getSRID()); } BufferOp::~BufferOp(){ delete edgeList; delete graph; delete geomFact; } Geometry* BufferOp::getResultGeometry(double distance) { computeBuffer(distance,BufferLineBuilder::DEFAULT_QUADRANT_SEGMENTS); return resultGeom; } Geometry* BufferOp::getResultGeometry(double distance, int quadrantSegments) { computeBuffer(distance, quadrantSegments); return resultGeom; } void BufferOp::computeBuffer(double distance, int quadrantSegments) throw(TopologyException *) { BufferEdgeBuilder *bufEdgeBuilder=new BufferEdgeBuilder(cga,li,distance,resultPrecisionModel,quadrantSegments); vector<Edge*> *bufferEdgeList=bufEdgeBuilder->getEdges(getArgGeometry(0)); vector<Edge*> *nodedEdges=nodeEdges(bufferEdgeList); for(int i=0;i<(int)nodedEdges->size();i++) { Edge *e=(*nodedEdges)[i]; insertEdge(e); } replaceCollapsedEdges(); graph->addEdges(edgeList); vector<BufferSubgraph*> *subgraphList=createSubgraphs(); PolygonBuilder *polyBuilder=new PolygonBuilder(geomFact,cga); try { buildSubgraphs(subgraphList,polyBuilder); } // *Should* throw a TopologyException only catch (...) { delete polyBuilder; delete nodedEdges; delete bufEdgeBuilder; for(int i=0;i<(int)subgraphList->size();i++) { delete (*subgraphList)[i]; } delete subgraphList; throw; } vector<Polygon*> *resultPolyList=polyBuilder->getPolygons(); resultGeom=computeGeometry(resultPolyList); //computeBufferLine(graph); delete bufEdgeBuilder; delete polyBuilder; delete resultPolyList; for(int i=0;i<(int)subgraphList->size();i++) { delete (*subgraphList)[i]; } delete subgraphList; delete nodedEdges; } /** *Use a GeometryGraph to node the created edges, *and create split edges between the nodes */ vector<Edge*>* BufferOp::nodeEdges(vector<Edge*> *edges){ // intersect edges again to ensure they are noded correctly GeometryGraph *ggraph=new GeometryGraph(0,geomFact->getPrecisionModel(),0); for (int i=0;i<(int)edges->size();i++) { Edge *e=(*edges)[i]; ggraph->addEdge(e); } SegmentIntersector *si=ggraph->computeSelfNodes(li, false); /* if (si.hasProperIntersection()) Debug.println("proper intersection found"); else Debug.println("no proper intersection found"); */ vector<Edge*> *newEdges=new vector<Edge*>(); ggraph->computeSplitEdges(newEdges); delete si; delete ggraph; return newEdges; } /** *Inserted edges are checked identical edge already exists. *If so, the edge is not inserted, but its label is merged *with the existing edge. * NOTE: the edge is deleted if already found ! */ void BufferOp::insertEdge(Edge *e){ //Debug.println(e); int foundIndex=edgeList->findEdgeIndex(e); // If an identical edge already exists, simply update its label if (foundIndex>=0) { Edge *existingEdge=(*edgeList)[foundIndex]; Label *existingLabel=existingEdge->getLabel(); Label *labelToMerge=e->getLabel(); // check if new edge is in reverse direction to existing edge // if so, must flip the label before merging it if (!existingEdge->isPointwiseEqual(e)) { labelToMerge=new Label(e->getLabel()); labelToMerge->flip(); } existingLabel->merge(labelToMerge); // compute new depth delta of sum of edges int mergeDelta=depthDelta(labelToMerge); int existingDelta=existingEdge->getDepthDelta(); int newDelta=existingDelta+mergeDelta; existingEdge->setDepthDelta(newDelta); checkDimensionalCollapse(labelToMerge,existingLabel); //Debug.print("new edge "); Debug.println(e); //Debug.print("existing "); Debug.println(existingEdge); delete e; } else { // no matching existing edge was found // add this new edge to the list of edges in this graph //e.setName(name+edges.size()); edgeList->push_back(e); e->setDepthDelta(depthDelta(e->getLabel())); } } /** *If either of the GeometryLocations for the existing label is *exactly opposite to the one in the labelToMerge, *this indicates a dimensional collapse has happened. *In this case, convert the label for that Geometry to a Line label */ void BufferOp::checkDimensionalCollapse(Label *labelToMerge,Label *existingLabel){ if (existingLabel->isArea() && labelToMerge->isArea()) { for (int i=0;i<2;i++) { if (!labelToMerge->isNull(i) && labelToMerge->getLocation(i,Position::LEFT)==existingLabel->getLocation(i,Position::RIGHT) && labelToMerge->getLocation(i,Position::RIGHT)==existingLabel->getLocation(i,Position::LEFT)) { existingLabel->toLine(i); } } } } /** *If collapsed edges are found, replace them with a new edge which is a L edge */ void BufferOp::replaceCollapsedEdges() { vector<Edge*> *newEdges=new vector<Edge*>(); for(int i=0;i<(int)edgeList->size();i++) { Edge *e=(*edgeList)[i]; if (e->isCollapsed()) { //Debug.print(e); edgeList->erase(edgeList->begin()+i); newEdges->push_back(e->getCollapsedEdge()); } } ((vector<Edge*>*)edgeList)->insert(edgeList->end(),newEdges->begin(),newEdges->end()); delete newEdges; } bool bsgGreaterThan(BufferSubgraph *first,BufferSubgraph *second) { if (first->compareTo(second)>0) return true; else return false; } vector<BufferSubgraph*>* BufferOp::createSubgraphs(){ vector<BufferSubgraph*> *subgraphList=new vector<BufferSubgraph*>(); map<Coordinate,Node*,CoordLT> *nodeMap=graph->getNodeMap()->nodeMap; map<Coordinate,Node*,CoordLT>::iterator it=nodeMap->begin(); for (;it!=nodeMap->end();it++) { Node *node=it->second; if (!node->isVisited()) { BufferSubgraph *subgraph=new BufferSubgraph(cga); subgraph->create(node); subgraphList->push_back(subgraph); } } /** *Sort the subgraphs in descending order of their rightmost coordinate. *This ensures that when the Polygons for the subgraphs are built, *subgraphs for shells will have been built before the subgraphs for *any holes they contain. */ sort(subgraphList->begin(),subgraphList->end(),bsgGreaterThan); return subgraphList; } void BufferOp::buildSubgraphs(vector<BufferSubgraph*> *subgraphList,PolygonBuilder *polyBuilder) throw (TopologyException *) { for(int i=0;i<(int)subgraphList->size();i++) { BufferSubgraph *subgraph=(*subgraphList)[i]; Coordinate& p=subgraph->getRightmostCoordinate(); int outsideDepth=0; if (polyBuilder->containsPoint(p)) outsideDepth=1; subgraph->computeDepth(outsideDepth); subgraph->findResultEdges(); // This might throw a TopologyException polyBuilder->add(subgraph->getDirectedEdges(),subgraph->getNodes()); } } Geometry* BufferOp::computeGeometry(vector<Polygon*> *resultPolyList){ vector<Geometry*> *geomList=new vector<Geometry*>(); for(int i=0;i<(int)resultPolyList->size();i++) { geomList->push_back((*resultPolyList)[i]); } Geometry *g=geomFact->buildGeometry(geomList); delete geomList; return g; } /** *toLineStrings converts a list of Edges to LineStrings. */ Geometry* BufferOp::toLineStrings(EdgeList *edges){ vector<Geometry*> *geomList=new vector<Geometry*>(); for(int i=0;i<(int)edges->size();i++) { Edge *e=(*edges)[i]; const CoordinateList *pts=e->getCoordinates(); LineString *line=geomFact->createLineString(pts); geomList->push_back(line); } Geometry *geom=geomFact->buildGeometry(geomList); return geom; } } <commit_msg>made buffer(0) back to its *correct* semantic (empy collection)<commit_after>/********************************************************************** * $Id$ * * GEOS - Geometry Engine Open Source * http://geos.refractions.net * * Copyright (C) 2001-2002 Vivid Solutions Inc. * * This is free software; you can redistribute and/or modify it under * the terms of the GNU Lesser General Public Licence as published * by the Free Software Foundation. * See the COPYING file for more information. * ********************************************************************** * $Log$ * Revision 1.12 2003/12/11 17:01:35 strk * made buffer(0) back to its *correct* semantic (empy collection) * * Revision 1.11 2003/12/11 16:01:12 strk * made buffer operation return a cloned input geom when called with 0 as distance * * Revision 1.10 2003/11/07 17:51:02 strk * Memory leak fix in insertEdge() * * Revision 1.9 2003/11/07 01:23:42 pramsey * Add standard CVS headers licence notices and copyrights to all cpp and h * files. * * Revision 1.8 2003/11/06 18:47:55 strk * Added throw specification for BufferOp's ::buildSubgraphs() * and ::computeBuffer(). Cleanup on exception in computeBuffer(). * * Revision 1.7 2003/11/06 18:00:15 strk * Cleanup on exception in ::bufferOp() * * Revision 1.6 2003/10/15 16:39:03 strk * Made Edge::getCoordinates() return a 'const' value. Adapted code set. * **********************************************************************/ #include "../../headers/opBuffer.h" #include <algorithm> namespace geos { Geometry* BufferOp::bufferOp(Geometry *g, double distance){ BufferOp *gBuf=new BufferOp(g); Geometry *geomBuf; try { geomBuf=gBuf->getResultGeometry(distance); } catch (...) { delete gBuf; throw; } delete gBuf; return geomBuf; } Geometry* BufferOp::bufferOp(Geometry *g, double distance, int quadrantSegments){ BufferOp *gBuf=new BufferOp(g); Geometry *geomBuf; try { geomBuf=gBuf->getResultGeometry(distance, quadrantSegments); } catch (...) { delete gBuf; throw; } delete gBuf; return geomBuf; } /** *Compute the change in depth as an edge is crossed from R to L */ int BufferOp::depthDelta(Label *label){ int lLoc=label->getLocation(0,Position::LEFT); int rLoc=label->getLocation(0,Position::RIGHT); if (lLoc==Location::INTERIOR && rLoc==Location::EXTERIOR) return 1; else if (lLoc==Location::EXTERIOR && rLoc==Location::INTERIOR) return -1; return 0; } BufferOp::BufferOp(Geometry *g0): GeometryGraphOperation(g0) { resultGeom=NULL; edgeList=new EdgeList(); graph=new PlanarGraph(new OverlayNodeFactory()); geomFact=new GeometryFactory(g0->getPrecisionModel(),g0->getSRID()); } BufferOp::~BufferOp(){ delete edgeList; delete graph; delete geomFact; } Geometry* BufferOp::getResultGeometry(double distance) { computeBuffer(distance,BufferLineBuilder::DEFAULT_QUADRANT_SEGMENTS); return resultGeom; } Geometry* BufferOp::getResultGeometry(double distance, int quadrantSegments) { computeBuffer(distance, quadrantSegments); return resultGeom; } void BufferOp::computeBuffer(double distance, int quadrantSegments) throw(TopologyException *) { BufferEdgeBuilder *bufEdgeBuilder=new BufferEdgeBuilder(cga,li,distance,resultPrecisionModel,quadrantSegments); vector<Edge*> *bufferEdgeList=bufEdgeBuilder->getEdges(getArgGeometry(0)); vector<Edge*> *nodedEdges=nodeEdges(bufferEdgeList); for(int i=0;i<(int)nodedEdges->size();i++) { Edge *e=(*nodedEdges)[i]; insertEdge(e); } replaceCollapsedEdges(); graph->addEdges(edgeList); vector<BufferSubgraph*> *subgraphList=createSubgraphs(); PolygonBuilder *polyBuilder=new PolygonBuilder(geomFact,cga); try { buildSubgraphs(subgraphList,polyBuilder); } // *Should* throw a TopologyException only catch (...) { delete polyBuilder; delete nodedEdges; delete bufEdgeBuilder; for(int i=0;i<(int)subgraphList->size();i++) { delete (*subgraphList)[i]; } delete subgraphList; throw; } vector<Polygon*> *resultPolyList=polyBuilder->getPolygons(); resultGeom=computeGeometry(resultPolyList); //computeBufferLine(graph); delete bufEdgeBuilder; delete polyBuilder; delete resultPolyList; for(int i=0;i<(int)subgraphList->size();i++) { delete (*subgraphList)[i]; } delete subgraphList; delete nodedEdges; } /** *Use a GeometryGraph to node the created edges, *and create split edges between the nodes */ vector<Edge*>* BufferOp::nodeEdges(vector<Edge*> *edges){ // intersect edges again to ensure they are noded correctly GeometryGraph *ggraph=new GeometryGraph(0,geomFact->getPrecisionModel(),0); for (int i=0;i<(int)edges->size();i++) { Edge *e=(*edges)[i]; ggraph->addEdge(e); } SegmentIntersector *si=ggraph->computeSelfNodes(li, false); /* if (si.hasProperIntersection()) Debug.println("proper intersection found"); else Debug.println("no proper intersection found"); */ vector<Edge*> *newEdges=new vector<Edge*>(); ggraph->computeSplitEdges(newEdges); delete si; delete ggraph; return newEdges; } /** *Inserted edges are checked identical edge already exists. *If so, the edge is not inserted, but its label is merged *with the existing edge. * NOTE: the edge is deleted if already found ! */ void BufferOp::insertEdge(Edge *e){ //Debug.println(e); int foundIndex=edgeList->findEdgeIndex(e); // If an identical edge already exists, simply update its label if (foundIndex>=0) { Edge *existingEdge=(*edgeList)[foundIndex]; Label *existingLabel=existingEdge->getLabel(); Label *labelToMerge=e->getLabel(); // check if new edge is in reverse direction to existing edge // if so, must flip the label before merging it if (!existingEdge->isPointwiseEqual(e)) { labelToMerge=new Label(e->getLabel()); labelToMerge->flip(); } existingLabel->merge(labelToMerge); // compute new depth delta of sum of edges int mergeDelta=depthDelta(labelToMerge); int existingDelta=existingEdge->getDepthDelta(); int newDelta=existingDelta+mergeDelta; existingEdge->setDepthDelta(newDelta); checkDimensionalCollapse(labelToMerge,existingLabel); //Debug.print("new edge "); Debug.println(e); //Debug.print("existing "); Debug.println(existingEdge); delete e; } else { // no matching existing edge was found // add this new edge to the list of edges in this graph //e.setName(name+edges.size()); edgeList->push_back(e); e->setDepthDelta(depthDelta(e->getLabel())); } } /** *If either of the GeometryLocations for the existing label is *exactly opposite to the one in the labelToMerge, *this indicates a dimensional collapse has happened. *In this case, convert the label for that Geometry to a Line label */ void BufferOp::checkDimensionalCollapse(Label *labelToMerge,Label *existingLabel){ if (existingLabel->isArea() && labelToMerge->isArea()) { for (int i=0;i<2;i++) { if (!labelToMerge->isNull(i) && labelToMerge->getLocation(i,Position::LEFT)==existingLabel->getLocation(i,Position::RIGHT) && labelToMerge->getLocation(i,Position::RIGHT)==existingLabel->getLocation(i,Position::LEFT)) { existingLabel->toLine(i); } } } } /** *If collapsed edges are found, replace them with a new edge which is a L edge */ void BufferOp::replaceCollapsedEdges() { vector<Edge*> *newEdges=new vector<Edge*>(); for(int i=0;i<(int)edgeList->size();i++) { Edge *e=(*edgeList)[i]; if (e->isCollapsed()) { //Debug.print(e); edgeList->erase(edgeList->begin()+i); newEdges->push_back(e->getCollapsedEdge()); } } ((vector<Edge*>*)edgeList)->insert(edgeList->end(),newEdges->begin(),newEdges->end()); delete newEdges; } bool bsgGreaterThan(BufferSubgraph *first,BufferSubgraph *second) { if (first->compareTo(second)>0) return true; else return false; } vector<BufferSubgraph*>* BufferOp::createSubgraphs(){ vector<BufferSubgraph*> *subgraphList=new vector<BufferSubgraph*>(); map<Coordinate,Node*,CoordLT> *nodeMap=graph->getNodeMap()->nodeMap; map<Coordinate,Node*,CoordLT>::iterator it=nodeMap->begin(); for (;it!=nodeMap->end();it++) { Node *node=it->second; if (!node->isVisited()) { BufferSubgraph *subgraph=new BufferSubgraph(cga); subgraph->create(node); subgraphList->push_back(subgraph); } } /** *Sort the subgraphs in descending order of their rightmost coordinate. *This ensures that when the Polygons for the subgraphs are built, *subgraphs for shells will have been built before the subgraphs for *any holes they contain. */ sort(subgraphList->begin(),subgraphList->end(),bsgGreaterThan); return subgraphList; } void BufferOp::buildSubgraphs(vector<BufferSubgraph*> *subgraphList,PolygonBuilder *polyBuilder) throw (TopologyException *) { for(int i=0;i<(int)subgraphList->size();i++) { BufferSubgraph *subgraph=(*subgraphList)[i]; Coordinate& p=subgraph->getRightmostCoordinate(); int outsideDepth=0; if (polyBuilder->containsPoint(p)) outsideDepth=1; subgraph->computeDepth(outsideDepth); subgraph->findResultEdges(); // This might throw a TopologyException polyBuilder->add(subgraph->getDirectedEdges(),subgraph->getNodes()); } } Geometry* BufferOp::computeGeometry(vector<Polygon*> *resultPolyList){ vector<Geometry*> *geomList=new vector<Geometry*>(); for(int i=0;i<(int)resultPolyList->size();i++) { geomList->push_back((*resultPolyList)[i]); } Geometry *g=geomFact->buildGeometry(geomList); delete geomList; return g; } /** *toLineStrings converts a list of Edges to LineStrings. */ Geometry* BufferOp::toLineStrings(EdgeList *edges){ vector<Geometry*> *geomList=new vector<Geometry*>(); for(int i=0;i<(int)edges->size();i++) { Edge *e=(*edges)[i]; const CoordinateList *pts=e->getCoordinates(); LineString *line=geomFact->createLineString(pts); geomList->push_back(line); } Geometry *geom=geomFact->buildGeometry(geomList); return geom; } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: basenode.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: obo $ $Date: 2005-10-11 08:43:44 $ * * 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 INCLUDED_SLIDESHOW_BASENODE_HXX #define INCLUDED_SLIDESHOW_BASENODE_HXX #include "animationnode.hxx" #include "slideshowcontext.hxx" #include "shapesubset.hxx" #include <vector> namespace presentation { namespace internal { typedef int StateTransitionTable[17]; /** Context for every node. Besides the global AnimationNodeFactory::Context data, this struct also contains the current DocTree subset for this node. If start and end index of the DocTreeNode are equal, the node should use the complete shape. */ struct NodeContext { NodeContext( const SlideShowContext& rContext ) : maContext( rContext ), mpMasterShapeSubset(), mnStartDelay(0.0), mbIsIndependentSubset( true ) {} void dispose() { maContext.dispose(); } /// Context as passed to createAnimationNode() SlideShowContext maContext; /// Shape to be used (provided by parent, e.g. for iterations) ShapeSubsetSharedPtr mpMasterShapeSubset; /// Additional delay to node begin (to offset iterate effects) double mnStartDelay; /// When true, subset must be created during slide initialization bool mbIsIndependentSubset; }; class BaseContainerNode; /** This interface extends AnimationNode with some file-private accessor methods. */ class BaseNode : public AnimationNode { public: BaseNode( const ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode >& xNode, const ::boost::shared_ptr< BaseContainerNode >& rParent, const NodeContext& rContext ); /** Provide the node with a shared_ptr to itself. Since implementation has to create objects which need a shared_ptr to this node, and a pointee cannot retrieve a shared_ptr to itself internally, have to set that from the outside. */ void setSelf( const ::boost::shared_ptr< BaseNode >& rSelf ); // Disposable interface // -------------------- virtual void dispose(); // Implemented subset of AnimationNode interface // --------------------------------------------- virtual ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode> getXAnimationNode() const; virtual bool init(); virtual bool resolve(); virtual bool activate(); virtual void deactivate(); virtual void end(); virtual NodeState getState() const; virtual bool registerDeactivatingListener( const AnimationNodeSharedPtr& rNotifee ); #if defined(VERBOSE) && defined(DBG_UTIL) virtual void showState() const; virtual const char* getDescription() const; void showTreeFromWithin() const; #endif const ::boost::shared_ptr< BaseContainerNode >& getParentNode() const { return mpParent; } protected: // inline accessors // ---------------- const SlideShowContext& getContext() const { return maContext; } const ::boost::shared_ptr< BaseNode >& getSelf() const { return mpSelf; } const ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode >& getXNode() const { return mxNode; } bool isMainSequenceRootNode() const { return mbIsMainSequenceRootNode; } /** Schedule event that activates the node, once it is resolved You can override this method in derived classes. AnimateBaseNode does it to implement its fixed delay */ virtual void scheduleActivationEvent(); /** Schedule event that deactivates the node, once it is active You can override this method in derived classes. */ virtual void scheduleDeactivationEvent() const; private: /** Get the default fill mode. If this node's default mode is AnimationFill::DEFAULT, this method recursively calls the parent node. */ sal_Int16 getFillDefaultMode() const; /** Get the default restart mode If this node's default mode is AnimationRestart::DEFAULT, this method recursively calls the parent node. */ sal_Int16 getRestartDefaultMode() const; /// Get the node's restart mode sal_Int16 getRestartMode(); /// Get the node's fill mode sal_Int16 getFillMode(); private: SlideShowContext maContext; typedef ::std::vector< AnimationNodeSharedPtr > ListenerVector; ListenerVector maDeactivatingListeners; ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode > mxNode; ::boost::shared_ptr< BaseContainerNode > mpParent; ::boost::shared_ptr< BaseNode > mpSelf; const int* mpStateTransitionTable; const double mnStartDelay; AnimationNode::NodeState meCurrState; const bool mbIsMainSequenceRootNode; }; typedef ::boost::shared_ptr< BaseNode > BaseNodeSharedPtr; } // namespace internal } // namespace presentation #endif /* INCLUDED_SLIDESHOW_BASENODE_HXX */ <commit_msg>INTEGRATION: CWS presfixes10 (1.6.6); FILE MERGED 2005/11/10 15:50:01 dbo 1.6.6.3: missing friend decl for SunCC Issue number: Submitted by: Reviewed by: 2005/11/10 14:57:26 dbo 1.6.6.2: #i45197# cleanup Issue number: Submitted by: Reviewed by: 2005/11/07 15:26:53 dbo 1.6.6.1: #i45197# revised code Issue number: Submitted by: Reviewed by:<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: basenode.hxx,v $ * * $Revision: 1.7 $ * * last change: $Author: rt $ $Date: 2006-07-26 07:35:12 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef INCLUDED_SLIDESHOW_BASENODE_HXX #define INCLUDED_SLIDESHOW_BASENODE_HXX #include "canvas/debug.hxx" #include "osl/diagnose.hxx" #include "animationnode.hxx" #include "slideshowcontext.hxx" #include "shapesubset.hxx" #include "boost/noncopyable.hpp" #include <vector> namespace presentation { namespace internal { /** Context for every node. Besides the global AnimationNodeFactory::Context data, this struct also contains the current DocTree subset for this node. If start and end index of the DocTreeNode are equal, the node should use the complete shape. */ struct NodeContext { NodeContext( const SlideShowContext& rContext ) : maContext( rContext ), mpMasterShapeSubset(), mnStartDelay(0.0), mbIsIndependentSubset( true ) {} void dispose() { maContext.dispose(); } /// Context as passed to createAnimationNode() SlideShowContext maContext; /// Shape to be used (provided by parent, e.g. for iterations) ShapeSubsetSharedPtr mpMasterShapeSubset; /// Additional delay to node begin (to offset iterate effects) double mnStartDelay; /// When true, subset must be created during slide initialization bool mbIsIndependentSubset; }; class BaseContainerNode; /** This interface extends AnimationNode with some file-private accessor methods. */ class BaseNode : public AnimationNode, private ::osl::DebugBase<BaseNode>, private ::boost::noncopyable { public: BaseNode( ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode> const& xNode, ::boost::shared_ptr<BaseContainerNode> const& pParent, NodeContext const& rContext ); /** Provide the node with a shared_ptr to itself. Since implementation has to create objects which need a shared_ptr to this node, and a pointee cannot retrieve a shared_ptr to itself internally, have to set that from the outside. */ void setSelf( const ::boost::shared_ptr< BaseNode >& rSelf ); #if defined(VERBOSE) && defined(DBG_UTIL) virtual void showState() const; virtual const char* getDescription() const; void showTreeFromWithin() const; #endif const ::boost::shared_ptr< BaseContainerNode >& getParentNode() const { return mpParent; } // Disposable: virtual void dispose(); // AnimationNode: virtual bool init(); virtual bool resolve(); virtual bool activate(); virtual void deactivate(); virtual void end(); virtual ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode> getXAnimationNode() const; virtual NodeState getState() const; virtual bool registerDeactivatingListener( const AnimationNodeSharedPtr& rNotifee ); // nop: virtual void notifyDeactivating( const AnimationNodeSharedPtr& rNotifier ); protected: void scheduleDeactivationEvent( EventSharedPtr const& pEvent = EventSharedPtr() ); SlideShowContext const& getContext() const { return maContext; } ::boost::shared_ptr<BaseNode> const& getSelf() const { return mpSelf; } bool isMainSequenceRootNode() const { return mbIsMainSequenceRootNode; } bool checkValidNode() const { ENSURE_AND_THROW( mpSelf, "no self ptr set!" ); bool const bRet = (meCurrState != INVALID); OSL_ENSURE( bRet, "### INVALID node!" ); return bRet; } private: // all state affecting methods have "_st" counterparts being called at // derived classes when in state transistion: no-ops here at BaseNode... virtual bool init_st(); virtual bool resolve_st(); virtual void activate_st(); virtual void deactivate_st( NodeState eDestState ); private: /// notifies /// - all registered deactivation listeners /// - single animation end (every node) /// - slide animations (if main sequence root node) void notifyEndListeners() const; /// Get the node's restart mode sal_Int16 getRestartMode(); /** Get the default restart mode If this node's default mode is AnimationRestart::DEFAULT, this method recursively calls the parent node. */ sal_Int16 getRestartDefaultMode() const; /// Get the node's fill mode sal_Int16 getFillMode(); /** Get the default fill mode. If this node's default mode is AnimationFill::DEFAULT, this method recursively calls the parent node. */ sal_Int16 getFillDefaultMode() const; bool isTransition( NodeState eFromState, NodeState eToState, bool debugAssert = true ) const { bool const bRet =((mpStateTransitionTable[eFromState] & eToState) != 0); OSL_ENSURE( !debugAssert || bRet, "### state unreachable!" ); return bRet; } bool inStateOrTransition( int mask ) const { return ((meCurrState & mask) != 0 || (meCurrentStateTransition & mask) != 0); } class StateTransition; friend class StateTransition; private: SlideShowContext maContext; typedef ::std::vector< AnimationNodeSharedPtr > ListenerVector; ListenerVector maDeactivatingListeners; ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode > mxAnimationNode; ::boost::shared_ptr< BaseContainerNode > mpParent; ::boost::shared_ptr< BaseNode > mpSelf; const int* mpStateTransitionTable; const double mnStartDelay; NodeState meCurrState; int meCurrentStateTransition; EventSharedPtr mpCurrentEvent; const bool mbIsMainSequenceRootNode; }; typedef ::boost::shared_ptr< BaseNode > BaseNodeSharedPtr; } // namespace internal } // namespace presentation #endif /* INCLUDED_SLIDESHOW_BASENODE_HXX */ <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * 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/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you 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 . */ #include <vcl/outdev.hxx> #include <vcl/window.hxx> #include <vcl/salnativewidgets.hxx> #include <vcl/pdfextoutdevdata.hxx> #include <salgdi.hxx> static bool EnableNativeWidget( const OutputDevice& i_rDevice ) { const OutDevType eType( i_rDevice.GetOutDevType() ); switch ( eType ) { case OUTDEV_WINDOW: return dynamic_cast< const Window* >( &i_rDevice )->IsNativeWidgetEnabled(); case OUTDEV_VIRDEV: { const ::vcl::ExtOutDevData* pOutDevData( i_rDevice.GetExtOutDevData() ); const ::vcl::PDFExtOutDevData* pPDFData( dynamic_cast< const ::vcl::PDFExtOutDevData* >( pOutDevData ) ); if ( pPDFData != NULL ) return false; return true; } default: return false; } } ImplControlValue::~ImplControlValue() { } ImplControlValue* ImplControlValue::clone() const { assert( typeid( const ImplControlValue ) == typeid( *this )); return new ImplControlValue( *this ); } ScrollbarValue::~ScrollbarValue() { } ScrollbarValue* ScrollbarValue::clone() const { assert( typeid( const ScrollbarValue ) == typeid( *this )); return new ScrollbarValue( *this ); } SliderValue::~SliderValue() { } SliderValue* SliderValue::clone() const { assert( typeid( const SliderValue ) == typeid( *this )); return new SliderValue( *this ); } TabitemValue::~TabitemValue() { } TabitemValue* TabitemValue::clone() const { assert( typeid( const TabitemValue ) == typeid( *this )); return new TabitemValue( *this ); } SpinbuttonValue::~SpinbuttonValue() { } SpinbuttonValue* SpinbuttonValue::clone() const { assert( typeid( const SpinbuttonValue ) == typeid( *this )); return new SpinbuttonValue( *this ); } ToolbarValue::~ToolbarValue() { } ToolbarValue* ToolbarValue::clone() const { assert( typeid( const ToolbarValue ) == typeid( *this )); return new ToolbarValue( *this ); } MenubarValue::~MenubarValue() { } MenubarValue* MenubarValue::clone() const { assert( typeid( const MenubarValue ) == typeid( *this )); return new MenubarValue( *this ); } MenupopupValue::~MenupopupValue() { } MenupopupValue* MenupopupValue::clone() const { assert( typeid( const MenupopupValue ) == typeid( *this )); return new MenupopupValue( *this ); } PushButtonValue::~PushButtonValue() { } PushButtonValue* PushButtonValue::clone() const { assert( typeid( const PushButtonValue ) == typeid( *this )); return new PushButtonValue( *this ); } // These functions are mainly passthrough functions that allow access to // the SalFrame behind a Window object for native widget rendering purposes. bool OutputDevice::IsNativeControlSupported( ControlType nType, ControlPart nPart ) const { if( !EnableNativeWidget( *this ) ) return false; if ( !mpGraphics ) if ( !AcquireGraphics() ) return false; return( mpGraphics->IsNativeControlSupported(nType, nPart) ); } bool OutputDevice::HitTestNativeControl( ControlType nType, ControlPart nPart, const Rectangle& rControlRegion, const Point& aPos, bool& rIsInside ) const { if( !EnableNativeWidget( *this ) ) return false; if ( !mpGraphics ) if ( !AcquireGraphics() ) return false; Point aWinOffs( mnOutOffX, mnOutOffY ); Rectangle screenRegion( rControlRegion ); screenRegion.Move( aWinOffs.X(), aWinOffs.Y()); return( mpGraphics->HitTestNativeControl(nType, nPart, screenRegion, Point( aPos.X() + mnOutOffX, aPos.Y() + mnOutOffY ), rIsInside, this ) ); } static boost::shared_ptr< ImplControlValue > TransformControlValue( const ImplControlValue& rVal, const OutputDevice& rDev ) { boost::shared_ptr< ImplControlValue > aResult; switch( rVal.getType() ) { case CTRL_SLIDER: { const SliderValue* pSlVal = static_cast<const SliderValue*>(&rVal); SliderValue* pNew = new SliderValue( *pSlVal ); aResult.reset( pNew ); pNew->maThumbRect = rDev.ImplLogicToDevicePixel( pSlVal->maThumbRect ); } break; case CTRL_SCROLLBAR: { const ScrollbarValue* pScVal = static_cast<const ScrollbarValue*>(&rVal); ScrollbarValue* pNew = new ScrollbarValue( *pScVal ); aResult.reset( pNew ); pNew->maThumbRect = rDev.ImplLogicToDevicePixel( pScVal->maThumbRect ); pNew->maButton1Rect = rDev.ImplLogicToDevicePixel( pScVal->maButton1Rect ); pNew->maButton2Rect = rDev.ImplLogicToDevicePixel( pScVal->maButton2Rect ); } break; case CTRL_SPINBUTTONS: { const SpinbuttonValue* pSpVal = static_cast<const SpinbuttonValue*>(&rVal); SpinbuttonValue* pNew = new SpinbuttonValue( *pSpVal ); aResult.reset( pNew ); pNew->maUpperRect = rDev.ImplLogicToDevicePixel( pSpVal->maUpperRect ); pNew->maLowerRect = rDev.ImplLogicToDevicePixel( pSpVal->maLowerRect ); } break; case CTRL_TOOLBAR: { const ToolbarValue* pTVal = static_cast<const ToolbarValue*>(&rVal); ToolbarValue* pNew = new ToolbarValue( *pTVal ); aResult.reset( pNew ); pNew->maGripRect = rDev.ImplLogicToDevicePixel( pTVal->maGripRect ); } break; case CTRL_TAB_ITEM: { const TabitemValue* pTIVal = static_cast<const TabitemValue*>(&rVal); TabitemValue* pNew = new TabitemValue( *pTIVal ); aResult.reset( pNew ); } break; case CTRL_MENUBAR: { const MenubarValue* pMVal = static_cast<const MenubarValue*>(&rVal); MenubarValue* pNew = new MenubarValue( *pMVal ); aResult.reset( pNew ); } break; case CTRL_PUSHBUTTON: { const PushButtonValue* pBVal = static_cast<const PushButtonValue*>(&rVal); PushButtonValue* pNew = new PushButtonValue( *pBVal ); aResult.reset( pNew ); } break; case CTRL_GENERIC: aResult.reset( new ImplControlValue( rVal ) ); break; case CTRL_MENU_POPUP: { const MenupopupValue* pMVal = static_cast<const MenupopupValue*>(&rVal); MenupopupValue* pNew = new MenupopupValue( *pMVal ); pNew->maItemRect = rDev.ImplLogicToDevicePixel( pMVal->maItemRect ); aResult.reset( pNew ); } break; default: OSL_FAIL( "unknown ImplControlValue type !" ); break; } return aResult; } bool OutputDevice::DrawNativeControl( ControlType nType, ControlPart nPart, const Rectangle& rControlRegion, ControlState nState, const ImplControlValue& aValue, const OUString& aCaption ) { if( !EnableNativeWidget( *this ) ) return false; // make sure the current clip region is initialized correctly if ( !mpGraphics ) if ( !AcquireGraphics() ) return false; if ( mbInitClipRegion ) InitClipRegion(); if ( mbOutputClipped ) return true; if ( mbInitLineColor ) InitLineColor(); if ( mbInitFillColor ) InitFillColor(); // Convert the coordinates from relative to Window-absolute, so we draw // in the correct place in platform code boost::shared_ptr< ImplControlValue > aScreenCtrlValue( TransformControlValue( aValue, *this ) ); Rectangle screenRegion( ImplLogicToDevicePixel( rControlRegion ) ); Region aTestRegion( GetActiveClipRegion() ); aTestRegion.Intersect( rControlRegion ); if (aTestRegion == Region(rControlRegion)) nState |= CTRL_CACHING_ALLOWED; // control is not clipped, caching allowed bool bRet = mpGraphics->DrawNativeControl(nType, nPart, screenRegion, nState, *aScreenCtrlValue, aCaption, this ); return bRet; } bool OutputDevice::GetNativeControlRegion( ControlType nType, ControlPart nPart, const Rectangle& rControlRegion, ControlState nState, const ImplControlValue& aValue, const OUString& aCaption, Rectangle &rNativeBoundingRegion, Rectangle &rNativeContentRegion ) const { if( !EnableNativeWidget( *this ) ) return false; if ( !mpGraphics ) if ( !AcquireGraphics() ) return false; // Convert the coordinates from relative to Window-absolute, so we draw // in the correct place in platform code boost::shared_ptr< ImplControlValue > aScreenCtrlValue( TransformControlValue( aValue, *this ) ); Rectangle screenRegion( ImplLogicToDevicePixel( rControlRegion ) ); bool bRet = mpGraphics->GetNativeControlRegion(nType, nPart, screenRegion, nState, *aScreenCtrlValue, aCaption, rNativeBoundingRegion, rNativeContentRegion, this ); if( bRet ) { // transform back native regions rNativeBoundingRegion = ImplDevicePixelToLogic( rNativeBoundingRegion ); rNativeContentRegion = ImplDevicePixelToLogic( rNativeContentRegion ); } return bRet; } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>coverity#1209550 Unchecked dynamic_cast<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * 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/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you 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 . */ #include <vcl/outdev.hxx> #include <vcl/window.hxx> #include <vcl/salnativewidgets.hxx> #include <vcl/pdfextoutdevdata.hxx> #include <salgdi.hxx> static bool EnableNativeWidget( const OutputDevice& i_rDevice ) { const OutDevType eType( i_rDevice.GetOutDevType() ); switch ( eType ) { case OUTDEV_WINDOW: { const Window* pWindow = dynamic_cast< const Window* >( &i_rDevice ); if (pWindow) { return pWindow->IsNativeWidgetEnabled(); } else { SAL_WARN ("vcl.gdi", "Could not cast i_rDevice to Window"); assert (pWindow); return false; } } case OUTDEV_VIRDEV: { const ::vcl::ExtOutDevData* pOutDevData( i_rDevice.GetExtOutDevData() ); const ::vcl::PDFExtOutDevData* pPDFData( dynamic_cast< const ::vcl::PDFExtOutDevData* >( pOutDevData ) ); if ( pPDFData != NULL ) return false; return true; } default: return false; } } ImplControlValue::~ImplControlValue() { } ImplControlValue* ImplControlValue::clone() const { assert( typeid( const ImplControlValue ) == typeid( *this )); return new ImplControlValue( *this ); } ScrollbarValue::~ScrollbarValue() { } ScrollbarValue* ScrollbarValue::clone() const { assert( typeid( const ScrollbarValue ) == typeid( *this )); return new ScrollbarValue( *this ); } SliderValue::~SliderValue() { } SliderValue* SliderValue::clone() const { assert( typeid( const SliderValue ) == typeid( *this )); return new SliderValue( *this ); } TabitemValue::~TabitemValue() { } TabitemValue* TabitemValue::clone() const { assert( typeid( const TabitemValue ) == typeid( *this )); return new TabitemValue( *this ); } SpinbuttonValue::~SpinbuttonValue() { } SpinbuttonValue* SpinbuttonValue::clone() const { assert( typeid( const SpinbuttonValue ) == typeid( *this )); return new SpinbuttonValue( *this ); } ToolbarValue::~ToolbarValue() { } ToolbarValue* ToolbarValue::clone() const { assert( typeid( const ToolbarValue ) == typeid( *this )); return new ToolbarValue( *this ); } MenubarValue::~MenubarValue() { } MenubarValue* MenubarValue::clone() const { assert( typeid( const MenubarValue ) == typeid( *this )); return new MenubarValue( *this ); } MenupopupValue::~MenupopupValue() { } MenupopupValue* MenupopupValue::clone() const { assert( typeid( const MenupopupValue ) == typeid( *this )); return new MenupopupValue( *this ); } PushButtonValue::~PushButtonValue() { } PushButtonValue* PushButtonValue::clone() const { assert( typeid( const PushButtonValue ) == typeid( *this )); return new PushButtonValue( *this ); } // These functions are mainly passthrough functions that allow access to // the SalFrame behind a Window object for native widget rendering purposes. bool OutputDevice::IsNativeControlSupported( ControlType nType, ControlPart nPart ) const { if( !EnableNativeWidget( *this ) ) return false; if ( !mpGraphics ) if ( !AcquireGraphics() ) return false; return( mpGraphics->IsNativeControlSupported(nType, nPart) ); } bool OutputDevice::HitTestNativeControl( ControlType nType, ControlPart nPart, const Rectangle& rControlRegion, const Point& aPos, bool& rIsInside ) const { if( !EnableNativeWidget( *this ) ) return false; if ( !mpGraphics ) if ( !AcquireGraphics() ) return false; Point aWinOffs( mnOutOffX, mnOutOffY ); Rectangle screenRegion( rControlRegion ); screenRegion.Move( aWinOffs.X(), aWinOffs.Y()); return( mpGraphics->HitTestNativeControl(nType, nPart, screenRegion, Point( aPos.X() + mnOutOffX, aPos.Y() + mnOutOffY ), rIsInside, this ) ); } static boost::shared_ptr< ImplControlValue > TransformControlValue( const ImplControlValue& rVal, const OutputDevice& rDev ) { boost::shared_ptr< ImplControlValue > aResult; switch( rVal.getType() ) { case CTRL_SLIDER: { const SliderValue* pSlVal = static_cast<const SliderValue*>(&rVal); SliderValue* pNew = new SliderValue( *pSlVal ); aResult.reset( pNew ); pNew->maThumbRect = rDev.ImplLogicToDevicePixel( pSlVal->maThumbRect ); } break; case CTRL_SCROLLBAR: { const ScrollbarValue* pScVal = static_cast<const ScrollbarValue*>(&rVal); ScrollbarValue* pNew = new ScrollbarValue( *pScVal ); aResult.reset( pNew ); pNew->maThumbRect = rDev.ImplLogicToDevicePixel( pScVal->maThumbRect ); pNew->maButton1Rect = rDev.ImplLogicToDevicePixel( pScVal->maButton1Rect ); pNew->maButton2Rect = rDev.ImplLogicToDevicePixel( pScVal->maButton2Rect ); } break; case CTRL_SPINBUTTONS: { const SpinbuttonValue* pSpVal = static_cast<const SpinbuttonValue*>(&rVal); SpinbuttonValue* pNew = new SpinbuttonValue( *pSpVal ); aResult.reset( pNew ); pNew->maUpperRect = rDev.ImplLogicToDevicePixel( pSpVal->maUpperRect ); pNew->maLowerRect = rDev.ImplLogicToDevicePixel( pSpVal->maLowerRect ); } break; case CTRL_TOOLBAR: { const ToolbarValue* pTVal = static_cast<const ToolbarValue*>(&rVal); ToolbarValue* pNew = new ToolbarValue( *pTVal ); aResult.reset( pNew ); pNew->maGripRect = rDev.ImplLogicToDevicePixel( pTVal->maGripRect ); } break; case CTRL_TAB_ITEM: { const TabitemValue* pTIVal = static_cast<const TabitemValue*>(&rVal); TabitemValue* pNew = new TabitemValue( *pTIVal ); aResult.reset( pNew ); } break; case CTRL_MENUBAR: { const MenubarValue* pMVal = static_cast<const MenubarValue*>(&rVal); MenubarValue* pNew = new MenubarValue( *pMVal ); aResult.reset( pNew ); } break; case CTRL_PUSHBUTTON: { const PushButtonValue* pBVal = static_cast<const PushButtonValue*>(&rVal); PushButtonValue* pNew = new PushButtonValue( *pBVal ); aResult.reset( pNew ); } break; case CTRL_GENERIC: aResult.reset( new ImplControlValue( rVal ) ); break; case CTRL_MENU_POPUP: { const MenupopupValue* pMVal = static_cast<const MenupopupValue*>(&rVal); MenupopupValue* pNew = new MenupopupValue( *pMVal ); pNew->maItemRect = rDev.ImplLogicToDevicePixel( pMVal->maItemRect ); aResult.reset( pNew ); } break; default: OSL_FAIL( "unknown ImplControlValue type !" ); break; } return aResult; } bool OutputDevice::DrawNativeControl( ControlType nType, ControlPart nPart, const Rectangle& rControlRegion, ControlState nState, const ImplControlValue& aValue, const OUString& aCaption ) { if( !EnableNativeWidget( *this ) ) return false; // make sure the current clip region is initialized correctly if ( !mpGraphics ) if ( !AcquireGraphics() ) return false; if ( mbInitClipRegion ) InitClipRegion(); if ( mbOutputClipped ) return true; if ( mbInitLineColor ) InitLineColor(); if ( mbInitFillColor ) InitFillColor(); // Convert the coordinates from relative to Window-absolute, so we draw // in the correct place in platform code boost::shared_ptr< ImplControlValue > aScreenCtrlValue( TransformControlValue( aValue, *this ) ); Rectangle screenRegion( ImplLogicToDevicePixel( rControlRegion ) ); Region aTestRegion( GetActiveClipRegion() ); aTestRegion.Intersect( rControlRegion ); if (aTestRegion == Region(rControlRegion)) nState |= CTRL_CACHING_ALLOWED; // control is not clipped, caching allowed bool bRet = mpGraphics->DrawNativeControl(nType, nPart, screenRegion, nState, *aScreenCtrlValue, aCaption, this ); return bRet; } bool OutputDevice::GetNativeControlRegion( ControlType nType, ControlPart nPart, const Rectangle& rControlRegion, ControlState nState, const ImplControlValue& aValue, const OUString& aCaption, Rectangle &rNativeBoundingRegion, Rectangle &rNativeContentRegion ) const { if( !EnableNativeWidget( *this ) ) return false; if ( !mpGraphics ) if ( !AcquireGraphics() ) return false; // Convert the coordinates from relative to Window-absolute, so we draw // in the correct place in platform code boost::shared_ptr< ImplControlValue > aScreenCtrlValue( TransformControlValue( aValue, *this ) ); Rectangle screenRegion( ImplLogicToDevicePixel( rControlRegion ) ); bool bRet = mpGraphics->GetNativeControlRegion(nType, nPart, screenRegion, nState, *aScreenCtrlValue, aCaption, rNativeBoundingRegion, rNativeContentRegion, this ); if( bRet ) { // transform back native regions rNativeBoundingRegion = ImplDevicePixelToLogic( rNativeBoundingRegion ); rNativeContentRegion = ImplDevicePixelToLogic( rNativeContentRegion ); } return bRet; } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: salplug.cxx,v $ * * $Revision: 1.17 $ * * last change: $Author: rt $ $Date: 2005-10-19 15:33:22 $ * * 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 OSL_MODULE_H #include <osl/module.h> #endif #ifndef OSL_PROCESS_H #include <osl/process.h> #endif #ifndef RTL_STRING_HXX #include <rtl/ustrbuf.hxx> #endif #include <svunx.h> #include <prex.h> #include <X11/Xatom.h> #include <postx.h> #include <salinst.hxx> #include <saldata.hxx> #include <cstdio> #include <unistd.h> using namespace rtl; typedef SalInstance*(*salFactoryProc)( oslModule pModule); static oslModule pCloseModule = NULL; #define DESKTOP_NONE 0 #define DESKTOP_UNKNOWN 1 #define DESKTOP_GNOME 2 #define DESKTOP_KDE 3 #define DESKTOP_CDE 4 static const char * desktop_strings[5] = { "none", "unknown", "GNOME", "KDE", "CDE" }; static SalInstance* tryInstance( const OUString& rModuleBase ) { SalInstance* pInst = NULL; OUStringBuffer aModName( 128 ); aModName.appendAscii( SAL_DLLPREFIX"vclplug_" ); aModName.append( rModuleBase ); aModName.append( (sal_Int32)SUPD ); aModName.appendAscii( SAL_DLLPOSTFIX ); aModName.appendAscii( SAL_DLLEXTENSION ); OUString aModule = aModName.makeStringAndClear(); oslModule aMod = osl_loadModule( aModule.pData, SAL_LOADMODULE_DEFAULT ); if( aMod ) { OUString aSym( RTL_CONSTASCII_USTRINGPARAM( "create_SalInstance" ) ); salFactoryProc aProc = (salFactoryProc)osl_getSymbol( aMod, aSym.pData ); if( aProc ) { pInst = aProc( aMod ); #if OSL_DEBUG_LEVEL > 1 fprintf( stderr, "sal plugin %s produced instance %p\n", OUStringToOString( aModule, RTL_TEXTENCODING_ASCII_US ).getStr(), pInst ); #endif if( pInst ) { pCloseModule = aMod; GetSalData()->m_pPlugin = aMod; } else osl_unloadModule( aMod ); } else { #if OSL_DEBUG_LEVEL > 1 fprintf( stderr, "could not load symbol %s from shared object %s\n", OUStringToOString( aSym, RTL_TEXTENCODING_ASCII_US ).getStr(), OUStringToOString( aModule, RTL_TEXTENCODING_ASCII_US ).getStr() ); #endif osl_unloadModule( aMod ); } } #if OSL_DEBUG_LEVEL > 1 else fprintf( stderr, "could not load shared object %s\n", OUStringToOString( aModule, RTL_TEXTENCODING_ASCII_US ).getStr() ); #endif return pInst; } static bool is_gnome_desktop( Display* pDisplay ) { bool ret = false; // warning: these checks are coincidental, GNOME does not // explicitly advertise itself if ( NULL != getenv( "GNOME_DESKTOP_SESSION_ID" ) ) ret = true; if( ! ret ) { Atom nAtom1 = XInternAtom( pDisplay, "GNOME_SM_PROXY", True ); Atom nAtom2 = XInternAtom( pDisplay, "NAUTILUS_DESKTOP_WINDOW_ID", True ); if( nAtom1 || nAtom2 ) { int nProperties = 0; Atom* pProperties = XListProperties( pDisplay, DefaultRootWindow( pDisplay ), &nProperties ); if( pProperties && nProperties ) { for( int i = 0; i < nProperties; i++ ) if( pProperties[ i ] == nAtom1 || pProperties[ i ] == nAtom2 ) { ret = true; } XFree( pProperties ); } } } if( ! ret ) { Atom nUTFAtom = XInternAtom( pDisplay, "UTF8_STRING", True ); Atom nNetWMNameAtom = XInternAtom( pDisplay, "_NET_WM_NAME", True ); if( nUTFAtom && nNetWMNameAtom ) { // another, more expensive check: search for a gnome-panel XLIB_Window aRoot, aParent, *pChildren = NULL; unsigned int nChildren = 0; XQueryTree( pDisplay, DefaultRootWindow( pDisplay ), &aRoot, &aParent, &pChildren, &nChildren ); if( pChildren && nChildren ) { for( unsigned int i = 0; i < nChildren && ! ret; i++ ) { Atom nType = None; int nFormat = 0; unsigned long nItems = 0, nBytes = 0; unsigned char* pProp = NULL; XGetWindowProperty( pDisplay, pChildren[i], nNetWMNameAtom, 0, 8, False, nUTFAtom, &nType, &nFormat, &nItems, &nBytes, &pProp ); if( pProp && nType == nUTFAtom ) { OString aWMName( (sal_Char*)pProp ); if( aWMName.equalsIgnoreAsciiCase( "gnome-panel" ) ) ret = true; } if( pProp ) XFree( pProp ); } XFree( pChildren ); } } } return ret; } static bool bWasXError = false; static inline bool WasXError() { bool bRet = bWasXError; bWasXError = false; return bRet; } extern "C" { static int autodect_error_handler( Display*, XErrorEvent* ) { bWasXError = true; return 0; } typedef int(* XErrorHandler)(Display*,XErrorEvent*); } static OUString getNetWMName( Display* pDisplay ) { OUString aRet; Atom nWmCheck = XInternAtom( pDisplay, "_NET_SUPPORTING_WM_CHECK", True ); Atom nWmName = XInternAtom( pDisplay, "_NET_WM_NAME", True ); if( nWmName && nWmCheck ) { XLIB_Window aCheckWin = None; Atom aRealType = None; int nFormat = 8; unsigned long nItems = 0; unsigned long nBytesLeft = 0; unsigned char* pProperty = NULL; XGetWindowProperty( pDisplay, DefaultRootWindow( pDisplay ), nWmCheck, 0, 1, False, XA_WINDOW, &aRealType, &nFormat, &nItems, &nBytesLeft, &pProperty ); if( aRealType == XA_WINDOW && nFormat == 32 && nItems != 0 ) aCheckWin = *(XLIB_Window*)pProperty; if( pProperty ) { XFree( pProperty ); pProperty = NULL; } // see if that window really exists and has the check property set if( aCheckWin != None ) { // clear error flag WasXError(); // get the property XGetWindowProperty( pDisplay, aCheckWin, nWmCheck, 0, 1, False, XA_WINDOW, &aRealType, &nFormat, &nItems, &nBytesLeft, &pProperty ); if( ! WasXError() && aRealType == XA_WINDOW && nFormat == 32 && nItems != 0 && pProperty ) { if( aCheckWin == *(XLIB_Window*)pProperty ) { XFree( pProperty ); pProperty = NULL; XGetWindowProperty( pDisplay, aCheckWin, nWmName, 0, 256, False, AnyPropertyType, &aRealType, &nFormat, &nItems, &nBytesLeft, &pProperty ); if( !WasXError() && nItems != 0 && pProperty && *pProperty ) { if( aRealType == XA_STRING ) // some WM's use this although the should use UTF8_STRING { aRet = rtl::OStringToOUString( rtl::OString( (sal_Char*)pProperty ), RTL_TEXTENCODING_ISO_8859_1 ); } else aRet = rtl::OStringToOUString( rtl::OString( (sal_Char*)pProperty ), RTL_TEXTENCODING_UTF8 ); } } } if( pProperty ) { XFree( pProperty ); pProperty = NULL; } } } return aRet; } static bool is_kde_desktop( Display* pDisplay ) { if ( NULL != getenv( "KDE_FULL_SESSION" ) ) return true; // check for kwin rtl::OUString aWM = getNetWMName( pDisplay ); if( aWM.equalsIgnoreAsciiCaseAscii( "KWin" ) ) return true; return false; } static bool is_cde_desktop( Display* pDisplay ) { void* pLibrary = NULL; Atom nDtAtom = XInternAtom( pDisplay, "_DT_WM_READY", True ); OUString aPathName( RTL_CONSTASCII_USTRINGPARAM( "file:///usr/dt/lib/libDtSvc.so" ) ); if( nDtAtom && ( pLibrary = osl_loadModule( aPathName.pData, SAL_LOADMODULE_DEFAULT ) ) ) { osl_unloadModule( (oslModule*)pLibrary ); return true; } return false; } static const char * get_desktop_environment() { static const char *pRet = NULL; static const char *pOverride = getenv( "OOO_FORCE_DESKTOP" ); if ( pOverride && *pOverride ) { OString aOver( pOverride ); if ( aOver.equalsIgnoreAsciiCase( "cde" ) ) pRet = desktop_strings[DESKTOP_CDE]; if ( aOver.equalsIgnoreAsciiCase( "kde" ) ) pRet = desktop_strings[DESKTOP_KDE]; if ( aOver.equalsIgnoreAsciiCase( "gnome" ) ) pRet = desktop_strings[DESKTOP_GNOME]; if ( aOver.equalsIgnoreAsciiCase( "none" ) ) pRet = desktop_strings[DESKTOP_UNKNOWN]; } if ( NULL == pRet ) { // get display to connect to const char* pDisplayStr = getenv( "DISPLAY" ); int nParams = osl_getCommandArgCount(); OUString aParam; OString aBParm; for( int i = 0; i < nParams-1; i++ ) { osl_getCommandArg( i, &aParam.pData ); if( aParam.equalsAscii( "-display" ) || aParam.equalsAscii( "--display" ) ) { osl_getCommandArg( i+1, &aParam.pData ); aBParm = OUStringToOString( aParam, osl_getThreadTextEncoding() ); pDisplayStr = aBParm.getStr(); break; } } // no server at all if( ! pDisplayStr || !*pDisplayStr ) pRet = desktop_strings[DESKTOP_NONE]; else { Display* pDisplay = XOpenDisplay( pDisplayStr ); if( pDisplay ) { XErrorHandler pOldHdl = XSetErrorHandler( autodect_error_handler ); if ( is_kde_desktop( pDisplay ) ) pRet = desktop_strings[DESKTOP_KDE]; else if ( is_gnome_desktop( pDisplay ) ) pRet = desktop_strings[DESKTOP_GNOME]; else if ( is_cde_desktop( pDisplay ) ) pRet = desktop_strings[DESKTOP_CDE]; else pRet = desktop_strings[DESKTOP_UNKNOWN]; // set the default handler again XSetErrorHandler( pOldHdl ); XCloseDisplay( pDisplay ); } } } return pRet; } static const char* autodetect_plugin() { const char * desktop = get_desktop_environment(); const char * pRet = NULL; // no server at all: dummy plugin if ( desktop == desktop_strings[DESKTOP_NONE] ) pRet = "dummy"; else if ( desktop == desktop_strings[DESKTOP_GNOME] ) pRet = "gtk"; else if( desktop == desktop_strings[DESKTOP_KDE] ) pRet = "kde"; else pRet = "gen"; #if OSL_DEBUG_LEVEL > 1 fprintf( stderr, "plugin autodetection: %s\n", pRet ); #endif return pRet; } SalInstance *CreateSalInstance() { SalInstance* pInst = NULL; static const char* pUsePlugin = getenv( "SAL_USE_VCLPLUGIN" ); if( !(pUsePlugin && *pUsePlugin) ) pUsePlugin = autodetect_plugin(); if( pUsePlugin && *pUsePlugin ) pInst = tryInstance( OUString::createFromAscii( pUsePlugin ) ); // fallback to gen if( ! pInst ) pInst = tryInstance( OUString( RTL_CONSTASCII_USTRINGPARAM( "gen" ) ) ); if( ! pInst ) { fprintf( stderr, "no suitable windowing system found, exiting.\n" ); _exit( 1 ); } // acquire SolarMutex pInst->AcquireYieldMutex( 1 ); return pInst; } void DestroySalInstance( SalInstance *pInst ) { // release SolarMutex pInst->ReleaseYieldMutex(); delete pInst; if( pCloseModule ) osl_unloadModule( pCloseModule ); } void InitSalData() { } void DeInitSalData() { } void InitSalMain() { } void DeInitSalMain() { } void SalAbort( const XubString& rErrorText ) { if( !rErrorText.Len() ) fprintf( stderr, "Application Error" ); else fprintf( stderr, ByteString( rErrorText, gsl_getSystemTextEncoding() ).GetBuffer() ); abort(); } const OUString& SalGetDesktopEnvironment() { static OUString aRet = OStringToOUString(OString(get_desktop_environment()), RTL_TEXTENCODING_ASCII_US); return aRet; } <commit_msg>#i54458#, #i10000#: Correct my last changes<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: salplug.cxx,v $ * * $Revision: 1.18 $ * * last change: $Author: rt $ $Date: 2005-10-27 07:59:29 $ * * 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 OSL_MODULE_H #include <osl/module.h> #endif #ifndef OSL_PROCESS_H #include <osl/process.h> #endif #ifndef RTL_STRING_HXX #include <rtl/ustrbuf.hxx> #endif #include <svunx.h> #include <prex.h> #include <X11/Xatom.h> #include <postx.h> #include <salinst.hxx> #include <saldata.hxx> #include <cstdio> #include <unistd.h> using namespace rtl; typedef SalInstance*(*salFactoryProc)( oslModule pModule); static oslModule pCloseModule = NULL; #define DESKTOP_NONE 0 #define DESKTOP_UNKNOWN 1 #define DESKTOP_GNOME 2 #define DESKTOP_KDE 3 #define DESKTOP_CDE 4 static const char * desktop_strings[5] = { "none", "unknown", "GNOME", "KDE", "CDE" }; static SalInstance* tryInstance( const OUString& rModuleBase ) { SalInstance* pInst = NULL; OUStringBuffer aModName( 128 ); aModName.appendAscii( SAL_DLLPREFIX"vclplug_" ); aModName.append( rModuleBase ); aModName.append( (sal_Int32)SUPD ); aModName.appendAscii( SAL_DLLPOSTFIX ); aModName.appendAscii( SAL_DLLEXTENSION ); OUString aModule = aModName.makeStringAndClear(); oslModule aMod = osl_loadModule( aModule.pData, SAL_LOADMODULE_DEFAULT ); if( aMod ) { OUString aSym( RTL_CONSTASCII_USTRINGPARAM( "create_SalInstance" ) ); salFactoryProc aProc = (salFactoryProc)osl_getSymbol( aMod, aSym.pData ); if( aProc ) { pInst = aProc( aMod ); #if OSL_DEBUG_LEVEL > 1 fprintf( stderr, "sal plugin %s produced instance %p\n", OUStringToOString( aModule, RTL_TEXTENCODING_ASCII_US ).getStr(), pInst ); #endif if( pInst ) { pCloseModule = aMod; GetSalData()->m_pPlugin = aMod; } else osl_unloadModule( aMod ); } else { #if OSL_DEBUG_LEVEL > 1 fprintf( stderr, "could not load symbol %s from shared object %s\n", OUStringToOString( aSym, RTL_TEXTENCODING_ASCII_US ).getStr(), OUStringToOString( aModule, RTL_TEXTENCODING_ASCII_US ).getStr() ); #endif osl_unloadModule( aMod ); } } #if OSL_DEBUG_LEVEL > 1 else fprintf( stderr, "could not load shared object %s\n", OUStringToOString( aModule, RTL_TEXTENCODING_ASCII_US ).getStr() ); #endif return pInst; } static bool is_gnome_desktop( Display* pDisplay ) { bool ret = false; // warning: these checks are coincidental, GNOME does not // explicitly advertise itself if ( NULL != getenv( "GNOME_DESKTOP_SESSION_ID" ) ) ret = true; if( ! ret ) { Atom nAtom1 = XInternAtom( pDisplay, "GNOME_SM_PROXY", True ); Atom nAtom2 = XInternAtom( pDisplay, "NAUTILUS_DESKTOP_WINDOW_ID", True ); if( nAtom1 || nAtom2 ) { int nProperties = 0; Atom* pProperties = XListProperties( pDisplay, DefaultRootWindow( pDisplay ), &nProperties ); if( pProperties && nProperties ) { for( int i = 0; i < nProperties; i++ ) if( pProperties[ i ] == nAtom1 || pProperties[ i ] == nAtom2 ) { ret = true; } XFree( pProperties ); } } } if( ! ret ) { Atom nUTFAtom = XInternAtom( pDisplay, "UTF8_STRING", True ); Atom nNetWMNameAtom = XInternAtom( pDisplay, "_NET_WM_NAME", True ); if( nUTFAtom && nNetWMNameAtom ) { // another, more expensive check: search for a gnome-panel XLIB_Window aRoot, aParent, *pChildren = NULL; unsigned int nChildren = 0; XQueryTree( pDisplay, DefaultRootWindow( pDisplay ), &aRoot, &aParent, &pChildren, &nChildren ); if( pChildren && nChildren ) { for( unsigned int i = 0; i < nChildren && ! ret; i++ ) { Atom nType = None; int nFormat = 0; unsigned long nItems = 0, nBytes = 0; unsigned char* pProp = NULL; XGetWindowProperty( pDisplay, pChildren[i], nNetWMNameAtom, 0, 8, False, nUTFAtom, &nType, &nFormat, &nItems, &nBytes, &pProp ); if( pProp && nType == nUTFAtom ) { OString aWMName( (sal_Char*)pProp ); if( aWMName.equalsIgnoreAsciiCase( "gnome-panel" ) ) ret = true; } if( pProp ) XFree( pProp ); } XFree( pChildren ); } } } return ret; } static bool bWasXError = false; static inline bool WasXError() { bool bRet = bWasXError; bWasXError = false; return bRet; } extern "C" { static int autodect_error_handler( Display*, XErrorEvent* ) { bWasXError = true; return 0; } typedef int(* XErrorHandler)(Display*,XErrorEvent*); } static OUString getNetWMName( Display* pDisplay ) { OUString aRet; Atom nWmCheck = XInternAtom( pDisplay, "_NET_SUPPORTING_WM_CHECK", True ); Atom nWmName = XInternAtom( pDisplay, "_NET_WM_NAME", True ); if( nWmName && nWmCheck ) { XLIB_Window aCheckWin = None; Atom aRealType = None; int nFormat = 8; unsigned long nItems = 0; unsigned long nBytesLeft = 0; unsigned char* pProperty = NULL; XGetWindowProperty( pDisplay, DefaultRootWindow( pDisplay ), nWmCheck, 0, 1, False, XA_WINDOW, &aRealType, &nFormat, &nItems, &nBytesLeft, &pProperty ); if( aRealType == XA_WINDOW && nFormat == 32 && nItems != 0 ) aCheckWin = *(XLIB_Window*)pProperty; if( pProperty ) { XFree( pProperty ); pProperty = NULL; } // see if that window really exists and has the check property set if( aCheckWin != None ) { // clear error flag WasXError(); // get the property XGetWindowProperty( pDisplay, aCheckWin, nWmCheck, 0, 1, False, XA_WINDOW, &aRealType, &nFormat, &nItems, &nBytesLeft, &pProperty ); if( ! WasXError() && aRealType == XA_WINDOW && nFormat == 32 && nItems != 0 && pProperty ) { if( aCheckWin == *(XLIB_Window*)pProperty ) { XFree( pProperty ); pProperty = NULL; XGetWindowProperty( pDisplay, aCheckWin, nWmName, 0, 256, False, AnyPropertyType, &aRealType, &nFormat, &nItems, &nBytesLeft, &pProperty ); if( !WasXError() && nItems != 0 && pProperty && *pProperty ) { if( aRealType == XA_STRING ) // some WM's use this although the should use UTF8_STRING { aRet = rtl::OStringToOUString( rtl::OString( (sal_Char*)pProperty ), RTL_TEXTENCODING_ISO_8859_1 ); } else aRet = rtl::OStringToOUString( rtl::OString( (sal_Char*)pProperty ), RTL_TEXTENCODING_UTF8 ); } } } if( pProperty ) { XFree( pProperty ); pProperty = NULL; } } } return aRet; } static bool is_kde_desktop( Display* pDisplay ) { if ( NULL != getenv( "KDE_FULL_SESSION" ) ) return true; // check for kwin rtl::OUString aWM = getNetWMName( pDisplay ); if( aWM.equalsIgnoreAsciiCaseAscii( "KWin" ) ) return true; return false; } static bool is_cde_desktop( Display* pDisplay ) { void* pLibrary = NULL; Atom nDtAtom = XInternAtom( pDisplay, "_DT_WM_READY", True ); OUString aPathName( RTL_CONSTASCII_USTRINGPARAM( "file:///usr/dt/lib/libDtSvc.so" ) ); if( nDtAtom && ( pLibrary = osl_loadModule( aPathName.pData, SAL_LOADMODULE_DEFAULT ) ) ) { osl_unloadModule( (oslModule)pLibrary ); return true; } return false; } static const char * get_desktop_environment() { static const char *pRet = NULL; static const char *pOverride = getenv( "OOO_FORCE_DESKTOP" ); if ( pOverride && *pOverride ) { OString aOver( pOverride ); if ( aOver.equalsIgnoreAsciiCase( "cde" ) ) pRet = desktop_strings[DESKTOP_CDE]; if ( aOver.equalsIgnoreAsciiCase( "kde" ) ) pRet = desktop_strings[DESKTOP_KDE]; if ( aOver.equalsIgnoreAsciiCase( "gnome" ) ) pRet = desktop_strings[DESKTOP_GNOME]; if ( aOver.equalsIgnoreAsciiCase( "none" ) ) pRet = desktop_strings[DESKTOP_UNKNOWN]; } if ( NULL == pRet ) { // get display to connect to const char* pDisplayStr = getenv( "DISPLAY" ); int nParams = osl_getCommandArgCount(); OUString aParam; OString aBParm; for( int i = 0; i < nParams-1; i++ ) { osl_getCommandArg( i, &aParam.pData ); if( aParam.equalsAscii( "-display" ) || aParam.equalsAscii( "--display" ) ) { osl_getCommandArg( i+1, &aParam.pData ); aBParm = OUStringToOString( aParam, osl_getThreadTextEncoding() ); pDisplayStr = aBParm.getStr(); break; } } // no server at all if( ! pDisplayStr || !*pDisplayStr ) pRet = desktop_strings[DESKTOP_NONE]; else { Display* pDisplay = XOpenDisplay( pDisplayStr ); if( pDisplay ) { XErrorHandler pOldHdl = XSetErrorHandler( autodect_error_handler ); if ( is_kde_desktop( pDisplay ) ) pRet = desktop_strings[DESKTOP_KDE]; else if ( is_gnome_desktop( pDisplay ) ) pRet = desktop_strings[DESKTOP_GNOME]; else if ( is_cde_desktop( pDisplay ) ) pRet = desktop_strings[DESKTOP_CDE]; else pRet = desktop_strings[DESKTOP_UNKNOWN]; // set the default handler again XSetErrorHandler( pOldHdl ); XCloseDisplay( pDisplay ); } } } return pRet; } static const char* autodetect_plugin() { const char * desktop = get_desktop_environment(); const char * pRet = NULL; // no server at all: dummy plugin if ( desktop == desktop_strings[DESKTOP_NONE] ) pRet = "dummy"; else if ( desktop == desktop_strings[DESKTOP_GNOME] ) pRet = "gtk"; else if( desktop == desktop_strings[DESKTOP_KDE] ) pRet = "kde"; else pRet = "gen"; #if OSL_DEBUG_LEVEL > 1 fprintf( stderr, "plugin autodetection: %s\n", pRet ); #endif return pRet; } SalInstance *CreateSalInstance() { SalInstance* pInst = NULL; static const char* pUsePlugin = getenv( "SAL_USE_VCLPLUGIN" ); if( !(pUsePlugin && *pUsePlugin) ) pUsePlugin = autodetect_plugin(); if( pUsePlugin && *pUsePlugin ) pInst = tryInstance( OUString::createFromAscii( pUsePlugin ) ); // fallback to gen if( ! pInst ) pInst = tryInstance( OUString( RTL_CONSTASCII_USTRINGPARAM( "gen" ) ) ); if( ! pInst ) { fprintf( stderr, "no suitable windowing system found, exiting.\n" ); _exit( 1 ); } // acquire SolarMutex pInst->AcquireYieldMutex( 1 ); return pInst; } void DestroySalInstance( SalInstance *pInst ) { // release SolarMutex pInst->ReleaseYieldMutex(); delete pInst; if( pCloseModule ) osl_unloadModule( pCloseModule ); } void InitSalData() { } void DeInitSalData() { } void InitSalMain() { } void DeInitSalMain() { } void SalAbort( const XubString& rErrorText ) { if( !rErrorText.Len() ) fprintf( stderr, "Application Error" ); else fprintf( stderr, ByteString( rErrorText, gsl_getSystemTextEncoding() ).GetBuffer() ); abort(); } const OUString& SalGetDesktopEnvironment() { static OUString aRet = OStringToOUString(OString(get_desktop_environment()), RTL_TEXTENCODING_ASCII_US); return aRet; } <|endoftext|>
<commit_before>// This file is part of the HörTech Open Master Hearing Aid (openMHA) // Copyright © 2007 2009 2010 2013 2014 2015 2018 2019 2020 HörTech gGmbH // // openMHA 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, version 3 of the License. // // openMHA 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, version 3 for more details. // // You should have received a copy of the GNU Affero General Public License, // version 3 along with openMHA. If not, see <http://www.gnu.org/licenses/>. #include "mha_plugin.hh" #include "mha_signal.hh" #include "mha_events.h" #include "mha_defs.h" #include "mha_filter.hh" namespace mconv { /**\internal * class implements plugin for partitioned convolution. * A matrix of impulse responses, filtering n input channels to m output * channels, is supported. */ class MConv : public MHAPlugin::plugin_t<MHAFilter::partitioned_convolution_t> { public: /** Plugin constructor. * @param iac handle and function pointers for algorithm communication * @param chainname Name of processing chain * @param algoname The name by which the chain refers to this algorithm */ MConv(const algo_comm_t & iac, const std::string & chainname, const std::string & algoname); /** Prepare this plugin for processing. * @param mhaconfig Configuration for this plugin (Input/Output parameter) * Sample rate, fragment size, number of channels are detailed here. */ void prepare(mhaconfig_t & mhaconfig); void release(); mha_wave_t* process(mha_wave_t*); private: /** Update is needed only once, since this plugin allows only * change of irs after prepare(). */ void update(); /** This function updates the irs without allowing a change * of its size after prepare(). */ void update_irs(); /** Number of output channels to produce */ MHAParser::int_t nchannels_out; /** Vector of input channel indices. * Each element in this vector identifies the input channel to * which to apply the corresponding impulse response in irs. */ MHAParser::vint_t inch; /** Vector of output channel indices. * Each element in this vector identifies the output channel to * which the result of filtering with the corresponding impulse * response in irs is mixed. */ MHAParser::vint_t outch; /** Impulse responses, one per row. For each row, the * corresponding element of inch identifies the source channel, * and the corresponding element of outch identifies the target * channel. */ MHAParser::mfloat_t irs; /** Number of input channels, set during prepare. */ unsigned int nchannels_in; /** Fragsize, set during prepare, is used as the partition length in the * partitioned convolution */ unsigned int fragsize; MHAEvents::patchbay_t<MConv> patchbay; }; MConv::MConv(const algo_comm_t & iac, const std::string & chainname, const std::string & algoname) : MHAPlugin::plugin_t<MHAFilter::partitioned_convolution_t> ("FFT based FIR filter using partitioned convolution\n" " This plugin filters its input channels using partitioned fast\n" "convolution. The variables in this plugin define a sparse matrix of\n" "impulse responses. The number of elements in the vectors inch and\n" "outch and the number of rows in irs have to be equal.\n", iac), nchannels_out("Number of output channels to produce", "1", "[0,["), inch("Vector of input channel indices.\n" " Each element in this vector identifies the input channel to\n" "which to apply the corresponding impulse response in irs.", "[0]", "[0,["), outch("Vector of output channel indices.\n" " Each element in this vector identifies the output channel to\n" "which the result of filtering with the corresponding impulse\n" "response in irs is mixed.", "[0]", "[0,["), irs("Impulse responses, one per row. For each row, the corresponding\n" "element of inch identifies the source channel, and the\n" "corresponding element of outch identifies the target channel.", "[[1]]"), nchannels_in(0), fragsize(0) { insert_item("nchannels_out", &nchannels_out); insert_item("inch", &inch); insert_item("outch", &outch); insert_item("irs", &irs); patchbay.connect(&irs.writeaccess, this, &MConv::update_irs); } void MConv::prepare(mhaconfig_t & mhaconfig) { if (mhaconfig.domain != MHA_WAVEFORM) throw MHA_ErrorMsg("Plugin supports waveform processing only."); nchannels_in = mhaconfig.channels; mhaconfig.channels = nchannels_out.data; fragsize = mhaconfig.fragsize; update(); inch.setlock(true); outch.setlock(true); nchannels_out.setlock(true); } void MConv::release() { nchannels_out.setlock(false); inch.setlock(false); outch.setlock(false); } void MConv::update() { if (irs.data.size() != inch.data.size() || irs.data.size() != outch.data.size()) throw MHA_Error(__FILE__, __LINE__, "Sizes of irs (%zu), inch (%zu), and outch (%zu) do not match", irs.data.size(), inch.data.size(), outch.data.size()); MHAFilter::transfer_function_t tf; MHAFilter::transfer_matrix_t tm; for (size_t index = 0; index < irs.data.size(); ++index) { if (inch.data[index] < 0 || inch.data[index] >= (int)nchannels_in) throw MHA_Error(__FILE__,__LINE__, "Source channel index inch[%d]=%d is out of range", int(index), inch.data[index]); tf.source_channel_index = inch.data[index]; if (outch.data[index] < 0 || outch.data[index] >= nchannels_out.data) throw MHA_Error(__FILE__,__LINE__, "Target channel index outch[%d]=%d is out of range", int(index), outch.data[index]); tf.target_channel_index = outch.data[index]; tf.impulse_response = irs.data[index]; tm.push_back(tf); } if (is_prepared()) push_config(new MHAFilter::partitioned_convolution_t(fragsize, nchannels_in, nchannels_out.data, tm)); } void MConv::update_irs() { if (!is_prepared()) return; if (irs.data.size() != inch.data.size() || irs.data.size() != outch.data.size()) throw MHA_Error(__FILE__, __LINE__, "Sizes of irs (%zu), inch (%zu), and outch (%zu) do not match", irs.data.size(), inch.data.size(), outch.data.size()); MHAFilter::transfer_function_t tf; MHAFilter::transfer_matrix_t tm; for (size_t index = 0; index < irs.data.size(); ++index) { tf.source_channel_index = inch.data[index]; tf.target_channel_index = outch.data[index]; tf.impulse_response = irs.data[index]; tm.push_back(tf); } push_config(new MHAFilter::partitioned_convolution_t(fragsize, nchannels_in, nchannels_out.data, tm)); } mha_wave_t* MConv::process(mha_wave_t * s_in) { poll_config(); mha_wave_t * s_out = cfg->process(s_in); return s_out; } } MHAPLUGIN_CALLBACKS(mconv,mconv::MConv, wave, wave) MHAPLUGIN_DOCUMENTATION(mconv, "filter", "The plugin {\\em mconv} performs partitioned convolution, using a" " sparse matrix of impulse responses.\n\n" " The partition size used for the partitioned convolution is equal to" " fragsize, the number of samples per channel in one block of audio. " " The impulse responses are separated into partitions, and each partition" " is applied with the appropriate delay. Each partition is applied using the" "overlap-save method. The FFT length used is 2*fragsize." "For efficiency reasons, fragsize should be a power of two.\n\n" " Partitioned convolution is used to reduce the" " overall algorithmic delay of the convolution with a long impulse response." " The overall computational cost of using partitioned convolution is higher" " when compared to convolving the complete impulse response in a single overlap-save" " operation, because longer FFTs are more efficient.\n\n" " This implementation discards impulse response partitions where the coefficients are all zero." ) // Local Variables: // compile-command: "make" // c-basic-offset: 4 // indent-tabs-mode: nil // coding: utf-8-unix // End: <commit_msg>Remove questionable statements about partitioned convolution<commit_after>// This file is part of the HörTech Open Master Hearing Aid (openMHA) // Copyright © 2007 2009 2010 2013 2014 2015 2018 2019 2020 HörTech gGmbH // // openMHA 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, version 3 of the License. // // openMHA 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, version 3 for more details. // // You should have received a copy of the GNU Affero General Public License, // version 3 along with openMHA. If not, see <http://www.gnu.org/licenses/>. #include "mha_plugin.hh" #include "mha_signal.hh" #include "mha_events.h" #include "mha_defs.h" #include "mha_filter.hh" namespace mconv { /**\internal * class implements plugin for partitioned convolution. * A matrix of impulse responses, filtering n input channels to m output * channels, is supported. */ class MConv : public MHAPlugin::plugin_t<MHAFilter::partitioned_convolution_t> { public: /** Plugin constructor. * @param iac handle and function pointers for algorithm communication * @param chainname Name of processing chain * @param algoname The name by which the chain refers to this algorithm */ MConv(const algo_comm_t & iac, const std::string & chainname, const std::string & algoname); /** Prepare this plugin for processing. * @param mhaconfig Configuration for this plugin (Input/Output parameter) * Sample rate, fragment size, number of channels are detailed here. */ void prepare(mhaconfig_t & mhaconfig); void release(); mha_wave_t* process(mha_wave_t*); private: /** Update is needed only once, since this plugin allows only * change of irs after prepare(). */ void update(); /** This function updates the irs without allowing a change * of its size after prepare(). */ void update_irs(); /** Number of output channels to produce */ MHAParser::int_t nchannels_out; /** Vector of input channel indices. * Each element in this vector identifies the input channel to * which to apply the corresponding impulse response in irs. */ MHAParser::vint_t inch; /** Vector of output channel indices. * Each element in this vector identifies the output channel to * which the result of filtering with the corresponding impulse * response in irs is mixed. */ MHAParser::vint_t outch; /** Impulse responses, one per row. For each row, the * corresponding element of inch identifies the source channel, * and the corresponding element of outch identifies the target * channel. */ MHAParser::mfloat_t irs; /** Number of input channels, set during prepare. */ unsigned int nchannels_in; /** Fragsize, set during prepare, is used as the partition length in the * partitioned convolution */ unsigned int fragsize; MHAEvents::patchbay_t<MConv> patchbay; }; MConv::MConv(const algo_comm_t & iac, const std::string & chainname, const std::string & algoname) : MHAPlugin::plugin_t<MHAFilter::partitioned_convolution_t> ("FFT based FIR filter using partitioned convolution\n" " This plugin filters its input channels using partitioned fast\n" "convolution. The variables in this plugin define a sparse matrix of\n" "impulse responses. The number of elements in the vectors inch and\n" "outch and the number of rows in irs have to be equal.\n", iac), nchannels_out("Number of output channels to produce", "1", "[0,["), inch("Vector of input channel indices.\n" " Each element in this vector identifies the input channel to\n" "which to apply the corresponding impulse response in irs.", "[0]", "[0,["), outch("Vector of output channel indices.\n" " Each element in this vector identifies the output channel to\n" "which the result of filtering with the corresponding impulse\n" "response in irs is mixed.", "[0]", "[0,["), irs("Impulse responses, one per row. For each row, the corresponding\n" "element of inch identifies the source channel, and the\n" "corresponding element of outch identifies the target channel.", "[[1]]"), nchannels_in(0), fragsize(0) { insert_item("nchannels_out", &nchannels_out); insert_item("inch", &inch); insert_item("outch", &outch); insert_item("irs", &irs); patchbay.connect(&irs.writeaccess, this, &MConv::update_irs); } void MConv::prepare(mhaconfig_t & mhaconfig) { if (mhaconfig.domain != MHA_WAVEFORM) throw MHA_ErrorMsg("Plugin supports waveform processing only."); nchannels_in = mhaconfig.channels; mhaconfig.channels = nchannels_out.data; fragsize = mhaconfig.fragsize; update(); inch.setlock(true); outch.setlock(true); nchannels_out.setlock(true); } void MConv::release() { nchannels_out.setlock(false); inch.setlock(false); outch.setlock(false); } void MConv::update() { if (irs.data.size() != inch.data.size() || irs.data.size() != outch.data.size()) throw MHA_Error(__FILE__, __LINE__, "Sizes of irs (%zu), inch (%zu), and outch (%zu) do not match", irs.data.size(), inch.data.size(), outch.data.size()); MHAFilter::transfer_function_t tf; MHAFilter::transfer_matrix_t tm; for (size_t index = 0; index < irs.data.size(); ++index) { if (inch.data[index] < 0 || inch.data[index] >= (int)nchannels_in) throw MHA_Error(__FILE__,__LINE__, "Source channel index inch[%d]=%d is out of range", int(index), inch.data[index]); tf.source_channel_index = inch.data[index]; if (outch.data[index] < 0 || outch.data[index] >= nchannels_out.data) throw MHA_Error(__FILE__,__LINE__, "Target channel index outch[%d]=%d is out of range", int(index), outch.data[index]); tf.target_channel_index = outch.data[index]; tf.impulse_response = irs.data[index]; tm.push_back(tf); } if (is_prepared()) push_config(new MHAFilter::partitioned_convolution_t(fragsize, nchannels_in, nchannels_out.data, tm)); } void MConv::update_irs() { if (!is_prepared()) return; if (irs.data.size() != inch.data.size() || irs.data.size() != outch.data.size()) throw MHA_Error(__FILE__, __LINE__, "Sizes of irs (%zu), inch (%zu), and outch (%zu) do not match", irs.data.size(), inch.data.size(), outch.data.size()); MHAFilter::transfer_function_t tf; MHAFilter::transfer_matrix_t tm; for (size_t index = 0; index < irs.data.size(); ++index) { tf.source_channel_index = inch.data[index]; tf.target_channel_index = outch.data[index]; tf.impulse_response = irs.data[index]; tm.push_back(tf); } push_config(new MHAFilter::partitioned_convolution_t(fragsize, nchannels_in, nchannels_out.data, tm)); } mha_wave_t* MConv::process(mha_wave_t * s_in) { poll_config(); mha_wave_t * s_out = cfg->process(s_in); return s_out; } } MHAPLUGIN_CALLBACKS(mconv,mconv::MConv, wave, wave) MHAPLUGIN_DOCUMENTATION(mconv, "filter", "The plugin {\\em mconv} performs partitioned convolution, using a" " sparse matrix of impulse responses.\n\n" " The partition size used for the partitioned convolution is equal to" " fragsize, the number of samples per channel in one block of audio. " " The impulse responses are separated into partitions, and each partition" " is applied with the appropriate delay. Each partition is applied using the" "overlap-save method. The FFT length used is 2*fragsize." "For efficiency reasons, fragsize should be a power of two.\n\n" " This implementation discards impulse response partitions where the coefficients are all zero." ) // Local Variables: // compile-command: "make" // c-basic-offset: 4 // indent-tabs-mode: nil // coding: utf-8-unix // End: <|endoftext|>
<commit_before>// The MIT License (MIT) // Copyright (c) 2013 lailongwei<lailongwei@126.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #include "llbc/common/Export.h" #include "llbc/common/BeforeIncl.h" #include "llbc/core/time/Time.h" #include "llbc/core/log/LogData.h" #include "llbc/core/log/LogFormattingInfo.h" #include "llbc/core/log/LogTimeToken.h" __LLBC_NS_BEGIN LLBC_LogTimeToken::LLBC_LogTimeToken() : _lastFmtTime(0) , _cacheLen(0) , _fmtCache("") { } LLBC_LogTimeToken::~LLBC_LogTimeToken() { } int LLBC_LogTimeToken::Initialize(LLBC_LogFormattingInfo *formatter, const LLBC_String &str) { SetFormatter(formatter); return LLBC_OK; } int LLBC_LogTimeToken::GetType() const { return LLBC_LogTokenType::TimeToken; } void LLBC_LogTimeToken::Format(const LLBC_LogData &data, LLBC_String &formattedData) const { // Format non millisecond part. int index = static_cast<int>(formattedData.size()); time_t timeInSecond = static_cast<time_t>(data.logTime / 1000); if (timeInSecond != _lastFmtTime) { struct tm timeStruct; #if LLBC_TARGET_PLATFORM_WIN32 localtime_s(&timeStruct, &timeInSecond); #else localtime_r(&timeInSecond, &timeStruct); #endif _lastFmtTime = timeInSecond; _cacheLen = strftime(_fmtCache, sizeof(_fmtCache), "%y-%m-%d %H:%M:%S.", &timeStruct); } formattedData.append(_fmtCache, _cacheLen); // Format millisecond part. formattedData.append_format("%03llu", data.logTime % 1000); LLBC_LogFormattingInfo *formatter = GetFormatter(); formatter->Format(formattedData, index); } __LLBC_NS_END #include "llbc/common/AfterIncl.h" <commit_msg>Linux平台编译错误fix<commit_after>// The MIT License (MIT) // Copyright (c) 2013 lailongwei<lailongwei@126.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #include "llbc/common/Export.h" #include "llbc/common/BeforeIncl.h" #include "llbc/core/time/Time.h" #include "llbc/core/log/LogData.h" #include "llbc/core/log/LogFormattingInfo.h" #include "llbc/core/log/LogTimeToken.h" __LLBC_NS_BEGIN LLBC_LogTimeToken::LLBC_LogTimeToken() : _lastFmtTime(0) , _cacheLen(0) , _fmtCache{} { } LLBC_LogTimeToken::~LLBC_LogTimeToken() { } int LLBC_LogTimeToken::Initialize(LLBC_LogFormattingInfo *formatter, const LLBC_String &str) { SetFormatter(formatter); return LLBC_OK; } int LLBC_LogTimeToken::GetType() const { return LLBC_LogTokenType::TimeToken; } void LLBC_LogTimeToken::Format(const LLBC_LogData &data, LLBC_String &formattedData) const { // Format non millisecond part. int index = static_cast<int>(formattedData.size()); time_t timeInSecond = static_cast<time_t>(data.logTime / 1000); if (timeInSecond != _lastFmtTime) { struct tm timeStruct; #if LLBC_TARGET_PLATFORM_WIN32 localtime_s(&timeStruct, &timeInSecond); #else localtime_r(&timeInSecond, &timeStruct); #endif _lastFmtTime = timeInSecond; _cacheLen = strftime(_fmtCache, sizeof(_fmtCache), "%y-%m-%d %H:%M:%S.", &timeStruct); } formattedData.append(_fmtCache, _cacheLen); // Format millisecond part. formattedData.append_format("%03llu", data.logTime % 1000); LLBC_LogFormattingInfo *formatter = GetFormatter(); formatter->Format(formattedData, index); } __LLBC_NS_END #include "llbc/common/AfterIncl.h" <|endoftext|>
<commit_before><commit_msg>implementation of demo_generator<commit_after>/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <filesystem> #include <fstream> #include "../src/proto_value.h" #include "../src/proto_parser.h" #include "proto/event_predicate.pb.h" using ::wireless_android_play_analytics::ProtoValue; using ::wireless_android_play_analytics::MessageValue; using ::wireless_android_play_analytics::PrimitiveValue; using ::wireless_android_play_analytics::EventPredicate; using ::wireless_android_play_analytics::ProtoParser; namespace { std::string Generate(MessageValue* message) { const std::vector<ProtoValue*>& message_fields = message->GetFieldsMutable(); absl::variant<double, float, int, unsigned int, int64_t, uint64_t, bool, const google::protobuf::EnumValueDescriptor*, std::string> val; // Generate random int_comparator. MessageValue* event_matcher = static_cast<MessageValue*>(message_fields[0]); if (rand() % 2) { std::unique_ptr<ProtoValue> int_comparator = absl::make_unique<PrimitiveValue>("int_comparator", 1, 8); PrimitiveValue* int_comparator_ptr = static_cast<PrimitiveValue*>(int_comparator.get()); // Generate comment if (rand() % 2) { int_comparator_ptr->SetCommentBehindField("# randomly generated comment"); } std::vector<std::string> comments_above_field; int count = 0; while(rand() % 2) { comments_above_field.push_back("# randomly generated comment " + std::to_string(count++)); } int_comparator_ptr->SetCommentAboveField(comments_above_field); int input = rand() % 1000; val = input; int_comparator_ptr->SetVal(val); event_matcher->AddField(std::move(int_comparator)); } // Randomly erase leaf_ui_predicates. MessageValue* ui_element_path_predicate = static_cast<MessageValue*>( message_fields[2]); if (rand() % 2) { ui_element_path_predicate->DeleteField(2); } if (rand() % 2) { ui_element_path_predicate->DeleteField(1); } return message->PrintToTextProto(); } } // namespace int main() { std::ifstream ifs; std::string text_proto; EventPredicate event_predicate; ifs.open("demo/proto_texts/original_proto_text.txt"); assert(ifs.good()); while (ifs.good()) { std::string tmp; std::getline(ifs, tmp); text_proto += tmp + "\n"; } ProtoParser parser(text_proto); for(int i = 0; i < 10; ++i) { std::unique_ptr<ProtoValue> message = parser.Create(event_predicate); std::ofstream outs; outs.open("demo/proto_texts/proto_text(" + std::to_string(i) +").txt"); outs << Generate(static_cast<MessageValue*>(message.get())); } return 0; }<|endoftext|>
<commit_before><commit_msg>Re-enable optimal bloom on Intel GPUs.<commit_after><|endoftext|>
<commit_before>#include "rosplan_planning_system/PlannerInterface/LPGPlannerInterface.h" namespace KCL_rosplan { /*-------------*/ /* constructor */ /*-------------*/ LPGPlannerInterface::LPGPlannerInterface(ros::NodeHandle& nh) { node_handle = &nh; plan_server = new actionlib::SimpleActionServer<rosplan_dispatch_msgs::PlanAction>((*node_handle), "start_planning", boost::bind(&PlannerInterface::runPlanningServerAction, this, _1), false); // publishing raw planner output std::string plannerTopic = "planner_output"; node_handle->getParam("planner_topic", plannerTopic); plan_publisher = node_handle->advertise<std_msgs::String>(plannerTopic, 1, true); // start planning action server plan_server->start(); } LPGPlannerInterface::~LPGPlannerInterface() { delete plan_server; } /** * Runs external commands */ std::string LPGPlannerInterface::runCommand(std::string cmd) { std::string data; FILE *stream; char buffer[1000]; stream = popen(cmd.c_str(), "r"); while ( fgets(buffer, 1000, stream) != NULL ) data.append(buffer); pclose(stream); return data; } /*------------------*/ /* Plan and process */ /*------------------*/ /** * passes the problem to the Planner; the plan to post-processing. */ bool LPGPlannerInterface::runPlanner() { // save problem to file for LPG if(use_problem_topic && problem_instance_received) { ROS_INFO("KCL: (%s) (%s) Writing problem to file.", ros::this_node::getName().c_str(), problem_name.c_str()); std::ofstream dest; dest.open((problem_path).c_str()); dest << problem_instance; dest.close(); } // prepare the planner command line std::string str = planner_command; std::size_t dit = str.find("DOMAIN"); if(dit!=std::string::npos) str.replace(dit,6,domain_path); std::size_t pit = str.find("PROBLEM"); if(pit!=std::string::npos) str.replace(pit,7,problem_path); std::string updatePlan = "cp "+data_path+"lpgplan.SOL"+" "+data_path+"plan.pddl"; // call the planer ROS_INFO("KCL: (%s) (%s) Running: %s", ros::this_node::getName().c_str(), problem_name.c_str(), str.c_str()); std::string plan = runCommand(str.c_str()); ROS_INFO("KCL: (%s) (%s) Planning complete", ros::this_node::getName().c_str(), problem_name.c_str()); // move plan to correct path runCommand(updatePlan.c_str()); // check the planner solved the problem std::ifstream planfile; planfile.open((data_path + "plan.pddl").c_str()); std::string line; std::stringstream ss; int curr, next; bool solved = false; double planDuration; while (std::getline(planfile, line)) { if (line.find("0.0", 0) != std::string::npos){ solved = true; }else if (line.find("; ", 0) == std::string::npos) { // consume useless lines } planDuration = 0; if ((line.length()>1)){ ss.str(""); } while (std::getline(planfile, line)) { if (line.length()<2) break; ss << line << std::endl; } planner_output = ss.str(); } planfile.close(); if(!solved) ROS_INFO("KCL: (%s) (%s) Plan was unsolvable.", ros::this_node::getName().c_str(), problem_name.c_str()); else ROS_INFO("KCL: (%s) (%s) Plan was solved.", ros::this_node::getName().c_str(), problem_name.c_str()); return solved; } } // close namespace /*-------------*/ /* Main method */ /*-------------*/ int main(int argc, char **argv) { srand (static_cast <unsigned> (time(0))); ros::init(argc,argv,"rosplan_planner_interface"); ros::NodeHandle nh("~"); KCL_rosplan::LPGPlannerInterface pi(nh); // subscribe to problem instance std::string problemTopic = "problem_instance"; nh.getParam("problem_topic", problemTopic); ros::Subscriber problem_sub = nh.subscribe(problemTopic, 1, &KCL_rosplan::PlannerInterface::problemCallback, dynamic_cast<KCL_rosplan::PlannerInterface*>(&pi)); // start the planning services ros::ServiceServer service1 = nh.advertiseService("planning_server", &KCL_rosplan::PlannerInterface::runPlanningServerDefault, dynamic_cast<KCL_rosplan::PlannerInterface*>(&pi)); ros::ServiceServer service2 = nh.advertiseService("planning_server_params", &KCL_rosplan::PlannerInterface::runPlanningServerParams, dynamic_cast<KCL_rosplan::PlannerInterface*>(&pi)); ROS_INFO("KCL: (%s) Ready to receive", ros::this_node::getName().c_str()); ros::spin(); return 0; } <commit_msg>added inline comment for plan extraction<commit_after>#include "rosplan_planning_system/PlannerInterface/LPGPlannerInterface.h" namespace KCL_rosplan { /*-------------*/ /* constructor */ /*-------------*/ LPGPlannerInterface::LPGPlannerInterface(ros::NodeHandle& nh) { node_handle = &nh; plan_server = new actionlib::SimpleActionServer<rosplan_dispatch_msgs::PlanAction>((*node_handle), "start_planning", boost::bind(&PlannerInterface::runPlanningServerAction, this, _1), false); // publishing raw planner output std::string plannerTopic = "planner_output"; node_handle->getParam("planner_topic", plannerTopic); plan_publisher = node_handle->advertise<std_msgs::String>(plannerTopic, 1, true); // start planning action server plan_server->start(); } LPGPlannerInterface::~LPGPlannerInterface() { delete plan_server; } /** * Runs external commands */ std::string LPGPlannerInterface::runCommand(std::string cmd) { std::string data; FILE *stream; char buffer[1000]; stream = popen(cmd.c_str(), "r"); while ( fgets(buffer, 1000, stream) != NULL ) data.append(buffer); pclose(stream); return data; } /*------------------*/ /* Plan and process */ /*------------------*/ /** * passes the problem to the Planner; the plan to post-processing. */ bool LPGPlannerInterface::runPlanner() { // save problem to file for LPG if(use_problem_topic && problem_instance_received) { ROS_INFO("KCL: (%s) (%s) Writing problem to file.", ros::this_node::getName().c_str(), problem_name.c_str()); std::ofstream dest; dest.open((problem_path).c_str()); dest << problem_instance; dest.close(); } // prepare the planner command line std::string str = planner_command; std::size_t dit = str.find("DOMAIN"); if(dit!=std::string::npos) str.replace(dit,6,domain_path); std::size_t pit = str.find("PROBLEM"); if(pit!=std::string::npos) str.replace(pit,7,problem_path); std::string updatePlan = "cp "+data_path+"lpgplan.SOL"+" "+data_path+"plan.pddl"; // call the planer ROS_INFO("KCL: (%s) (%s) Running: %s", ros::this_node::getName().c_str(), problem_name.c_str(), str.c_str()); std::string plan = runCommand(str.c_str()); ROS_INFO("KCL: (%s) (%s) Planning complete", ros::this_node::getName().c_str(), problem_name.c_str()); // move plan to correct path runCommand(updatePlan.c_str()); // check the planner solved the problem std::ifstream planfile; planfile.open((data_path + "plan.pddl").c_str()); std::string line; std::stringstream ss; int curr, next; bool solved = false; double planDuration; while (std::getline(planfile, line)) { if (line.find("0.0", 0) != std::string::npos){ solved = true; }else if (line.find("; ", 0) == std::string::npos) { // consume useless lines } planDuration = 0; // extract second block of uninterrupted lines (the actual plan) from .SOL file content if ((line.length()>1)){ ss.str(""); } while (std::getline(planfile, line)) { if (line.length()<2) break; ss << line << std::endl; } planner_output = ss.str(); } planfile.close(); if(!solved) ROS_INFO("KCL: (%s) (%s) Plan was unsolvable.", ros::this_node::getName().c_str(), problem_name.c_str()); else ROS_INFO("KCL: (%s) (%s) Plan was solved.", ros::this_node::getName().c_str(), problem_name.c_str()); return solved; } } // close namespace /*-------------*/ /* Main method */ /*-------------*/ int main(int argc, char **argv) { srand (static_cast <unsigned> (time(0))); ros::init(argc,argv,"rosplan_planner_interface"); ros::NodeHandle nh("~"); KCL_rosplan::LPGPlannerInterface pi(nh); // subscribe to problem instance std::string problemTopic = "problem_instance"; nh.getParam("problem_topic", problemTopic); ros::Subscriber problem_sub = nh.subscribe(problemTopic, 1, &KCL_rosplan::PlannerInterface::problemCallback, dynamic_cast<KCL_rosplan::PlannerInterface*>(&pi)); // start the planning services ros::ServiceServer service1 = nh.advertiseService("planning_server", &KCL_rosplan::PlannerInterface::runPlanningServerDefault, dynamic_cast<KCL_rosplan::PlannerInterface*>(&pi)); ros::ServiceServer service2 = nh.advertiseService("planning_server_params", &KCL_rosplan::PlannerInterface::runPlanningServerParams, dynamic_cast<KCL_rosplan::PlannerInterface*>(&pi)); ROS_INFO("KCL: (%s) Ready to receive", ros::this_node::getName().c_str()); ros::spin(); return 0; } <|endoftext|>
<commit_before>/* Copyright (C) 2013 Nipun Talukdar 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. */ #ifndef __GEETCASS_CQL3RESULT__ #define __GEETCASS_CQL3RESULT__ #include <boost/shared_ptr.hpp> #include <boost/noncopyable.hpp> #include <bytebuffer.hpp> #include <cql3cons.hpp> #include <cql3header.hpp> #include <encode.hpp> #include <vector> using std::vector; namespace GeetCass { struct Column { string column; Cql3Types column_type; Column(const string& col, Cql3Types type) : column(col), column_type(type) { } }; struct Cql3RowMetaData { static void init(ByteBuffer& buffer, Cql3RowMetaData& metadata); uint32_t flags; uint32_t column_count; string global_table_spec[2]; vector <Column *> columns; }; class Cql3Row : public boost::noncopyable { public: Cql3Row(void *buffer = 0, size_t size = 0, Cql3RowMetaData* metadata =0); ///TBD }; class Cql3Rows { public: uint32_t getRowCount(); Cql3Row getNextRow(); Cql3Row getRow(uint32_t rowNum); // TBD private: ByteBuffer *_buffer; Cql3RowMetaData _metaData; size_t _startInByteBuffer; size_t _stopInByteBuffer; uint32_t _currentRow; uint32_t _maxRow; vector <int> _rowPositions; }; class Cql3Result { public: Cql3Result(ByteBuffer& buffer); Cql3Result(); Cql3Result(const Cql3Result& result); Cql3Result& operator=(const Cql3Result& result); void setBuffer(ByteBuffer& buffer); ResultCode getResultCode() const; ~Cql3Result(); private: ByteBuffer* _resultData; ResultCode _resultCode; }; } // GeetCass napespace ends #endif <commit_msg>A change<commit_after>/* Copyright (C) 2013 Nipun Talukdar 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. */ #ifndef __GEETCASS_CQL3RESULT__ #define __GEETCASS_CQL3RESULT__ #include <boost/shared_ptr.hpp> #include <boost/noncopyable.hpp> #include <bytebuffer.hpp> #include <cql3cons.hpp> #include <cql3header.hpp> #include <encode.hpp> #include <vector> using std::vector; namespace GeetCass { struct Column { string column; Cql3Types column_type; Column(const string& col, Cql3Types type) : column(col), column_type(type) { } }; struct Cql3RowMetaData { static void init(ByteBuffer& buffer, Cql3RowMetaData& metadata); uint32_t flags; uint32_t column_count; string global_table_spec[2]; vector <Column *> columns; }; class Cql3Row : public boost::noncopyable { public: Cql3Row(void *buffer = 0, size_t size = 0, Cql3RowMetaData* metadata =0); private: std::unordered_map<string, size_t > _columnPositions; bool getString(const string& column, string& out); bool getInt(const string& column, int32_t& val); ///TBD }; class Cql3Rows { public: uint32_t getRowCount(); Cql3Row getNextRow(); Cql3Row getRow(uint32_t rowNum); // TBD private: ByteBuffer *_buffer; Cql3RowMetaData _metaData; size_t _startInByteBuffer; size_t _stopInByteBuffer; uint32_t _currentRow; uint32_t _maxRow; vector <int> _rowPositions; }; class Cql3Result { public: Cql3Result(ByteBuffer& buffer); Cql3Result(); Cql3Result(const Cql3Result& result); Cql3Result& operator=(const Cql3Result& result); void setBuffer(ByteBuffer& buffer); ResultCode getResultCode() const; ~Cql3Result(); private: ByteBuffer* _resultData; ResultCode _resultCode; }; } // GeetCass napespace ends #endif <|endoftext|>
<commit_before> /* * jabberprotocol.cpp - Base class for the Kopete Jabber protocol * * Copyright (c) 2002-2003 by Till Gerken <till@tantalo.net> * Copyright (c) 2002 by Daniel Stone <dstone@kde.org> * * Kopete (c) by the Kopete developers <kopete-devel@kde.org> * * ************************************************************************* * * * * * This program is free software; you can redistribute it and/or modify * * * it under the terms of the GNU General Public License as published by * * * the Free Software Foundation; either version 2 of the License, or * * * (at your option) any later version. * * * * * ************************************************************************* */ #include <kdebug.h> #include <kgenericfactory.h> #include <kconfig.h> #include <kmessagebox.h> #include <kiconloader.h> #include <kpopupmenu.h> #include <kstandarddirs.h> #include <klineeditdlg.h> #include <qapplication.h> #include <qcursor.h> #include <qmap.h> #include <qtimer.h> #include <qpixmap.h> #include <qstringlist.h> #include "im.h" #include "xmpp.h" #include <sys/utsname.h> #include "kopetecontact.h" #include "kopetecontactlist.h" #include "kopetemetacontact.h" #include "kopetechatsession.h" #include "kopeteonlinestatusmanager.h" #include "kopeteaway.h" #include "kopeteglobal.h" #include "kopeteprotocol.h" #include "kopeteplugin.h" #include "addcontactpage.h" #include "jabbercontact.h" #include "dlgjabbersendraw.h" #include "dlgjabberservices.h" #include "dlgjabberchatjoin.h" #include "jabberaddcontactpage.h" #include "jabberprotocol.h" #include "jabberaccount.h" #include "kopeteaccountmanager.h" #include "jabbereditaccountwidget.h" #include "kopetecommandhandler.h" JabberProtocol *JabberProtocol::protocolInstance = 0; typedef KGenericFactory<JabberProtocol> JabberProtocolFactory; K_EXPORT_COMPONENT_FACTORY( kopete_jabber, JabberProtocolFactory( "kopete_jabber" ) ) JabberProtocol::JabberProtocol (QObject * parent, const char *name, const QStringList &) : Kopete::Protocol( JabberProtocolFactory::instance(), parent, name ), JabberKOSChatty(Kopete::OnlineStatus::Online, 100, this, JabberFreeForChat, "jabber_chatty", i18n ("Free for Chat"), i18n ("Free for Chat"), Kopete::OnlineStatusManager::FreeForChat ), JabberKOSOnline(Kopete::OnlineStatus::Online, 90, this, JabberOnline, QString::null, i18n ("Online"), i18n ("Online"), Kopete::OnlineStatusManager::Online ), JabberKOSAway(Kopete::OnlineStatus::Away, 80, this, JabberAway, "contact_away_overlay", i18n ("Away"), i18n ("Away"), Kopete::OnlineStatusManager::Away, Kopete::OnlineStatusManager::HasAwayMessage), JabberKOSXA(Kopete::OnlineStatus::Away, 70, this, JabberXA, "contact_xa_overlay", i18n ("Extended Away"), i18n ("Extended Away"), Kopete::OnlineStatusManager::Away, Kopete::OnlineStatusManager::HasAwayMessage), JabberKOSDND(Kopete::OnlineStatus::Away, 60, this, JabberDND, "contact_busy_overlay", i18n ("Do not Disturb"), i18n ("Do not Disturb"), Kopete::OnlineStatusManager::Busy, Kopete::OnlineStatusManager::HasAwayMessage), JabberKOSOffline(Kopete::OnlineStatus::Offline, 50, this, JabberOffline, QString::null, i18n ("Offline") ,i18n ("Offline"), Kopete::OnlineStatusManager::Offline ), JabberKOSInvisible(Kopete::OnlineStatus::Invisible, 40, this, JabberInvisible, "contact_invisible_overlay", i18n ("Invisible") ,i18n ("Invisible"), Kopete::OnlineStatusManager::Invisible), JabberKOSConnecting(Kopete::OnlineStatus::Connecting, 30, this, JabberConnecting, "jabber_connecting", i18n("Connecting")), propAwayMessage(Kopete::Global::Properties::self()->awayMessage()), propFirstName(Kopete::Global::Properties::self()->firstName()), propLastName(Kopete::Global::Properties::self()->lastName()), propFullName(Kopete::Global::Properties::self()->fullName()), propEmailAddress(Kopete::Global::Properties::self()->emailAddress()), propPrivatePhone(Kopete::Global::Properties::self()->privatePhone()), propPrivateMobilePhone(Kopete::Global::Properties::self()->privateMobilePhone()), propWorkPhone(Kopete::Global::Properties::self()->workPhone()), propWorkMobilePhone(Kopete::Global::Properties::self()->workMobilePhone()), propNickName(Kopete::Global::Properties::self()->nickName()), propSubscriptionStatus("jabberSubscriptionStatus", i18n ("Subscription"), QString::null, true, false), propAuthorizationStatus("jabberAuthorizationStatus", i18n ("Authorization Status"), QString::null, true, false), propAvailableResources("jabberAvailableResources", i18n ("Available Resources"), "jabber_chatty", false, true), propVCardCacheTimeStamp("jabberVCardCacheTimeStamp", i18n ("vCard Cache Timestamp"), QString::null, true, false, true) { kdDebug (JABBER_DEBUG_GLOBAL) << "[JabberProtocol] Loading ..." << endl; /* This is meant to be a singleton, so we will check if we have * been loaded before. */ if (protocolInstance) { kdDebug (JABBER_DEBUG_GLOBAL) << "[JabberProtocol] Warning: Protocol already " << "loaded, not initializing again." << endl; return; } protocolInstance = this; addAddressBookField ("messaging/xmpp", Kopete::Plugin::MakeIndexField); } JabberProtocol::~JabberProtocol () { //disconnectAll(); /* make sure that the next attempt to load Jabber * re-initializes the protocol class. */ protocolInstance = 0L; } AddContactPage *JabberProtocol::createAddContactWidget (QWidget * parent, Kopete::Account * i) { kdDebug (JABBER_DEBUG_GLOBAL) << "[Jabber Protocol] Create Add Contact Widget\n" << endl; return new JabberAddContactPage (i, parent); } KopeteEditAccountWidget *JabberProtocol::createEditAccountWidget (Kopete::Account * account, QWidget * parent) { kdDebug (JABBER_DEBUG_GLOBAL) << "[Jabber Protocol] Edit Account Widget\n" << endl; return new JabberEditAccountWidget (this, static_cast < JabberAccount * >(account), parent); } Kopete::Account *JabberProtocol::createNewAccount (const QString & accountId) { kdDebug (JABBER_DEBUG_GLOBAL) << "[Jabber Protocol] Create New Account. ID: " << accountId << "\n" << endl; return new JabberAccount (this, accountId); } Kopete::OnlineStatus JabberProtocol::resourceToKOS ( const XMPP::Resource &resource ) { // update to offline by default Kopete::OnlineStatus status = JabberKOSOffline; if ( !resource.status().isAvailable () ) { // resource is offline status = JabberKOSOffline; } else { if (resource.status ().show ().isEmpty ()) { if (resource.status ().isInvisible ()) { status = JabberKOSInvisible; } else { status = JabberKOSOnline; } } else if (resource.status ().show () == "chat") { status = JabberKOSChatty; } else if (resource.status ().show () == "away") { status = JabberKOSAway; } else if (resource.status ().show () == "xa") { status = JabberKOSXA; } else if (resource.status ().show () == "dnd") { status = JabberKOSDND; } else if (resource.status ().show () == "connecting") { status = JabberKOSConnecting; } } return status; } JabberProtocol *JabberProtocol::protocol () { // return current instance return protocolInstance; } Kopete::Contact *JabberProtocol::deserializeContact (Kopete::MetaContact * metaContact, const QMap < QString, QString > &serializedData, const QMap < QString, QString > & /* addressBookData */ ) { // kdDebug (JABBER_DEBUG_GLOBAL) << k_funcinfo << "Deserializing data for metacontact " << metaContact->displayName () << "\n" << endl; QString contactId = serializedData["contactId"]; QString displayName = serializedData["displayName"]; QString accountId = serializedData["accountId"]; QDict < Kopete::Account > accounts = Kopete::AccountManager::self ()->accounts (this); Kopete::Account *account = accounts[accountId]; if (!account) { kdDebug(JABBER_DEBUG_GLOBAL) << k_funcinfo << "WARNING: Account for contact does not exist, skipping." << endl; return 0; } if (account) account->addContact (contactId, metaContact); return account->contacts()[contactId]; } #include "jabberprotocol.moc" <commit_msg>Fix KOS categories so that there is just one status in each category. Prevents undefined behaviour in libkopete and inconsistent away behaviour from the UI.<commit_after> /* * jabberprotocol.cpp - Base class for the Kopete Jabber protocol * * Copyright (c) 2002-2003 by Till Gerken <till@tantalo.net> * Copyright (c) 2002 by Daniel Stone <dstone@kde.org> * * Kopete (c) by the Kopete developers <kopete-devel@kde.org> * * ************************************************************************* * * * * * This program is free software; you can redistribute it and/or modify * * * it under the terms of the GNU General Public License as published by * * * the Free Software Foundation; either version 2 of the License, or * * * (at your option) any later version. * * * * * ************************************************************************* */ #include <kdebug.h> #include <kgenericfactory.h> #include <kconfig.h> #include <kmessagebox.h> #include <kiconloader.h> #include <kpopupmenu.h> #include <kstandarddirs.h> #include <klineeditdlg.h> #include <qapplication.h> #include <qcursor.h> #include <qmap.h> #include <qtimer.h> #include <qpixmap.h> #include <qstringlist.h> #include "im.h" #include "xmpp.h" #include <sys/utsname.h> #include "kopetecontact.h" #include "kopetecontactlist.h" #include "kopetemetacontact.h" #include "kopetechatsession.h" #include "kopeteonlinestatusmanager.h" #include "kopeteaway.h" #include "kopeteglobal.h" #include "kopeteprotocol.h" #include "kopeteplugin.h" #include "addcontactpage.h" #include "jabbercontact.h" #include "dlgjabbersendraw.h" #include "dlgjabberservices.h" #include "dlgjabberchatjoin.h" #include "jabberaddcontactpage.h" #include "jabberprotocol.h" #include "jabberaccount.h" #include "kopeteaccountmanager.h" #include "jabbereditaccountwidget.h" #include "kopetecommandhandler.h" JabberProtocol *JabberProtocol::protocolInstance = 0; typedef KGenericFactory<JabberProtocol> JabberProtocolFactory; K_EXPORT_COMPONENT_FACTORY( kopete_jabber, JabberProtocolFactory( "kopete_jabber" ) ) JabberProtocol::JabberProtocol (QObject * parent, const char *name, const QStringList &) : Kopete::Protocol( JabberProtocolFactory::instance(), parent, name ), JabberKOSChatty(Kopete::OnlineStatus::Online, 100, this, JabberFreeForChat, "jabber_chatty", i18n ("Free for Chat"), i18n ("Free for Chat"), Kopete::OnlineStatusManager::FreeForChat ), JabberKOSOnline(Kopete::OnlineStatus::Online, 90, this, JabberOnline, QString::null, i18n ("Online"), i18n ("Online"), Kopete::OnlineStatusManager::Online ), JabberKOSAway(Kopete::OnlineStatus::Away, 80, this, JabberAway, "contact_away_overlay", i18n ("Away"), i18n ("Away"), Kopete::OnlineStatusManager::Away, Kopete::OnlineStatusManager::HasAwayMessage), JabberKOSXA(Kopete::OnlineStatus::Away, 70, this, JabberXA, "contact_xa_overlay", i18n ("Extended Away"), i18n ("Extended Away"), 0, Kopete::OnlineStatusManager::HasAwayMessage), JabberKOSDND(Kopete::OnlineStatus::Away, 60, this, JabberDND, "contact_busy_overlay", i18n ("Do not Disturb"), i18n ("Do not Disturb"), Kopete::OnlineStatusManager::Busy, Kopete::OnlineStatusManager::HasAwayMessage), JabberKOSOffline(Kopete::OnlineStatus::Offline, 50, this, JabberOffline, QString::null, i18n ("Offline") ,i18n ("Offline"), Kopete::OnlineStatusManager::Offline ), JabberKOSInvisible(Kopete::OnlineStatus::Invisible, 40, this, JabberInvisible, "contact_invisible_overlay", i18n ("Invisible") ,i18n ("Invisible"), Kopete::OnlineStatusManager::Invisible), JabberKOSConnecting(Kopete::OnlineStatus::Connecting, 30, this, JabberConnecting, "jabber_connecting", i18n("Connecting")), propAwayMessage(Kopete::Global::Properties::self()->awayMessage()), propFirstName(Kopete::Global::Properties::self()->firstName()), propLastName(Kopete::Global::Properties::self()->lastName()), propFullName(Kopete::Global::Properties::self()->fullName()), propEmailAddress(Kopete::Global::Properties::self()->emailAddress()), propPrivatePhone(Kopete::Global::Properties::self()->privatePhone()), propPrivateMobilePhone(Kopete::Global::Properties::self()->privateMobilePhone()), propWorkPhone(Kopete::Global::Properties::self()->workPhone()), propWorkMobilePhone(Kopete::Global::Properties::self()->workMobilePhone()), propNickName(Kopete::Global::Properties::self()->nickName()), propSubscriptionStatus("jabberSubscriptionStatus", i18n ("Subscription"), QString::null, true, false), propAuthorizationStatus("jabberAuthorizationStatus", i18n ("Authorization Status"), QString::null, true, false), propAvailableResources("jabberAvailableResources", i18n ("Available Resources"), "jabber_chatty", false, true), propVCardCacheTimeStamp("jabberVCardCacheTimeStamp", i18n ("vCard Cache Timestamp"), QString::null, true, false, true) { kdDebug (JABBER_DEBUG_GLOBAL) << "[JabberProtocol] Loading ..." << endl; /* This is meant to be a singleton, so we will check if we have * been loaded before. */ if (protocolInstance) { kdDebug (JABBER_DEBUG_GLOBAL) << "[JabberProtocol] Warning: Protocol already " << "loaded, not initializing again." << endl; return; } protocolInstance = this; addAddressBookField ("messaging/xmpp", Kopete::Plugin::MakeIndexField); } JabberProtocol::~JabberProtocol () { //disconnectAll(); /* make sure that the next attempt to load Jabber * re-initializes the protocol class. */ protocolInstance = 0L; } AddContactPage *JabberProtocol::createAddContactWidget (QWidget * parent, Kopete::Account * i) { kdDebug (JABBER_DEBUG_GLOBAL) << "[Jabber Protocol] Create Add Contact Widget\n" << endl; return new JabberAddContactPage (i, parent); } KopeteEditAccountWidget *JabberProtocol::createEditAccountWidget (Kopete::Account * account, QWidget * parent) { kdDebug (JABBER_DEBUG_GLOBAL) << "[Jabber Protocol] Edit Account Widget\n" << endl; return new JabberEditAccountWidget (this, static_cast < JabberAccount * >(account), parent); } Kopete::Account *JabberProtocol::createNewAccount (const QString & accountId) { kdDebug (JABBER_DEBUG_GLOBAL) << "[Jabber Protocol] Create New Account. ID: " << accountId << "\n" << endl; return new JabberAccount (this, accountId); } Kopete::OnlineStatus JabberProtocol::resourceToKOS ( const XMPP::Resource &resource ) { // update to offline by default Kopete::OnlineStatus status = JabberKOSOffline; if ( !resource.status().isAvailable () ) { // resource is offline status = JabberKOSOffline; } else { if (resource.status ().show ().isEmpty ()) { if (resource.status ().isInvisible ()) { status = JabberKOSInvisible; } else { status = JabberKOSOnline; } } else if (resource.status ().show () == "chat") { status = JabberKOSChatty; } else if (resource.status ().show () == "away") { status = JabberKOSAway; } else if (resource.status ().show () == "xa") { status = JabberKOSXA; } else if (resource.status ().show () == "dnd") { status = JabberKOSDND; } else if (resource.status ().show () == "connecting") { status = JabberKOSConnecting; } } return status; } JabberProtocol *JabberProtocol::protocol () { // return current instance return protocolInstance; } Kopete::Contact *JabberProtocol::deserializeContact (Kopete::MetaContact * metaContact, const QMap < QString, QString > &serializedData, const QMap < QString, QString > & /* addressBookData */ ) { // kdDebug (JABBER_DEBUG_GLOBAL) << k_funcinfo << "Deserializing data for metacontact " << metaContact->displayName () << "\n" << endl; QString contactId = serializedData["contactId"]; QString displayName = serializedData["displayName"]; QString accountId = serializedData["accountId"]; QDict < Kopete::Account > accounts = Kopete::AccountManager::self ()->accounts (this); Kopete::Account *account = accounts[accountId]; if (!account) { kdDebug(JABBER_DEBUG_GLOBAL) << k_funcinfo << "WARNING: Account for contact does not exist, skipping." << endl; return 0; } if (account) account->addContact (contactId, metaContact); return account->contacts()[contactId]; } #include "jabberprotocol.moc" <|endoftext|>
<commit_before>/* msndebugrawcmddlg.cpp - Send a raw MSN command for debugging Copyright (c) 2002 by Martijn Klingens <klingens@kde.org> Kopete (c) 2002 by the Kopete developers <kopete-devel@kde.org> Portions of this code are taken from KMerlin, (c) 2001 by Olaf Lueg <olueg@olsd.de> ************************************************************************* * * * 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. * * * ************************************************************************* */ #include "msndebugrawcmddlg.h" #include "ui_msndebugrawcommand_base.h" #include <qcheckbox.h> #include <qlineedit.h> #include <ktextedit.h> #include <klocale.h> MSNDebugRawCmdDlg::MSNDebugRawCmdDlg( QWidget *parent ) : KDialog( parent ) { setCaption( i18n( "DEBUG: Send Raw Command - MSN Plugin" ) ); setButtons( KDialog::Ok | KDialog::Cancel ); setDefaultButton( KDialog::Ok ); showButtonSeparator( true ); setInitialSize( QSize( 350, 200 ) ); QWidget* w = new QWidget( this ); m_main = new Ui::MSNDebugRawCommand_base(); m_main->setupUi( w ); setMainWidget( w ); } MSNDebugRawCmdDlg::~MSNDebugRawCmdDlg() { m_main; } QString MSNDebugRawCmdDlg::command() { return m_main->m_command->text(); } QString MSNDebugRawCmdDlg::params() { return m_main->m_params->text(); } bool MSNDebugRawCmdDlg::addNewline() { return m_main->m_addNewline->isChecked(); } bool MSNDebugRawCmdDlg::addId() { return m_main->m_addId->isChecked(); } QString MSNDebugRawCmdDlg::msg() { return m_main->m_msg->text(); } #include "msndebugrawcmddlg.moc" // vim: set noet ts=4 sts=4 sw=4: <commit_msg><commit_after>/* msndebugrawcmddlg.cpp - Send a raw MSN command for debugging Copyright (c) 2002 by Martijn Klingens <klingens@kde.org> Kopete (c) 2002 by the Kopete developers <kopete-devel@kde.org> Portions of this code are taken from KMerlin, (c) 2001 by Olaf Lueg <olueg@olsd.de> ************************************************************************* * * * 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. * * * ************************************************************************* */ #include "msndebugrawcmddlg.h" #include "ui_msndebugrawcommand_base.h" #include <qcheckbox.h> #include <qlineedit.h> #include <ktextedit.h> #include <klocale.h> MSNDebugRawCmdDlg::MSNDebugRawCmdDlg( QWidget *parent ) : KDialog( parent ) { setCaption( i18n( "DEBUG: Send Raw Command - MSN Plugin" ) ); setButtons( KDialog::Ok | KDialog::Cancel ); setDefaultButton( KDialog::Ok ); showButtonSeparator( true ); setInitialSize( QSize( 350, 200 ) ); QWidget* w = new QWidget( this ); m_main = new Ui::MSNDebugRawCommand_base(); m_main->setupUi( w ); setMainWidget( w ); } MSNDebugRawCmdDlg::~MSNDebugRawCmdDlg() { delete m_main; } QString MSNDebugRawCmdDlg::command() { return m_main->m_command->text(); } QString MSNDebugRawCmdDlg::params() { return m_main->m_params->text(); } bool MSNDebugRawCmdDlg::addNewline() { return m_main->m_addNewline->isChecked(); } bool MSNDebugRawCmdDlg::addId() { return m_main->m_addId->isChecked(); } QString MSNDebugRawCmdDlg::msg() { return m_main->m_msg->toPlainText(); } #include "msndebugrawcmddlg.moc" // vim: set noet ts=4 sts=4 sw=4: <|endoftext|>
<commit_before>/******************************************************************************\ * File: lexer.cpp * Purpose: Implementation of lexer classes * Author: Anton van Wezenbeek * RCS-ID: $Id$ * * Copyright (c) 1998-2009 Anton van Wezenbeek * All rights are reserved. Reproduction in whole or part is prohibited * without the written consent of the copyright owner. \******************************************************************************/ #include <wx/stc/stc.h> // for wxSTC_KEYWORDSET_MAX #include <wx/tokenzr.h> #include <wx/extension/lexer.h> #include <wx/extension/util.h> // for exGetWord using namespace std; const wxString exLexer::GetKeywordsString(int keyword_set) const { wxString keywords; if (keyword_set == -1) { for ( set<wxString>::const_iterator it = m_Keywords.begin(); it != m_Keywords.end(); ++it) { keywords += *it + " "; } } else { std::map< int, std::set<wxString> >::const_iterator it = m_KeywordsSet.find(keyword_set); if (it == m_KeywordsSet.end()) { wxFAIL; } else { set<wxString> theset = it->second; for ( set<wxString>::const_iterator it = theset.begin(); it != theset.end(); ++it) { keywords += *it + " "; } } } return keywords; } const wxString exLexer::GetFormattedText( const wxString& lines, const wxString& header, bool fill_out_with_space, bool fill_out) const { wxString text = lines, header_to_use = header; size_t nCharIndex; wxString out; // Process text between the carriage return line feeds. while ((nCharIndex = text.find("\n")) != wxString::npos) { out << GetUnFormattedText( text.substr(0, nCharIndex), header_to_use, fill_out_with_space, fill_out); text = text.substr(nCharIndex + 1); header_to_use = wxString(' ', header.size()); } if (!text.empty()) { out << GetUnFormattedText( text, header_to_use, fill_out_with_space, fill_out); } return out; } const wxString exLexer::GetUnFormattedText( const wxString& lines, const wxString& header, bool fill_out_with_space, bool fill_out) const { const size_t line_length = UsableCharactersPerLine(); // Use the header, with one space extra to separate, or no header at all. const wxString header_with_spaces = (header.size() == 0) ? wxString(wxEmptyString) : wxString(' ', header.size()); wxString in = lines, line = header; bool at_begin = true; wxString out; while (!in.empty()) { const wxString word = exGetWord(in, false, false); if (line.size() + 1 + word.size() > line_length) { out << MakeSingleLineComment(line, fill_out_with_space, fill_out) << "\n"; line = header_with_spaces + word; at_begin = true; } else { line += (!line.empty() && !at_begin ? " ": wxString(wxEmptyString)) + word; at_begin = false; } } out << MakeSingleLineComment(line, fill_out_with_space, fill_out); return out; } bool exLexer::IsKeyword(const wxString& word) const { set<wxString>::const_iterator it = m_Keywords.find(word); return (it != m_Keywords.end()); } bool exLexer::KeywordStartsWith(const wxString& word) const { for ( set<wxString>::const_iterator it = m_Keywords.begin(); it != m_Keywords.end(); ++it) { if (it->Upper().StartsWith(word.Upper())) { return true; } } return false; } const wxString exLexer::MakeComment( const wxString& text, bool fill_out_with_space, bool fill_out) const { wxString out; text.find("\n") != wxString::npos ? out << GetFormattedText(text, wxEmptyString, fill_out_with_space, fill_out): out << GetUnFormattedText(text, wxEmptyString, fill_out_with_space, fill_out); return out; } const wxString exLexer::MakeComment( const wxString& prefix, const wxString& text) const { wxString out; text.find("\n") != wxString::npos ? out << GetFormattedText(text, prefix, true, true): out << GetUnFormattedText(text, prefix, true, true); return out; } const wxString exLexer::MakeSingleLineComment( const wxString& text, bool fill_out_with_space, bool fill_out) const { // First set the fill_out_character. wxChar fill_out_character; if (fill_out_with_space) { fill_out_character = ' '; } else { if (text.empty()) { if (m_CommentBegin == m_CommentEnd || m_CommentEnd.empty()) fill_out_character = '-'; else fill_out_character = m_CommentBegin[m_CommentBegin.size() - 1]; } else fill_out_character = ' '; } wxString out = m_CommentBegin + fill_out_character + text; // Fill out characters. if (fill_out) { const int fill_chars = UsableCharactersPerLine() - text.size(); if (fill_chars > 0) { const wxString fill_out(fill_out_character, fill_chars); out += fill_out; } } if (!m_CommentEnd.empty()) out += fill_out_character + m_CommentEnd; return out; } bool exLexer::SetKeywords(const wxString& value) { set<wxString> keywords_set; wxStringTokenizer tkz(value, "\r\n "); int setno = 0; while (tkz.HasMoreTokens()) { const wxString line = tkz.GetNextToken(); wxStringTokenizer fields(line, ":"); wxString keyword; if (fields.CountTokens() > 1) { keyword = fields.GetNextToken(); const int new_setno = atoi(fields.GetNextToken().c_str()); if (new_setno >= wxSTC_KEYWORDSET_MAX) { return false; } if (new_setno != setno) { if (!keywords_set.empty()) { m_KeywordsSet.insert(make_pair(setno, keywords_set)); keywords_set.clear(); } setno = new_setno; } keywords_set.insert(keyword); } else { keyword = line; keywords_set.insert(line); } m_Keywords.insert(keyword); } m_KeywordsSet.insert(make_pair(setno, keywords_set)); return true; } int exLexer::UsableCharactersPerLine() const { // We always use lines with 80 characters. We adjust this here for // the space the beginning and end of the comment characters occupy. return 80 - (m_CommentBegin.size() + 1) - ((m_CommentEnd.size() != 0) ? m_CommentEnd.size() + 1 : 0); } <commit_msg>fixed spacing error<commit_after>/******************************************************************************\ * File: lexer.cpp * Purpose: Implementation of lexer classes * Author: Anton van Wezenbeek * RCS-ID: $Id$ * * Copyright (c) 1998-2009 Anton van Wezenbeek * All rights are reserved. Reproduction in whole or part is prohibited * without the written consent of the copyright owner. \******************************************************************************/ #include <wx/stc/stc.h> // for wxSTC_KEYWORDSET_MAX #include <wx/tokenzr.h> #include <wx/extension/lexer.h> #include <wx/extension/util.h> // for exGetWord using namespace std; const wxString exLexer::GetKeywordsString(int keyword_set) const { wxString keywords; if (keyword_set == -1) { for ( set<wxString>::const_iterator it = m_Keywords.begin(); it != m_Keywords.end(); ++it) { keywords += *it + " "; } } else { std::map< int, std::set<wxString> >::const_iterator it = m_KeywordsSet.find(keyword_set); if (it == m_KeywordsSet.end()) { wxFAIL; } else { set<wxString> theset = it->second; for ( set<wxString>::const_iterator it = theset.begin(); it != theset.end(); ++it) { keywords += *it + " "; } } } return keywords; } const wxString exLexer::GetFormattedText( const wxString& lines, const wxString& header, bool fill_out_with_space, bool fill_out) const { wxString text = lines, header_to_use = header; size_t nCharIndex; wxString out; // Process text between the carriage return line feeds. while ((nCharIndex = text.find("\n")) != wxString::npos) { out << GetUnFormattedText( text.substr(0, nCharIndex), header_to_use, fill_out_with_space, fill_out); text = text.substr(nCharIndex + 1); header_to_use = wxString(' ', header.size()); } if (!text.empty()) { out << GetUnFormattedText( text, header_to_use, fill_out_with_space, fill_out); } return out; } const wxString exLexer::GetUnFormattedText( const wxString& lines, const wxString& header, bool fill_out_with_space, bool fill_out) const { const size_t line_length = UsableCharactersPerLine(); // Use the header, with one space extra to separate, or no header at all. const wxString header_with_spaces = (header.size() == 0) ? wxString(wxEmptyString) : wxString(' ', header.size()); wxString in = lines, line = header; bool at_begin = true; wxString out; while (!in.empty()) { const wxString word = exGetWord(in, false, false); if (line.size() + 1 + word.size() > line_length) { out << MakeSingleLineComment(line, fill_out_with_space, fill_out) << "\n"; line = header_with_spaces + word; } else { line += (!line.empty() && !at_begin ? " ": wxString(wxEmptyString)) + word; at_begin = false; } } out << MakeSingleLineComment(line, fill_out_with_space, fill_out); return out; } bool exLexer::IsKeyword(const wxString& word) const { set<wxString>::const_iterator it = m_Keywords.find(word); return (it != m_Keywords.end()); } bool exLexer::KeywordStartsWith(const wxString& word) const { for ( set<wxString>::const_iterator it = m_Keywords.begin(); it != m_Keywords.end(); ++it) { if (it->Upper().StartsWith(word.Upper())) { return true; } } return false; } const wxString exLexer::MakeComment( const wxString& text, bool fill_out_with_space, bool fill_out) const { wxString out; text.find("\n") != wxString::npos ? out << GetFormattedText(text, wxEmptyString, fill_out_with_space, fill_out): out << GetUnFormattedText(text, wxEmptyString, fill_out_with_space, fill_out); return out; } const wxString exLexer::MakeComment( const wxString& prefix, const wxString& text) const { wxString out; text.find("\n") != wxString::npos ? out << GetFormattedText(text, prefix, true, true): out << GetUnFormattedText(text, prefix, true, true); return out; } const wxString exLexer::MakeSingleLineComment( const wxString& text, bool fill_out_with_space, bool fill_out) const { // First set the fill_out_character. wxChar fill_out_character; if (fill_out_with_space) { fill_out_character = ' '; } else { if (text.empty()) { if (m_CommentBegin == m_CommentEnd || m_CommentEnd.empty()) fill_out_character = '-'; else fill_out_character = m_CommentBegin[m_CommentBegin.size() - 1]; } else fill_out_character = ' '; } wxString out = m_CommentBegin + fill_out_character + text; // Fill out characters. if (fill_out) { const int fill_chars = UsableCharactersPerLine() - text.size(); if (fill_chars > 0) { const wxString fill_out(fill_out_character, fill_chars); out += fill_out; } } if (!m_CommentEnd.empty()) out += fill_out_character + m_CommentEnd; return out; } bool exLexer::SetKeywords(const wxString& value) { set<wxString> keywords_set; wxStringTokenizer tkz(value, "\r\n "); int setno = 0; while (tkz.HasMoreTokens()) { const wxString line = tkz.GetNextToken(); wxStringTokenizer fields(line, ":"); wxString keyword; if (fields.CountTokens() > 1) { keyword = fields.GetNextToken(); const int new_setno = atoi(fields.GetNextToken().c_str()); if (new_setno >= wxSTC_KEYWORDSET_MAX) { return false; } if (new_setno != setno) { if (!keywords_set.empty()) { m_KeywordsSet.insert(make_pair(setno, keywords_set)); keywords_set.clear(); } setno = new_setno; } keywords_set.insert(keyword); } else { keyword = line; keywords_set.insert(line); } m_Keywords.insert(keyword); } m_KeywordsSet.insert(make_pair(setno, keywords_set)); return true; } int exLexer::UsableCharactersPerLine() const { // We always use lines with 80 characters. We adjust this here for // the space the beginning and end of the comment characters occupy. return 80 - (m_CommentBegin.size() + 1) - ((m_CommentEnd.size() != 0) ? m_CommentEnd.size() + 1 : 0); } <|endoftext|>
<commit_before>#ifndef hash_map_hh_INCLUDED #define hash_map_hh_INCLUDED #include "hash.hh" #include "memory.hh" #include "vector.hh" namespace Kakoune { template<typename T> constexpr void constexpr_swap(T& lhs, T& rhs) { T tmp = std::move(lhs); lhs = std::move(rhs); rhs = std::move(tmp); } template<MemoryDomain domain, template<typename, MemoryDomain> class Container> struct HashIndex { struct Entry { size_t hash = 0; int index = -1; }; static constexpr float max_fill_rate = 0.5f; constexpr HashIndex() = default; constexpr HashIndex(size_t count) { const size_t min_size = (size_t)(count / max_fill_rate) + 1; size_t new_size = 4; while (new_size < min_size) new_size *= 2; m_entries.resize(new_size, {}); } using ContainerType = Container<Entry, domain>; constexpr void resize(size_t new_size) { kak_assert(new_size > m_entries.size()); ContainerType old_entries = std::move(m_entries); m_entries.resize(new_size, {}); for (auto& entry : old_entries) { if (entry.index >= 0) add(entry.hash, entry.index); } } constexpr void reserve(size_t count) { kak_assert(count > 0); const size_t min_size = (size_t)(count / max_fill_rate) + 1; size_t new_size = m_entries.empty() ? 4 : m_entries.size(); while (new_size < min_size) new_size *= 2; if (new_size > m_entries.size()) resize(new_size); } constexpr void add(size_t hash, int index) { Entry entry{hash, index}; while (true) { auto target_slot = compute_slot(entry.hash); for (auto slot = target_slot; slot < m_entries.size(); ++slot) { if (m_entries[slot].index == -1) { m_entries[slot] = entry; return; } // Robin hood hashing auto candidate_slot = compute_slot(m_entries[slot].hash); if (target_slot < candidate_slot) { constexpr_swap(m_entries[slot], entry); target_slot = candidate_slot; } } // no free entries found, resize, try again resize(m_entries.size() * 2); } } constexpr void remove(size_t hash, int index) { for (auto slot = compute_slot(hash); slot < m_entries.size(); ++slot) { kak_assert(m_entries[slot].index >= 0); if (m_entries[slot].index == index) { m_entries[slot].index = -1; // Recompact following entries for (auto next = slot+1; next < m_entries.size(); ++next) { if (m_entries[next].index == -1 or compute_slot(m_entries[next].hash) == next) break; kak_assert(compute_slot(m_entries[next].hash) < next); constexpr_swap(m_entries[next-1], m_entries[next]); } break; } } } constexpr void ordered_fix_entries(int index) { for (auto& entry : m_entries) { if (entry.index >= index) --entry.index; } } constexpr void unordered_fix_entries(size_t hash, int old_index, int new_index) { for (auto slot = compute_slot(hash); slot < m_entries.size(); ++slot) { if (m_entries[slot].index == old_index) { m_entries[slot].index = new_index; return; } } kak_assert(false); // entry not found ?! } constexpr const Entry& operator[](size_t index) const { return m_entries[index]; } constexpr size_t size() const { return m_entries.size(); } constexpr size_t compute_slot(size_t hash) const { // We assume entries.size() is power of 2 return hash & (m_entries.size()-1); } constexpr void clear() { m_entries.clear(); } private: ContainerType m_entries; }; template<typename Key, typename Value> struct HashItem { Key key; Value value; }; template<typename Key, typename Value, MemoryDomain domain = MemoryDomain::Undefined, template<typename, MemoryDomain> class Container = Vector> struct HashMap { using Item = HashItem<Key, Value>; using ContainerType = Container<Item, domain>; constexpr HashMap() = default; constexpr HashMap(std::initializer_list<Item> val) : m_items(val), m_index(val.size()) { for (int i = 0; i < m_items.size(); ++i) m_index.add(hash_value(m_items[i].key), i); } constexpr Value& insert(Item item) { m_index.reserve(m_items.size()+1); m_index.add(hash_value(item.key), (int)m_items.size()); m_items.push_back(std::move(item)); return m_items.back().value; } template<typename KeyType> using EnableIfHashCompatible = std::enable_if_t< IsHashCompatible<Key, std::decay_t<KeyType>> >; template<typename KeyType, typename = EnableIfHashCompatible<KeyType>> constexpr int find_index(const KeyType& key, size_t hash) const { for (auto slot = m_index.compute_slot(hash); slot < m_index.size(); ++slot) { auto& entry = m_index[slot]; if (entry.index == -1) return -1; if (entry.hash == hash and m_items[entry.index].key == key) return entry.index; } return -1; } template<typename KeyType, typename = EnableIfHashCompatible<KeyType>> constexpr int find_index(const KeyType& key) const { return find_index(key, hash_value(key)); } template<typename KeyType, typename = EnableIfHashCompatible<KeyType>> constexpr bool contains(const KeyType& key) const { return find_index(key) >= 0; } template<typename KeyType, typename = EnableIfHashCompatible<KeyType>> constexpr Value& operator[](KeyType&& key) { const auto hash = hash_value(key); auto index = find_index(key, hash); if (index >= 0) return m_items[index].value; m_index.reserve(m_items.size()+1); m_index.add(hash, (int)m_items.size()); m_items.push_back({Key(std::forward<KeyType>(key)), {}}); return m_items.back().value; } template<typename KeyType, typename = EnableIfHashCompatible<KeyType>> constexpr void remove(const KeyType& key) { const auto hash = hash_value(key); int index = find_index(key, hash); if (index >= 0) { m_items.erase(m_items.begin() + index); m_index.remove(hash, index); m_index.ordered_fix_entries(index); } } template<typename KeyType, typename = EnableIfHashCompatible<KeyType>> constexpr void unordered_remove(const KeyType& key) { const auto hash = hash_value(key); int index = find_index(key, hash); if (index >= 0) { constexpr_swap(m_items[index], m_items.back()); m_items.pop_back(); m_index.remove(hash, index); if (index != m_items.size()) m_index.unordered_fix_entries(hash_value(m_items[index].key), m_items.size(), index); } } constexpr void erase(const Key& key) { unordered_remove(key); } template<typename KeyType, typename = EnableIfHashCompatible<KeyType>> constexpr void remove_all(const KeyType& key) { const auto hash = hash_value(key); for (int index = find_index(key, hash); index >= 0; index = find_index(key, hash)) { m_items.erase(m_items.begin() + index); m_index.remove(hash, index); m_index.ordered_fix_entries(index); } } using iterator = typename ContainerType::iterator; constexpr iterator begin() { return m_items.begin(); } constexpr iterator end() { return m_items.end(); } using const_iterator = typename ContainerType::const_iterator; constexpr const_iterator begin() const { return m_items.begin(); } constexpr const_iterator end() const { return m_items.end(); } template<typename KeyType, typename = EnableIfHashCompatible<KeyType>> constexpr iterator find(const KeyType& key) { auto index = find_index(key); return index >= 0 ? begin() + index : end(); } template<typename KeyType, typename = EnableIfHashCompatible<KeyType>> constexpr const_iterator find(const KeyType& key) const { return const_cast<HashMap*>(this)->find(key); } constexpr void clear() { m_items.clear(); m_index.clear(); } constexpr size_t size() const { return m_items.size(); } constexpr bool empty() const { return m_items.empty(); } constexpr void reserve(size_t size) { m_items.reserve(size); m_index.reserve(size); } // Equality is taking the order of insertion into account template<MemoryDomain otherDomain> constexpr bool operator==(const HashMap<Key, Value, otherDomain, Container>& other) const { return size() == other.size() and std::equal(begin(), end(), other.begin(), [](const Item& lhs, const Item& rhs) { return lhs.key == rhs.key and lhs.value == rhs.value; }); } template<MemoryDomain otherDomain> constexpr bool operator!=(const HashMap<Key, Value, otherDomain, Container>& other) const { return not (*this == other); } private: ContainerType m_items; HashIndex<domain, Container> m_index; }; void profile_hash_maps(); } #endif // hash_map_hh_INCLUDED <commit_msg>HashMap: Tolerate reserving for 0 elements<commit_after>#ifndef hash_map_hh_INCLUDED #define hash_map_hh_INCLUDED #include "hash.hh" #include "memory.hh" #include "vector.hh" namespace Kakoune { template<typename T> constexpr void constexpr_swap(T& lhs, T& rhs) { T tmp = std::move(lhs); lhs = std::move(rhs); rhs = std::move(tmp); } template<MemoryDomain domain, template<typename, MemoryDomain> class Container> struct HashIndex { struct Entry { size_t hash = 0; int index = -1; }; static constexpr float max_fill_rate = 0.5f; constexpr HashIndex() = default; constexpr HashIndex(size_t count) { const size_t min_size = (size_t)(count / max_fill_rate) + 1; size_t new_size = 4; while (new_size < min_size) new_size *= 2; m_entries.resize(new_size, {}); } using ContainerType = Container<Entry, domain>; constexpr void resize(size_t new_size) { kak_assert(new_size > m_entries.size()); ContainerType old_entries = std::move(m_entries); m_entries.resize(new_size, {}); for (auto& entry : old_entries) { if (entry.index >= 0) add(entry.hash, entry.index); } } constexpr void reserve(size_t count) { if (count == 0) return; const size_t min_size = (size_t)(count / max_fill_rate) + 1; size_t new_size = m_entries.empty() ? 4 : m_entries.size(); while (new_size < min_size) new_size *= 2; if (new_size > m_entries.size()) resize(new_size); } constexpr void add(size_t hash, int index) { Entry entry{hash, index}; while (true) { auto target_slot = compute_slot(entry.hash); for (auto slot = target_slot; slot < m_entries.size(); ++slot) { if (m_entries[slot].index == -1) { m_entries[slot] = entry; return; } // Robin hood hashing auto candidate_slot = compute_slot(m_entries[slot].hash); if (target_slot < candidate_slot) { constexpr_swap(m_entries[slot], entry); target_slot = candidate_slot; } } // no free entries found, resize, try again resize(m_entries.size() * 2); } } constexpr void remove(size_t hash, int index) { for (auto slot = compute_slot(hash); slot < m_entries.size(); ++slot) { kak_assert(m_entries[slot].index >= 0); if (m_entries[slot].index == index) { m_entries[slot].index = -1; // Recompact following entries for (auto next = slot+1; next < m_entries.size(); ++next) { if (m_entries[next].index == -1 or compute_slot(m_entries[next].hash) == next) break; kak_assert(compute_slot(m_entries[next].hash) < next); constexpr_swap(m_entries[next-1], m_entries[next]); } break; } } } constexpr void ordered_fix_entries(int index) { for (auto& entry : m_entries) { if (entry.index >= index) --entry.index; } } constexpr void unordered_fix_entries(size_t hash, int old_index, int new_index) { for (auto slot = compute_slot(hash); slot < m_entries.size(); ++slot) { if (m_entries[slot].index == old_index) { m_entries[slot].index = new_index; return; } } kak_assert(false); // entry not found ?! } constexpr const Entry& operator[](size_t index) const { return m_entries[index]; } constexpr size_t size() const { return m_entries.size(); } constexpr size_t compute_slot(size_t hash) const { // We assume entries.size() is power of 2 return hash & (m_entries.size()-1); } constexpr void clear() { m_entries.clear(); } private: ContainerType m_entries; }; template<typename Key, typename Value> struct HashItem { Key key; Value value; }; template<typename Key, typename Value, MemoryDomain domain = MemoryDomain::Undefined, template<typename, MemoryDomain> class Container = Vector> struct HashMap { using Item = HashItem<Key, Value>; using ContainerType = Container<Item, domain>; constexpr HashMap() = default; constexpr HashMap(std::initializer_list<Item> val) : m_items(val), m_index(val.size()) { for (int i = 0; i < m_items.size(); ++i) m_index.add(hash_value(m_items[i].key), i); } constexpr Value& insert(Item item) { m_index.reserve(m_items.size()+1); m_index.add(hash_value(item.key), (int)m_items.size()); m_items.push_back(std::move(item)); return m_items.back().value; } template<typename KeyType> using EnableIfHashCompatible = std::enable_if_t< IsHashCompatible<Key, std::decay_t<KeyType>> >; template<typename KeyType, typename = EnableIfHashCompatible<KeyType>> constexpr int find_index(const KeyType& key, size_t hash) const { for (auto slot = m_index.compute_slot(hash); slot < m_index.size(); ++slot) { auto& entry = m_index[slot]; if (entry.index == -1) return -1; if (entry.hash == hash and m_items[entry.index].key == key) return entry.index; } return -1; } template<typename KeyType, typename = EnableIfHashCompatible<KeyType>> constexpr int find_index(const KeyType& key) const { return find_index(key, hash_value(key)); } template<typename KeyType, typename = EnableIfHashCompatible<KeyType>> constexpr bool contains(const KeyType& key) const { return find_index(key) >= 0; } template<typename KeyType, typename = EnableIfHashCompatible<KeyType>> constexpr Value& operator[](KeyType&& key) { const auto hash = hash_value(key); auto index = find_index(key, hash); if (index >= 0) return m_items[index].value; m_index.reserve(m_items.size()+1); m_index.add(hash, (int)m_items.size()); m_items.push_back({Key(std::forward<KeyType>(key)), {}}); return m_items.back().value; } template<typename KeyType, typename = EnableIfHashCompatible<KeyType>> constexpr void remove(const KeyType& key) { const auto hash = hash_value(key); int index = find_index(key, hash); if (index >= 0) { m_items.erase(m_items.begin() + index); m_index.remove(hash, index); m_index.ordered_fix_entries(index); } } template<typename KeyType, typename = EnableIfHashCompatible<KeyType>> constexpr void unordered_remove(const KeyType& key) { const auto hash = hash_value(key); int index = find_index(key, hash); if (index >= 0) { constexpr_swap(m_items[index], m_items.back()); m_items.pop_back(); m_index.remove(hash, index); if (index != m_items.size()) m_index.unordered_fix_entries(hash_value(m_items[index].key), m_items.size(), index); } } constexpr void erase(const Key& key) { unordered_remove(key); } template<typename KeyType, typename = EnableIfHashCompatible<KeyType>> constexpr void remove_all(const KeyType& key) { const auto hash = hash_value(key); for (int index = find_index(key, hash); index >= 0; index = find_index(key, hash)) { m_items.erase(m_items.begin() + index); m_index.remove(hash, index); m_index.ordered_fix_entries(index); } } using iterator = typename ContainerType::iterator; constexpr iterator begin() { return m_items.begin(); } constexpr iterator end() { return m_items.end(); } using const_iterator = typename ContainerType::const_iterator; constexpr const_iterator begin() const { return m_items.begin(); } constexpr const_iterator end() const { return m_items.end(); } template<typename KeyType, typename = EnableIfHashCompatible<KeyType>> constexpr iterator find(const KeyType& key) { auto index = find_index(key); return index >= 0 ? begin() + index : end(); } template<typename KeyType, typename = EnableIfHashCompatible<KeyType>> constexpr const_iterator find(const KeyType& key) const { return const_cast<HashMap*>(this)->find(key); } constexpr void clear() { m_items.clear(); m_index.clear(); } constexpr size_t size() const { return m_items.size(); } constexpr bool empty() const { return m_items.empty(); } constexpr void reserve(size_t size) { m_items.reserve(size); m_index.reserve(size); } // Equality is taking the order of insertion into account template<MemoryDomain otherDomain> constexpr bool operator==(const HashMap<Key, Value, otherDomain, Container>& other) const { return size() == other.size() and std::equal(begin(), end(), other.begin(), [](const Item& lhs, const Item& rhs) { return lhs.key == rhs.key and lhs.value == rhs.value; }); } template<MemoryDomain otherDomain> constexpr bool operator!=(const HashMap<Key, Value, otherDomain, Container>& other) const { return not (*this == other); } private: ContainerType m_items; HashIndex<domain, Container> m_index; }; void profile_hash_maps(); } #endif // hash_map_hh_INCLUDED <|endoftext|>
<commit_before>/*************** <auto-copyright.pl BEGIN do not edit this line> ************** * * VR Juggler is (C) Copyright 1998-2007 by Iowa State University * * Original Authors: * Allen Bierbaum, Christopher Just, * Patrick Hartling, Kevin Meinert, * Carolina Cruz-Neira, Albert Baker * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * *************** <auto-copyright.pl END do not edit this line> ***************/ #include <windows.h> #ifdef _DEBUG # include <iostream> #endif #include <dinput.h> #include <stdlib.h> #include <math.h> #include <malloc.h> #include <memory.h> #include <tchar.h> #include <assert.h> #include <drivers/Microsoft/DirectXJoystick/DirectXJoystickExceptions.h> #include <drivers/Microsoft/DirectXJoystick/DirectXJoystickStandalone.h> namespace gadget { BOOL CALLBACK enumerateJoysticksCallback(const DIDEVICEINSTANCE* dInstance, void* pContext) { DirectXJoystickStandalone* obj = static_cast<DirectXJoystickStandalone*>(pContext); return obj->enumerateJoysticks(dInstance); } BOOL CALLBACK enumerateAxesCallback(const DIDEVICEOBJECTINSTANCE* doi, void* pContext) { DirectXJoystickStandalone* obj = static_cast<DirectXJoystickStandalone*>(pContext); return obj->enumerateAxes(doi); } DirectXJoystickStandalone::DirectXJoystickStandalone() : mDxObject(NULL) , mDxJoystick(NULL) , mDataFormatObj(&c_dfDIJoystick) , mDataFormatSize(sizeof(mJsData)) { } void DirectXJoystickStandalone::init() { HRESULT status; // Create a Direct Input manager object. status = DirectInput8Create(GetModuleHandle(NULL), DIRECTINPUT_VERSION, IID_IDirectInput8, (VOID**) &mDxObject, NULL); // An error returned at this point indicates that Direct Input is not // available. That means that we are effectively done with this device. if ( FAILED(status) ) { throw DirectXJoystickException("Direct Input is not available"); } // Look for joystick. mDxObject->EnumDevices(DI8DEVCLASS_GAMECTRL, enumerateJoysticksCallback, (void*) this, (DWORD) DIEDFL_ATTACHEDONLY); status = mDxJoystick->SetDataFormat(mDataFormatObj); if ( FAILED(status) ) { if ( status == DIERR_ACQUIRED ) { throw DirectXJoystickDataFormatException("Cannot set data format while device is acquired"); } else if ( status == DIERR_INVALIDPARAM ) { throw DirectXJoystickDataFormatException("Invalid data format chosen"); } else if ( status == DIERR_NOTINITIALIZED ) { throw DirectXJoystickDataFormatException("Cannot set data format on uninitialized device"); } else { throw DirectXJoystickDataFormatException("Unknown error when trying to set the data format"); } } // Set the cooperative level to let DInput know how this device should // interact with the system and with other DInput applications. // NOTE: This always fails because the first parameter is NULL! status = mDxJoystick->SetCooperativeLevel((HWND) NULL, DISCL_EXCLUSIVE | DISCL_FOREGROUND); /* if ( FAILED(status) ) { if ( status == DIERR_INVALIDPARAM ) { throw DirectXJoystickCooperationException("Invalid cooperative mode chosen"); } else if ( status == DIERR_NOTINITIALIZED ) { throw DirectXJoystickCooperationException("Cannot set cooperative mode on uninitialized device"); } else if ( status == E_HANDLE ) { throw DirectXJoystickCooperationException("Invalid HWND used when setting cooperative mode"); } else { throw DirectXJoystickCooperationException("Unknown error when trying to set the cooperative mode"); } } */ mCapabilities.dwSize = sizeof(DIDEVCAPS); status = mDxJoystick->GetCapabilities(&mCapabilities); if ( FAILED(status) ) { if ( status == DIERR_INVALIDPARAM || status == E_POINTER ) { throw DirectXJoystickQueryException("Invalid data passed to IDirectInputDevice8::GetCapabilities()"); } else if ( status == DIERR_NOTINITIALIZED ) { throw DirectXJoystickQueryException("Cannot query capabilities for an uninitialized device"); } else { throw DirectXJoystickQueryException("Unknown error when trying to query the joystick capabilities"); } } mAxisValueMap.resize(mCapabilities.dwAxes, NULL); // Enumerate the axes of the joystick and set the range of each axis found. mDxJoystick->EnumObjects(enumerateAxesCallback, (void*) this, DIDFT_AXIS); status = mDxJoystick->Acquire(); // DI_OK indicates that we acquired the device successfully. // S_FALSE indicates that we had already acquired the device. if ( status != DI_OK && status != S_FALSE ) { if ( status == DIERR_INVALIDPARAM ) { throw DirectXJoystickDataFormatException("Invalid parameter passed during device acquisition"); } else if ( status == DIERR_NOTINITIALIZED ) { throw DirectXJoystickDataFormatException("Cannot acquire an uninitialized device"); } else if ( status == DIERR_OTHERAPPHASPRIO ) { throw DirectXJoystickDataFormatException("A higher priority application has already acquired the device"); } else { throw DirectXJoystickDataFormatException("Unknown error when trying to acquire the device"); } } // Get device-specific information. DIDEVICEINSTANCE dx_dev_info; dx_dev_info.dwSize = sizeof(DIDEVICEINSTANCE); mDxJoystick->GetDeviceInfo(&dx_dev_info); mType = dx_dev_info.dwDevType; mProductName = std::string(dx_dev_info.tszProductName); if ( mProductName.empty() ) { mProductName = "unknown"; } } void DirectXJoystickStandalone::close() { // Unacquire & release any DirectInputDevice objects. if ( mDxJoystick != NULL ) { mDxJoystick->Unacquire(); mDxJoystick->Release(); mDxJoystick = NULL; } // Release any DirectInput objects. if ( mDxObject != NULL ) { mDxObject->Release(); mDxObject = NULL; } } bool DirectXJoystickStandalone::poll() { bool sample_taken(false); HRESULT status = mDxJoystick->Poll(); // If we failed to poll the joystick, try to reacquire it. When we cannot // poll the device, we cannot take a sample. if ( FAILED(status) ) { status = mDxJoystick->Acquire(); // XXX: It might be necessary to put a limit on the number of times we // try to reacquire the device as this process could hold up the Input // Manager. while ( status == DIERR_INPUTLOST ) { status = mDxJoystick->Acquire(); } } // We polled the joystick successfully, so we can read a sample. else { status = mDxJoystick->GetDeviceState(mDataFormatSize, &mJsData); sample_taken = true; } return sample_taken; } const DIJOYSTATE& DirectXJoystickStandalone::getData() const { return mJsData; } DWORD DirectXJoystickStandalone::getType() const { return mType; } const std::string& DirectXJoystickStandalone::getProductName() const { return mProductName; } LONG DirectXJoystickStandalone::getAxisValue(const unsigned int axisIndex) { if ( axisIndex < mCapabilities.dwAxes ) { return *(mAxisValueMap[axisIndex]); } else { // Map the given axis index to the range [0,3] so that we can use // the result as the index into mJsData.rgdwPOV. const unsigned int pov_index((axisIndex - mCapabilities.dwAxes) / 2); const DWORD pov_value(mJsData.rgdwPOV[pov_index]); // The hat is centered. if ( (LOWORD(pov_value) == 0xffff) ) { return (getAxisMax() + getAxisMin()) / 2; } else { const float pi = 3.14159265358979323846f; const float pov_rads((pov_value / 100.0) * pi / 180.0f); // We treat an even-numbered axis index as an X axis request. // An odd-numbered axis index then a Y axis request. const bool x_axis((axisIndex % 2) == 0); return (x_axis ? getAxisMax() * sinf(pov_rads) : getAxisMax() * cosf(pov_rads)); } } } BOOL DirectXJoystickStandalone::enumerateJoysticks(const DIDEVICEINSTANCE* dInstance) { // Obtain an interface to the enumerated joystick. HRESULT hr = mDxObject->CreateDevice(dInstance->guidInstance, &mDxJoystick, NULL); return (FAILED(hr) ? DIENUM_CONTINUE : DIENUM_STOP); /* // FIXME: allow configurable joystick station static int count = 0; ++count; if( count == 2 ) { mDxObject->CreateDevice(dInstance->guidInstance, &mDxJoystick, NULL); return DIENUM_STOP; } return DIENUM_CONTINUE; */ } BOOL DirectXJoystickStandalone::enumerateAxes(const DIDEVICEOBJECTINSTANCE* doi) { // The axes appear to be enumerated in reverse order by Direct Input. // XXX: Can we depend on this? Using DIDFT_GETINSTANCE(doi->dwType) gives // back values that I would not expect in certain cases. In other words, // the object instance number does not correlate with the memory ordering // in DIJOYSTATE. static int axis_index(mCapabilities.dwAxes - 1); assert(axis_index >= 0 && "axis_index went negative!"); // For each axis enumrated, this function will set // the minimum and maximum range values for it. if ( doi->dwType & DIDFT_AXIS ) { DIPROPRANGE diprg; diprg.diph.dwSize = sizeof(DIPROPRANGE); diprg.diph.dwHeaderSize = sizeof(DIPROPHEADER); diprg.diph.dwHow = DIPH_BYID; diprg.diph.dwObj = doi->dwType; diprg.lMin = getAxisMin(); diprg.lMax = getAxisMax(); // Set the range for the current axis. if( FAILED(mDxJoystick->SetProperty(DIPROP_RANGE, &diprg.diph)) ) { return DIENUM_STOP; } LONG* value_addr(NULL); if ( doi->guidType == GUID_XAxis ) { value_addr = &mJsData.lX; #ifdef _DEBUG std::cout << "Object for X axis" << std::endl; #endif } else if ( doi->guidType == GUID_YAxis ) { value_addr = &mJsData.lY; #ifdef _DEBUG std::cout << "Object for Y axis" << std::endl; #endif } else if ( doi->guidType == GUID_ZAxis ) { value_addr = &mJsData.lZ; #ifdef _DEBUG std::cout << "Object for Z axis" << std::endl; #endif } else if ( doi->guidType == GUID_RxAxis ) { value_addr = &mJsData.lRx; #ifdef _DEBUG std::cout << "Object for X axis rotation" << std::endl; #endif } else if ( doi->guidType == GUID_RyAxis ) { value_addr = &mJsData.lRy; #ifdef _DEBUG std::cout << "Object for Y axis rotation" << std::endl; #endif } else if ( doi->guidType == GUID_RzAxis ) { value_addr = &mJsData.lRz; #ifdef _DEBUG std::cout << "Object for Z axis rotation" << std::endl; #endif } else if ( doi->guidType == GUID_Slider ) { // XXX: I do not know the correct way to distinguish between the two // possible sliders. -PH 2/2/2005 if ( DIDFT_GETINSTANCE(doi->dwType) == 2 ) { value_addr = &mJsData.rglSlider[0]; } else { value_addr = &mJsData.rglSlider[1]; } #ifdef _DEBUG std::cout << "Object for slider" << std::endl; #endif } #ifdef _DEBUG std::cout << "Setting mAxisValueMap[" << axis_index << "]" << std::endl; #endif mAxisValueMap[axis_index] = value_addr; axis_index--; } return DIENUM_CONTINUE; } } // End of gadget namespace <commit_msg>Removed debug output.<commit_after>/*************** <auto-copyright.pl BEGIN do not edit this line> ************** * * VR Juggler is (C) Copyright 1998-2007 by Iowa State University * * Original Authors: * Allen Bierbaum, Christopher Just, * Patrick Hartling, Kevin Meinert, * Carolina Cruz-Neira, Albert Baker * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * *************** <auto-copyright.pl END do not edit this line> ***************/ #include <windows.h> #include <dinput.h> #include <stdlib.h> #include <math.h> #include <malloc.h> #include <memory.h> #include <tchar.h> #include <assert.h> #include <drivers/Microsoft/DirectXJoystick/DirectXJoystickExceptions.h> #include <drivers/Microsoft/DirectXJoystick/DirectXJoystickStandalone.h> namespace gadget { BOOL CALLBACK enumerateJoysticksCallback(const DIDEVICEINSTANCE* dInstance, void* pContext) { DirectXJoystickStandalone* obj = static_cast<DirectXJoystickStandalone*>(pContext); return obj->enumerateJoysticks(dInstance); } BOOL CALLBACK enumerateAxesCallback(const DIDEVICEOBJECTINSTANCE* doi, void* pContext) { DirectXJoystickStandalone* obj = static_cast<DirectXJoystickStandalone*>(pContext); return obj->enumerateAxes(doi); } DirectXJoystickStandalone::DirectXJoystickStandalone() : mDxObject(NULL) , mDxJoystick(NULL) , mDataFormatObj(&c_dfDIJoystick) , mDataFormatSize(sizeof(mJsData)) { } void DirectXJoystickStandalone::init() { HRESULT status; // Create a Direct Input manager object. status = DirectInput8Create(GetModuleHandle(NULL), DIRECTINPUT_VERSION, IID_IDirectInput8, (VOID**) &mDxObject, NULL); // An error returned at this point indicates that Direct Input is not // available. That means that we are effectively done with this device. if ( FAILED(status) ) { throw DirectXJoystickException("Direct Input is not available"); } // Look for joystick. mDxObject->EnumDevices(DI8DEVCLASS_GAMECTRL, enumerateJoysticksCallback, (void*) this, (DWORD) DIEDFL_ATTACHEDONLY); status = mDxJoystick->SetDataFormat(mDataFormatObj); if ( FAILED(status) ) { if ( status == DIERR_ACQUIRED ) { throw DirectXJoystickDataFormatException("Cannot set data format while device is acquired"); } else if ( status == DIERR_INVALIDPARAM ) { throw DirectXJoystickDataFormatException("Invalid data format chosen"); } else if ( status == DIERR_NOTINITIALIZED ) { throw DirectXJoystickDataFormatException("Cannot set data format on uninitialized device"); } else { throw DirectXJoystickDataFormatException("Unknown error when trying to set the data format"); } } // Set the cooperative level to let DInput know how this device should // interact with the system and with other DInput applications. // NOTE: This always fails because the first parameter is NULL! status = mDxJoystick->SetCooperativeLevel((HWND) NULL, DISCL_EXCLUSIVE | DISCL_FOREGROUND); /* if ( FAILED(status) ) { if ( status == DIERR_INVALIDPARAM ) { throw DirectXJoystickCooperationException("Invalid cooperative mode chosen"); } else if ( status == DIERR_NOTINITIALIZED ) { throw DirectXJoystickCooperationException("Cannot set cooperative mode on uninitialized device"); } else if ( status == E_HANDLE ) { throw DirectXJoystickCooperationException("Invalid HWND used when setting cooperative mode"); } else { throw DirectXJoystickCooperationException("Unknown error when trying to set the cooperative mode"); } } */ mCapabilities.dwSize = sizeof(DIDEVCAPS); status = mDxJoystick->GetCapabilities(&mCapabilities); if ( FAILED(status) ) { if ( status == DIERR_INVALIDPARAM || status == E_POINTER ) { throw DirectXJoystickQueryException("Invalid data passed to IDirectInputDevice8::GetCapabilities()"); } else if ( status == DIERR_NOTINITIALIZED ) { throw DirectXJoystickQueryException("Cannot query capabilities for an uninitialized device"); } else { throw DirectXJoystickQueryException("Unknown error when trying to query the joystick capabilities"); } } mAxisValueMap.resize(mCapabilities.dwAxes, NULL); // Enumerate the axes of the joystick and set the range of each axis found. mDxJoystick->EnumObjects(enumerateAxesCallback, (void*) this, DIDFT_AXIS); status = mDxJoystick->Acquire(); // DI_OK indicates that we acquired the device successfully. // S_FALSE indicates that we had already acquired the device. if ( status != DI_OK && status != S_FALSE ) { if ( status == DIERR_INVALIDPARAM ) { throw DirectXJoystickDataFormatException("Invalid parameter passed during device acquisition"); } else if ( status == DIERR_NOTINITIALIZED ) { throw DirectXJoystickDataFormatException("Cannot acquire an uninitialized device"); } else if ( status == DIERR_OTHERAPPHASPRIO ) { throw DirectXJoystickDataFormatException("A higher priority application has already acquired the device"); } else { throw DirectXJoystickDataFormatException("Unknown error when trying to acquire the device"); } } // Get device-specific information. DIDEVICEINSTANCE dx_dev_info; dx_dev_info.dwSize = sizeof(DIDEVICEINSTANCE); mDxJoystick->GetDeviceInfo(&dx_dev_info); mType = dx_dev_info.dwDevType; mProductName = std::string(dx_dev_info.tszProductName); if ( mProductName.empty() ) { mProductName = "unknown"; } } void DirectXJoystickStandalone::close() { // Unacquire & release any DirectInputDevice objects. if ( mDxJoystick != NULL ) { mDxJoystick->Unacquire(); mDxJoystick->Release(); mDxJoystick = NULL; } // Release any DirectInput objects. if ( mDxObject != NULL ) { mDxObject->Release(); mDxObject = NULL; } } bool DirectXJoystickStandalone::poll() { bool sample_taken(false); HRESULT status = mDxJoystick->Poll(); // If we failed to poll the joystick, try to reacquire it. When we cannot // poll the device, we cannot take a sample. if ( FAILED(status) ) { status = mDxJoystick->Acquire(); // XXX: It might be necessary to put a limit on the number of times we // try to reacquire the device as this process could hold up the Input // Manager. while ( status == DIERR_INPUTLOST ) { status = mDxJoystick->Acquire(); } } // We polled the joystick successfully, so we can read a sample. else { status = mDxJoystick->GetDeviceState(mDataFormatSize, &mJsData); sample_taken = true; } return sample_taken; } const DIJOYSTATE& DirectXJoystickStandalone::getData() const { return mJsData; } DWORD DirectXJoystickStandalone::getType() const { return mType; } const std::string& DirectXJoystickStandalone::getProductName() const { return mProductName; } LONG DirectXJoystickStandalone::getAxisValue(const unsigned int axisIndex) { if ( axisIndex < mCapabilities.dwAxes ) { return *(mAxisValueMap[axisIndex]); } else { // Map the given axis index to the range [0,3] so that we can use // the result as the index into mJsData.rgdwPOV. const unsigned int pov_index((axisIndex - mCapabilities.dwAxes) / 2); const DWORD pov_value(mJsData.rgdwPOV[pov_index]); // The hat is centered. if ( (LOWORD(pov_value) == 0xffff) ) { return (getAxisMax() + getAxisMin()) / 2; } else { const float pi = 3.14159265358979323846f; const float pov_rads((pov_value / 100.0) * pi / 180.0f); // We treat an even-numbered axis index as an X axis request. // An odd-numbered axis index then a Y axis request. const bool x_axis((axisIndex % 2) == 0); return (x_axis ? getAxisMax() * sinf(pov_rads) : getAxisMax() * cosf(pov_rads)); } } } BOOL DirectXJoystickStandalone::enumerateJoysticks(const DIDEVICEINSTANCE* dInstance) { // Obtain an interface to the enumerated joystick. HRESULT hr = mDxObject->CreateDevice(dInstance->guidInstance, &mDxJoystick, NULL); return (FAILED(hr) ? DIENUM_CONTINUE : DIENUM_STOP); /* // FIXME: allow configurable joystick station static int count = 0; ++count; if( count == 2 ) { mDxObject->CreateDevice(dInstance->guidInstance, &mDxJoystick, NULL); return DIENUM_STOP; } return DIENUM_CONTINUE; */ } BOOL DirectXJoystickStandalone::enumerateAxes(const DIDEVICEOBJECTINSTANCE* doi) { // The axes appear to be enumerated in reverse order by Direct Input. // XXX: Can we depend on this? Using DIDFT_GETINSTANCE(doi->dwType) gives // back values that I would not expect in certain cases. In other words, // the object instance number does not correlate with the memory ordering // in DIJOYSTATE. static int axis_index(mCapabilities.dwAxes - 1); assert(axis_index >= 0 && "axis_index went negative!"); // For each axis enumrated, this function will set // the minimum and maximum range values for it. if ( doi->dwType & DIDFT_AXIS ) { DIPROPRANGE diprg; diprg.diph.dwSize = sizeof(DIPROPRANGE); diprg.diph.dwHeaderSize = sizeof(DIPROPHEADER); diprg.diph.dwHow = DIPH_BYID; diprg.diph.dwObj = doi->dwType; diprg.lMin = getAxisMin(); diprg.lMax = getAxisMax(); // Set the range for the current axis. if( FAILED(mDxJoystick->SetProperty(DIPROP_RANGE, &diprg.diph)) ) { return DIENUM_STOP; } LONG* value_addr(NULL); if ( doi->guidType == GUID_XAxis ) { value_addr = &mJsData.lX; } else if ( doi->guidType == GUID_YAxis ) { value_addr = &mJsData.lY; } else if ( doi->guidType == GUID_ZAxis ) { value_addr = &mJsData.lZ; } else if ( doi->guidType == GUID_RxAxis ) { value_addr = &mJsData.lRx; } else if ( doi->guidType == GUID_RyAxis ) { value_addr = &mJsData.lRy; } else if ( doi->guidType == GUID_RzAxis ) { value_addr = &mJsData.lRz; } else if ( doi->guidType == GUID_Slider ) { // XXX: I do not know the correct way to distinguish between the two // possible sliders. -PH 2/2/2005 if ( DIDFT_GETINSTANCE(doi->dwType) == 2 ) { value_addr = &mJsData.rglSlider[0]; } else { value_addr = &mJsData.rglSlider[1]; } } mAxisValueMap[axis_index] = value_addr; axis_index--; } return DIENUM_CONTINUE; } } // End of gadget namespace <|endoftext|>
<commit_before>/** \file SimpleXmlParser.cc * \brief A non-validating XML parser class. * \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de) * * \copyright 2015 Universitätsbiblothek Tübingen. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "SimpleXmlParser.h" #include <stdexcept> #include "Compiler.h" #include "StringUtil.h" #include "TextUtil.h" namespace { inline bool DecodeEnity(const std::string &entity_string, std::string * const decoded_char) { if (unlikely(entity_string.empty())) return false; if (__builtin_strcmp(entity_string.c_str(), "amp") == 0) *decoded_char = "&"; else if (__builtin_strcmp(entity_string.c_str(), "apos") == 0) *decoded_char = "'"; else if (__builtin_strcmp(entity_string.c_str(), "quot") == 0) *decoded_char = "\""; else if (__builtin_strcmp(entity_string.c_str(), "lt") == 0) *decoded_char = "<"; else if (__builtin_strcmp(entity_string.c_str(), "gt") == 0) *decoded_char = ">"; else if (unlikely(entity_string[0] == '#')) { if (entity_string.length() < 2) return false; unsigned code_point; if (entity_string[1] == 'x') { if (entity_string.length() < 3 or entity_string.length() > 6) return false; if (not StringUtil::ToUnsigned(entity_string.substr(2), &code_point, 16)) return false; } else { if (entity_string.length() < 2 or entity_string.length() > 6) return false; if (not StringUtil::ToUnsigned(entity_string.substr(1), &code_point)) return false; } if (not TextUtil::WCharToUTF8String(static_cast<wchar_t>(code_point), decoded_char)) return false; } else return false; return true; } // Replaces entities in-place and resizes "data", if necessary. inline bool DecodeEntities(std::string * const data) { if (unlikely(data->empty())) return true; std::string::iterator next(data->begin()); bool in_entity(false); std::string entity; for (const auto ch : *data) { if (unlikely(in_entity)) { if (ch == ';') { std::string decoded_char; if (not DecodeEnity(entity, &decoded_char)) return false; for (const auto dch : decoded_char) *next++ = dch; in_entity = false; } else entity += ch; } else if (unlikely(ch == '&')) { in_entity = true; entity.clear(); } else *next++ = ch; } if (unlikely(next != data->end())) // We had some non-length-preserving entity replacements. data->resize(next - data->begin()); return not in_entity; } } // unnamed namespace inline void SimpleXmlParser::skipWhiteSpace() { for (;;) { const int ch(input_->get()); if (unlikely(ch == EOF)) return; if (ch != ' ' and ch != '\t' and ch != '\n' and ch != '\r') { input_->putback(ch); return; } else if (ch == '\n') ++line_no_; } } inline bool SimpleXmlParser::extractName(std::string * const name) { name->clear(); int ch(input_->get()); if (unlikely(ch == EOF or (not StringUtil::IsAsciiLetter(ch) and ch != '_' and ch != ':'))) { input_->putback(ch); return false; } *name += static_cast<char>(ch); for (;;) { ch = input_->get(); if (unlikely(ch == EOF)) return false; if (not (StringUtil::IsAsciiLetter(ch) or StringUtil::IsDigit(ch) or ch == '_' or ch == ':' or ch == '.')) { input_->putback(ch); return true; } *name += static_cast<char>(ch); } } inline bool SimpleXmlParser::extractQuotedString(const int closing_quote, std::string * const s) { s->clear(); for (;;) { const int ch(input_->get()); if (unlikely(ch == EOF)) return false; if (unlikely(ch == closing_quote)) return true; *s += static_cast<char>(ch); } } bool SimpleXmlParser::getNext(Type * const type, std::map<std::string, std::string> * const attrib_map, std::string * const data) { if (unlikely(last_type_ == ERROR)) throw std::runtime_error("in SimpleXmlParser::getNext: previous call already indicated an error!"); attrib_map->clear(); data->clear(); if (last_element_was_empty_) { last_type_ = *type = CLOSING_TAG; data->swap(last_tag_name_); last_element_was_empty_ = false; last_type_ = CLOSING_TAG; return true; } int ch; if (last_type_ == OPENING_TAG) { last_type_ = *type = CHARACTERS; while ((ch = input_->get()) != '<') { if (unlikely(ch == EOF)) { last_error_message_ = "Unexpected EOF while looking for the start of a closing tag!"; return false; } if (unlikely(ch == '\n')) ++line_no_; *data += static_cast<char>(ch); } input_->putback(ch); // Putting back the '<'. if (not DecodeEntities(data)) { last_type_ = *type = ERROR; last_error_message_ = "Invalid entity in character data ending on line " + std::to_string(line_no_) + "!"; return false; } } else { // end-of-document or opening or closing tag skipWhiteSpace(); ch = input_->get(); if (unlikely(ch == EOF)) { last_type_ = *type = END_OF_DOCUMENT; return true; } if (ch != '<') { last_type_ = *type = ERROR; last_error_message_ = "Expected '<' on line " + std::to_string(line_no_) + ", found '" + std::string(1, static_cast<char>(ch)) + "' instead!"; return false; } // If we're at the beginning, we may have an XML prolog: if (unlikely(last_type_ == UNINITIALISED) and input_->peek() == '?') { if (not parseProlog()) { last_type_ = *type = ERROR; return false; } last_type_ = *type = START_OF_DOCUMENT; return true; } ch = input_->get(); if (ch == '/') { // A closing tag. if (unlikely(not parseClosingTag(data))) { last_type_ = *type = ERROR; last_error_message_ = "Error while parsing a closing tag on line " + std::to_string(line_no_) + "!"; return false; } last_type_ = *type = CLOSING_TAG; } else { // An opening tag. input_->putback(ch); std::string error_message; if (unlikely(not parseOpeningTag(data, attrib_map, &error_message))) { last_type_ = *type = ERROR; last_error_message_ = "Error while parsing an opening tag on line " + std::to_string(line_no_) + "! (" + error_message + ")"; return false; } ch = input_->get(); if (ch == '/') { last_element_was_empty_ = true; last_tag_name_ = *data; ch = input_->get(); } if (unlikely(ch != '>')) { last_type_ = *type = ERROR; last_error_message_ = "Error while parsing a opening tag on line " + std::to_string(line_no_) + "! (" "Closing angle bracket not found.)"; return false; } last_type_ = *type = OPENING_TAG; } } return true; } bool SimpleXmlParser::parseProlog() { if (input_->peek() != '?') return true; input_->get(); std::string prolog_tag_name; std::map<std::string, std::string> prolog_attrib_map; std::string error_message; if (not parseOpeningTag(&prolog_tag_name, &prolog_attrib_map, &error_message)) { last_error_message_ = "Error in prolog! (" + error_message + ")"; return false; } int ch(input_->get()); if (unlikely(ch != '?')) { last_error_message_ = "Error in prolog, expected '?' but found '" + std::string(1, static_cast<char>(ch)) + "'!"; return false; } ch = input_->get(); if (unlikely(ch != '>')) { last_error_message_ = "Error in prolog, closing angle bracket not found!"; return false; } const auto encoding(prolog_attrib_map.find("encoding")); if (encoding != prolog_attrib_map.cend()) { if (::strcasecmp(encoding->second.c_str(), "utf-8") != 0) { last_error_message_ = "Error in prolog: We only support the UTF-8 encoding!"; return false; } } return true; } bool SimpleXmlParser::parseOpeningTag(std::string * const tag_name, std::map<std::string, std::string> * const attrib_map, std::string * const error_message) { attrib_map->clear(); error_message->clear(); if (unlikely(not extractName(tag_name))) { *error_message = "Failed to extract the tag name."; return false; } skipWhiteSpace(); std::string attrib_name; while (extractName(&attrib_name)) { if (unlikely(attrib_map->find(attrib_name) != attrib_map->cend())) { // Duplicate attribute name? *error_message = "Found a duplicate tag name."; return false; } skipWhiteSpace(); const int ch(input_->get()); if (unlikely(ch != '=')) { *error_message = "Could not find an equal sign as part of an attribute."; return false; } skipWhiteSpace(); const int quote(input_->get()); if (unlikely(quote != '"' and quote != '\'')) { *error_message = "Found neither a single- nor a double-quote starting an attribute value."; return false; } std::string attrib_value; if (unlikely(not extractQuotedString(quote, &attrib_value))) { *error_message = "Failed to extract the attribute value."; return false; } (*attrib_map)[attrib_name] = attrib_value; skipWhiteSpace(); } return true; } bool SimpleXmlParser::parseClosingTag(std::string * const tag_name) { tag_name->clear(); if (not extractName(tag_name)) return false; skipWhiteSpace(); return input_->get() == '>'; } std::string SimpleXmlParser::TypeToString(const Type type) { switch (type) { case UNINITIALISED: return "UNINITIALISED"; case START_OF_DOCUMENT: return "START_OF_DOCUMENT"; case END_OF_DOCUMENT: return "END_OF_DOCUMENT"; case ERROR: return "ERROR"; case OPENING_TAG: return "OPENING_TAG"; case CLOSING_TAG: return "CLOSING_TAG"; case CHARACTERS: return "CHARACTERS"; } __builtin_unreachable(); } <commit_msg>Fixed a typo.<commit_after>/** \file SimpleXmlParser.cc * \brief A non-validating XML parser class. * \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de) * * \copyright 2015 Universitätsbiblothek Tübingen. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "SimpleXmlParser.h" #include <stdexcept> #include "Compiler.h" #include "StringUtil.h" #include "TextUtil.h" namespace { inline bool DecodeEnity(const std::string &entity_string, std::string * const decoded_char) { if (unlikely(entity_string.empty())) return false; if (__builtin_strcmp(entity_string.c_str(), "amp") == 0) *decoded_char = "&"; else if (__builtin_strcmp(entity_string.c_str(), "apos") == 0) *decoded_char = "'"; else if (__builtin_strcmp(entity_string.c_str(), "quot") == 0) *decoded_char = "\""; else if (__builtin_strcmp(entity_string.c_str(), "lt") == 0) *decoded_char = "<"; else if (__builtin_strcmp(entity_string.c_str(), "gt") == 0) *decoded_char = ">"; else if (unlikely(entity_string[0] == '#')) { if (entity_string.length() < 2) return false; unsigned code_point; if (entity_string[1] == 'x') { if (entity_string.length() < 3 or entity_string.length() > 6) return false; if (not StringUtil::ToUnsigned(entity_string.substr(2), &code_point, 16)) return false; } else { if (entity_string.length() < 2 or entity_string.length() > 6) return false; if (not StringUtil::ToUnsigned(entity_string.substr(1), &code_point)) return false; } if (not TextUtil::WCharToUTF8String(static_cast<wchar_t>(code_point), decoded_char)) return false; } else return false; return true; } // Replaces entities in-place and resizes "data", if necessary. inline bool DecodeEntities(std::string * const data) { if (unlikely(data->empty())) return true; std::string::iterator next(data->begin()); bool in_entity(false); std::string entity; for (const auto ch : *data) { if (unlikely(in_entity)) { if (ch == ';') { std::string decoded_char; if (not DecodeEnity(entity, &decoded_char)) return false; for (const auto dch : decoded_char) *next++ = dch; in_entity = false; } else entity += ch; } else if (unlikely(ch == '&')) { in_entity = true; entity.clear(); } else *next++ = ch; } if (unlikely(next != data->end())) // We had some non-length-preserving entity replacements. data->resize(next - data->begin()); return not in_entity; } } // unnamed namespace inline void SimpleXmlParser::skipWhiteSpace() { for (;;) { const int ch(input_->get()); if (unlikely(ch == EOF)) return; if (ch != ' ' and ch != '\t' and ch != '\n' and ch != '\r') { input_->putback(ch); return; } else if (ch == '\n') ++line_no_; } } inline bool SimpleXmlParser::extractName(std::string * const name) { name->clear(); int ch(input_->get()); if (unlikely(ch == EOF or (not StringUtil::IsAsciiLetter(ch) and ch != '_' and ch != ':'))) { input_->putback(ch); return false; } *name += static_cast<char>(ch); for (;;) { ch = input_->get(); if (unlikely(ch == EOF)) return false; if (not (StringUtil::IsAsciiLetter(ch) or StringUtil::IsDigit(ch) or ch == '_' or ch == ':' or ch == '.')) { input_->putback(ch); return true; } *name += static_cast<char>(ch); } } inline bool SimpleXmlParser::extractQuotedString(const int closing_quote, std::string * const s) { s->clear(); for (;;) { const int ch(input_->get()); if (unlikely(ch == EOF)) return false; if (unlikely(ch == closing_quote)) return true; *s += static_cast<char>(ch); } } bool SimpleXmlParser::getNext(Type * const type, std::map<std::string, std::string> * const attrib_map, std::string * const data) { if (unlikely(last_type_ == ERROR)) throw std::runtime_error("in SimpleXmlParser::getNext: previous call already indicated an error!"); attrib_map->clear(); data->clear(); if (last_element_was_empty_) { last_type_ = *type = CLOSING_TAG; data->swap(last_tag_name_); last_element_was_empty_ = false; last_type_ = CLOSING_TAG; return true; } int ch; if (last_type_ == OPENING_TAG) { last_type_ = *type = CHARACTERS; while ((ch = input_->get()) != '<') { if (unlikely(ch == EOF)) { last_error_message_ = "Unexpected EOF while looking for the start of a closing tag!"; return false; } if (unlikely(ch == '\n')) ++line_no_; *data += static_cast<char>(ch); } input_->putback(ch); // Putting back the '<'. if (not DecodeEntities(data)) { last_type_ = *type = ERROR; last_error_message_ = "Invalid entity in character data ending on line " + std::to_string(line_no_) + "!"; return false; } } else { // end-of-document or opening or closing tag skipWhiteSpace(); ch = input_->get(); if (unlikely(ch == EOF)) { last_type_ = *type = END_OF_DOCUMENT; return true; } if (ch != '<') { last_type_ = *type = ERROR; last_error_message_ = "Expected '<' on line " + std::to_string(line_no_) + ", found '" + std::string(1, static_cast<char>(ch)) + "' instead!"; return false; } // If we're at the beginning, we may have an XML prolog: if (unlikely(last_type_ == UNINITIALISED) and input_->peek() == '?') { if (not parseProlog()) { last_type_ = *type = ERROR; return false; } last_type_ = *type = START_OF_DOCUMENT; return true; } ch = input_->get(); if (ch == '/') { // A closing tag. if (unlikely(not parseClosingTag(data))) { last_type_ = *type = ERROR; last_error_message_ = "Error while parsing a closing tag on line " + std::to_string(line_no_) + "!"; return false; } last_type_ = *type = CLOSING_TAG; } else { // An opening tag. input_->putback(ch); std::string error_message; if (unlikely(not parseOpeningTag(data, attrib_map, &error_message))) { last_type_ = *type = ERROR; last_error_message_ = "Error while parsing an opening tag on line " + std::to_string(line_no_) + "! (" + error_message + ")"; return false; } ch = input_->get(); if (ch == '/') { last_element_was_empty_ = true; last_tag_name_ = *data; ch = input_->get(); } if (unlikely(ch != '>')) { last_type_ = *type = ERROR; last_error_message_ = "Error while parsing an opening tag on line " + std::to_string(line_no_) + "! (" "Closing angle bracket not found.)"; return false; } last_type_ = *type = OPENING_TAG; } } return true; } bool SimpleXmlParser::parseProlog() { if (input_->peek() != '?') return true; input_->get(); std::string prolog_tag_name; std::map<std::string, std::string> prolog_attrib_map; std::string error_message; if (not parseOpeningTag(&prolog_tag_name, &prolog_attrib_map, &error_message)) { last_error_message_ = "Error in prolog! (" + error_message + ")"; return false; } int ch(input_->get()); if (unlikely(ch != '?')) { last_error_message_ = "Error in prolog, expected '?' but found '" + std::string(1, static_cast<char>(ch)) + "'!"; return false; } ch = input_->get(); if (unlikely(ch != '>')) { last_error_message_ = "Error in prolog, closing angle bracket not found!"; return false; } const auto encoding(prolog_attrib_map.find("encoding")); if (encoding != prolog_attrib_map.cend()) { if (::strcasecmp(encoding->second.c_str(), "utf-8") != 0) { last_error_message_ = "Error in prolog: We only support the UTF-8 encoding!"; return false; } } return true; } bool SimpleXmlParser::parseOpeningTag(std::string * const tag_name, std::map<std::string, std::string> * const attrib_map, std::string * const error_message) { attrib_map->clear(); error_message->clear(); if (unlikely(not extractName(tag_name))) { *error_message = "Failed to extract the tag name."; return false; } skipWhiteSpace(); std::string attrib_name; while (extractName(&attrib_name)) { if (unlikely(attrib_map->find(attrib_name) != attrib_map->cend())) { // Duplicate attribute name? *error_message = "Found a duplicate tag name."; return false; } skipWhiteSpace(); const int ch(input_->get()); if (unlikely(ch != '=')) { *error_message = "Could not find an equal sign as part of an attribute."; return false; } skipWhiteSpace(); const int quote(input_->get()); if (unlikely(quote != '"' and quote != '\'')) { *error_message = "Found neither a single- nor a double-quote starting an attribute value."; return false; } std::string attrib_value; if (unlikely(not extractQuotedString(quote, &attrib_value))) { *error_message = "Failed to extract the attribute value."; return false; } (*attrib_map)[attrib_name] = attrib_value; skipWhiteSpace(); } return true; } bool SimpleXmlParser::parseClosingTag(std::string * const tag_name) { tag_name->clear(); if (not extractName(tag_name)) return false; skipWhiteSpace(); return input_->get() == '>'; } std::string SimpleXmlParser::TypeToString(const Type type) { switch (type) { case UNINITIALISED: return "UNINITIALISED"; case START_OF_DOCUMENT: return "START_OF_DOCUMENT"; case END_OF_DOCUMENT: return "END_OF_DOCUMENT"; case ERROR: return "ERROR"; case OPENING_TAG: return "OPENING_TAG"; case CLOSING_TAG: return "CLOSING_TAG"; case CHARACTERS: return "CHARACTERS"; } __builtin_unreachable(); } <|endoftext|>
<commit_before>/* * #%L * %% * Copyright (C) 2020 BMW Car IT GmbH * %% * 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. * #L% */ #include <cstdio> #include <boost/format.hpp> #include "joynr/UdsServer.h" #include "joynr/Logger.h" #include "UdsFrameBufferV1.h" #include "UdsSendQueue.h" namespace joynr { constexpr char UdsServer::_initMessageStart[]; constexpr int UdsServer::_threadsPerServer; UdsServer::UdsServer(const UdsSettings& settings) noexcept : _ioContext(std::make_shared<boost::asio::io_service>(_threadsPerServer)), _registry{std::make_shared<Connection::Active>()}, _openSleepTime{settings.getConnectSleepTimeMs()}, _endpoint(settings.getSocketPath()), _acceptor(*_ioContext), _newClientSocket(*_ioContext), _started{false} { _remoteConfig._maxSendQueueSize = settings.getSendingQueueSize(); } UdsServer::~UdsServer() { _started.store(false); _ioContext->stop(); // Cancel all pending do-actions if (_worker.valid()) { _worker.get(); // Assure that no connection interferes with further cleanup of destructor } _registry->clear(); // Delete all clients not hold by a user } void UdsServer::setConnectCallback(const Connected& callback) noexcept { _remoteConfig._connectedCallback = callback; } void UdsServer::setDisconnectCallback(const Disconnected& callback) noexcept { _remoteConfig._disconnectedCallback = callback; } void UdsServer::setReceiveCallback(const Received& callback) noexcept { _remoteConfig._receivedCallback = callback; } void UdsServer::start() { if (_started.exchange(true)) { JOYNR_LOG_ERROR(logger(), "UDS server alreay started."); return; } _worker = std::async(&UdsServer::run, this); } void UdsServer::run() { bool isRetry = false; while (_started.load()) { if (isRetry) { // Wait before retry to open socket so that worker does not block everything std::this_thread::sleep_for(_openSleepTime); _ioContext->reset(); } if (remove(_endpoint.path().c_str())) { JOYNR_LOG_WARN(logger(), "UDS server path {} already exists. Replacing existing path.", _endpoint.path()); } isRetry = true; try { _acceptor.open(_endpoint.protocol()); _acceptor.bind(_endpoint); _acceptor.listen(); JOYNR_LOG_INFO( logger(), "UDS server wating for connections on path {}.", _endpoint.path()); doAcceptClient(); _ioContext->run(); } catch (const boost::system::system_error& error) { JOYNR_LOG_ERROR( logger(), "UDS server encountered an error and will restart: {}", error.what()); } boost::system::error_code ignore; _acceptor.close(ignore); } } void UdsServer::doAcceptClient() { _acceptor.async_accept(_newClientSocket, [this](boost::system::error_code acceptFailure) { if (acceptFailure) { JOYNR_LOG_ERROR(logger(), "UDS server failed to accept new client: {}", acceptFailure.message()); } else { auto newConnection = std::make_shared<Connection>(std::move(_newClientSocket), _ioContext, std::weak_ptr<Connection::Active>(_registry), _remoteConfig); _registry->insert(newConnection); JOYNR_LOG_INFO( logger(), "Connection request received from new client. {:d} clients are registered.", _registry->size()); newConnection->doReadInitHeader(); } doAcceptClient(); }); } UdsServer::Connection::Connection(uds::socket&& socket, std::shared_ptr<boost::asio::io_service> ioContext, std::weak_ptr<Active> registry, const ConnectionConfig& config) noexcept : _socket(std::move(socket)), _ioContext(std::move(ioContext)), _registry(std::move(registry)), _connectedCallback{config._connectedCallback}, _disconnectedCallback{config._disconnectedCallback}, _receivedCallback{config._receivedCallback}, _closedDueToError{false}, _sendQueue(std::make_unique<UdsSendQueue<UdsFrameBufferV1>>(config._maxSendQueueSize)), _readBuffer(std::make_unique<UdsFrameBufferV1>()) { } UdsServer::Connection::~Connection() { // Ignore any errors caused by the following socket closure. const auto closedDueToError = _closedDueToError.load(); // Assure that all enqueued actions are removed from the pool which might us the send queue boost::system::error_code ignore; _socket.close(ignore); if (closedDueToError) { _sendQueue->emptyQueueAndNotify("Connection lost to " + _address.getId()); } } void UdsServer::Connection::doReadInitHeader() { boost::asio::async_read(_socket, _readBuffer->header(), [this](boost::system::error_code readFailure, std::size_t /*length*/) { if (doCheck(readFailure)) { doReadInitBody(); } }); } void UdsServer::Connection::doReadInitBody() { try { boost::asio::async_read(_socket, _readBuffer->body(), [this](boost::system::error_code readFailure, std::size_t /*length*/) { if (doCheck(readFailure)) { try { _address = _readBuffer->readInit(); JOYNR_LOG_INFO(logger(), "Initialize connection for UDS client id: {}", _address.getId()); _connectedCallback(_address, this->shared_from_this()); doReadHeader(); } catch (const std::exception& e) { std::string id = _address.getId(); if (id.empty()) { id = "[unknown ID]"; } JOYNR_LOG_FATAL( logger(), "Failed to initialize UDS connection '{}': {}", id, e.what()); doClose(); } } }); } catch (const std::exception& e) { JOYNR_LOG_FATAL(logger(), "Failed to read init-frame for new UDS connection: {}", e.what()); doClose(); } } void UdsServer::Connection::doReadHeader() { boost::asio::async_read(_socket, _readBuffer->header(), [this](boost::system::error_code readFailure, std::size_t /*length*/) { if (doCheck(readFailure)) { doReadBody(); } }); } void UdsServer::Connection::doReadBody() { try { boost::asio::async_read( _socket, _readBuffer->body(), [this](boost::system::error_code readFailure, std::size_t /*length*/) { if (doCheck(readFailure)) { try { _receivedCallback(_address, _readBuffer->readMessage()); } catch (const std::exception& e) { JOYNR_LOG_FATAL(logger(), "Failed to process UDS message from '{}': {}", _address.getId(), e.what()); doClose(); } doReadHeader(); } }); } catch (const std::exception& e) { JOYNR_LOG_FATAL(logger(), "Failed to read UDS message-frame from '{}': {}", _address.getId(), e.what()); doClose(); } } void UdsServer::Connection::send(const smrf::ByteArrayView& msg, const IUdsSender::SendFailed& callback) { try { _ioContext->post([ this, frame = UdsFrameBufferV1(msg), callback ]() mutable { if (_sendQueue->pushBack(std::move(frame), callback)) { doWrite(); } }); } catch (const std::exception& e) { JOYNR_LOG_FATAL( logger(), "Failed insert UDS message for '{}': {}", _address.getId(), e.what()); doClose(); } } void UdsServer::Connection::doWrite() { boost::asio::async_write(_socket, _sendQueue->showFront(), [this](boost::system::error_code writeFailed, std::size_t /*length*/) { doCheck(writeFailed); if (_sendQueue->popFrontOnSuccess(writeFailed)) { doWrite(); } }); } bool UdsServer::Connection::doCheck(const boost::system::error_code& error) { if (error) { JOYNR_LOG_INFO(logger(), "UDS remote client connection disconnected: {}", error.message()); doClose(); return false; } return true; } void UdsServer::Connection::doClose() { if (!_closedDueToError.exchange(true)) { if (!_address.getId().empty()) { _disconnectedCallback(_address); } boost::system::error_code ignore; _socket.close(ignore); _ioContext->post([ removeMe = shared_from_this(), registry = _registry ]() { auto registryLock = registry.lock(); if (registryLock) { registryLock->erase(removeMe); } }); } } } // namespace joynr <commit_msg>[C++] Fix UDS server log statements for socket binding.<commit_after>/* * #%L * %% * Copyright (C) 2020 BMW Car IT GmbH * %% * 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. * #L% */ #include <cstdio> #include <boost/format.hpp> #include "joynr/UdsServer.h" #include "joynr/Logger.h" #include "UdsFrameBufferV1.h" #include "UdsSendQueue.h" namespace joynr { constexpr char UdsServer::_initMessageStart[]; constexpr int UdsServer::_threadsPerServer; UdsServer::UdsServer(const UdsSettings& settings) noexcept : _ioContext(std::make_shared<boost::asio::io_service>(_threadsPerServer)), _registry{std::make_shared<Connection::Active>()}, _openSleepTime{settings.getConnectSleepTimeMs()}, _endpoint(settings.getSocketPath()), _acceptor(*_ioContext), _newClientSocket(*_ioContext), _started{false} { _remoteConfig._maxSendQueueSize = settings.getSendingQueueSize(); } UdsServer::~UdsServer() { _started.store(false); _ioContext->stop(); // Cancel all pending do-actions if (_worker.valid()) { _worker.get(); // Assure that no connection interferes with further cleanup of destructor } _registry->clear(); // Delete all clients not hold by a user } void UdsServer::setConnectCallback(const Connected& callback) noexcept { _remoteConfig._connectedCallback = callback; } void UdsServer::setDisconnectCallback(const Disconnected& callback) noexcept { _remoteConfig._disconnectedCallback = callback; } void UdsServer::setReceiveCallback(const Received& callback) noexcept { _remoteConfig._receivedCallback = callback; } void UdsServer::start() { if (_started.exchange(true)) { JOYNR_LOG_ERROR(logger(), "UDS server alreay started."); return; } _worker = std::async(&UdsServer::run, this); } void UdsServer::run() { bool isRetry = false; while (_started.load()) { if (isRetry) { // Wait before retry to open socket so that worker does not block everything std::this_thread::sleep_for(_openSleepTime); _ioContext->reset(); } if (0 == remove(_endpoint.path().c_str())) { JOYNR_LOG_WARN(logger(), "UDS server path {} already exists. Replacing existing path.", _endpoint.path()); } isRetry = true; try { _acceptor.open(_endpoint.protocol()); _acceptor.bind(_endpoint); _acceptor.listen(); JOYNR_LOG_INFO(logger(), "Waiting for connections on path {}.", _endpoint.path()); doAcceptClient(); _ioContext->run(); } catch (const boost::system::system_error& error) { JOYNR_LOG_ERROR(logger(), "UDS server ({}) encountered an error and will restart: {}", _endpoint.path(), error.what()); } boost::system::error_code ignore; _acceptor.close(ignore); } } void UdsServer::doAcceptClient() { _acceptor.async_accept(_newClientSocket, [this](boost::system::error_code acceptFailure) { if (acceptFailure) { JOYNR_LOG_ERROR(logger(), "UDS server failed to accept new client: {}", acceptFailure.message()); } else { auto newConnection = std::make_shared<Connection>(std::move(_newClientSocket), _ioContext, std::weak_ptr<Connection::Active>(_registry), _remoteConfig); _registry->insert(newConnection); JOYNR_LOG_INFO( logger(), "Connection request received from new client. {:d} clients are registered.", _registry->size()); newConnection->doReadInitHeader(); } doAcceptClient(); }); } UdsServer::Connection::Connection(uds::socket&& socket, std::shared_ptr<boost::asio::io_service> ioContext, std::weak_ptr<Active> registry, const ConnectionConfig& config) noexcept : _socket(std::move(socket)), _ioContext(std::move(ioContext)), _registry(std::move(registry)), _connectedCallback{config._connectedCallback}, _disconnectedCallback{config._disconnectedCallback}, _receivedCallback{config._receivedCallback}, _closedDueToError{false}, _sendQueue(std::make_unique<UdsSendQueue<UdsFrameBufferV1>>(config._maxSendQueueSize)), _readBuffer(std::make_unique<UdsFrameBufferV1>()) { } UdsServer::Connection::~Connection() { // Ignore any errors caused by the following socket closure. const auto closedDueToError = _closedDueToError.load(); // Assure that all enqueued actions are removed from the pool which might us the send queue boost::system::error_code ignore; _socket.close(ignore); if (closedDueToError) { _sendQueue->emptyQueueAndNotify("Connection lost to " + _address.getId()); } } void UdsServer::Connection::doReadInitHeader() { boost::asio::async_read(_socket, _readBuffer->header(), [this](boost::system::error_code readFailure, std::size_t /*length*/) { if (doCheck(readFailure)) { doReadInitBody(); } }); } void UdsServer::Connection::doReadInitBody() { try { boost::asio::async_read(_socket, _readBuffer->body(), [this](boost::system::error_code readFailure, std::size_t /*length*/) { if (doCheck(readFailure)) { try { _address = _readBuffer->readInit(); JOYNR_LOG_INFO(logger(), "Initialize connection for UDS client id: {}", _address.getId()); _connectedCallback(_address, this->shared_from_this()); doReadHeader(); } catch (const std::exception& e) { std::string id = _address.getId(); if (id.empty()) { id = "[unknown ID]"; } JOYNR_LOG_FATAL( logger(), "Failed to initialize UDS connection '{}': {}", id, e.what()); doClose(); } } }); } catch (const std::exception& e) { JOYNR_LOG_FATAL(logger(), "Failed to read init-frame for new UDS connection: {}", e.what()); doClose(); } } void UdsServer::Connection::doReadHeader() { boost::asio::async_read(_socket, _readBuffer->header(), [this](boost::system::error_code readFailure, std::size_t /*length*/) { if (doCheck(readFailure)) { doReadBody(); } }); } void UdsServer::Connection::doReadBody() { try { boost::asio::async_read( _socket, _readBuffer->body(), [this](boost::system::error_code readFailure, std::size_t /*length*/) { if (doCheck(readFailure)) { try { _receivedCallback(_address, _readBuffer->readMessage()); } catch (const std::exception& e) { JOYNR_LOG_FATAL(logger(), "Failed to process UDS message from '{}': {}", _address.getId(), e.what()); doClose(); } doReadHeader(); } }); } catch (const std::exception& e) { JOYNR_LOG_FATAL(logger(), "Failed to read UDS message-frame from '{}': {}", _address.getId(), e.what()); doClose(); } } void UdsServer::Connection::send(const smrf::ByteArrayView& msg, const IUdsSender::SendFailed& callback) { try { _ioContext->post([ this, frame = UdsFrameBufferV1(msg), callback ]() mutable { if (_sendQueue->pushBack(std::move(frame), callback)) { doWrite(); } }); } catch (const std::exception& e) { JOYNR_LOG_FATAL( logger(), "Failed insert UDS message for '{}': {}", _address.getId(), e.what()); doClose(); } } void UdsServer::Connection::doWrite() { boost::asio::async_write(_socket, _sendQueue->showFront(), [this](boost::system::error_code writeFailed, std::size_t /*length*/) { doCheck(writeFailed); if (_sendQueue->popFrontOnSuccess(writeFailed)) { doWrite(); } }); } bool UdsServer::Connection::doCheck(const boost::system::error_code& error) { if (error) { JOYNR_LOG_INFO(logger(), "UDS remote client connection disconnected: {}", error.message()); doClose(); return false; } return true; } void UdsServer::Connection::doClose() { if (!_closedDueToError.exchange(true)) { if (!_address.getId().empty()) { _disconnectedCallback(_address); } boost::system::error_code ignore; _socket.close(ignore); _ioContext->post([ removeMe = shared_from_this(), registry = _registry ]() { auto registryLock = registry.lock(); if (registryLock) { registryLock->erase(removeMe); } }); } } } // namespace joynr <|endoftext|>
<commit_before>/* Copyright (c) 2015, Daniel C. Dillon * 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. */ #include <dqtx/QDensityWidget.hpp> #include <QPainter> #include <QPen> #include <QPainterPath> #include <iostream> #include <QPaintEvent> #include <algorithm> #include <limits> #include <stdint.h> namespace dqtx { QDensityWidget::QDensityWidget(QWidget *_parent, Qt::WindowFlags _flags) : QWidget(_parent, _flags) , m_accumulator() , m_color(QColor(Qt::black)) , m_padding(5) , m_bandwidth(.5) , m_maxObservations(600) { QObject::connect(this, SIGNAL(observationInserted(double)), this, SLOT(onObservationInserted(double))); QObject::connect(this, SIGNAL(colorChanged(QColor)), this, SLOT(onColorChanged(QColor))); QObject::connect(this, SIGNAL(paddingChanged(int)), this, SLOT(onPaddingChanged(int))); QObject::connect(this, SIGNAL(maxObservationsChanged(int)), this, SLOT(onMaxObservationsChanged(int))); } void QDensityWidget::insertObservation(const double _data) { emit observationInserted(_data); } void QDensityWidget::setColor(const QColor &_color) { emit colorChanged(_color); } void QDensityWidget::setPadding(int _padding) { emit paddingChanged(_padding); } void QDensityWidget::setMaxObservations(int _max) { emit maxObservationsChanged(_max); } QSize QDensityWidget::sizeHint() const { return QSize(68, 29); } void QDensityWidget::paintEvent(QPaintEvent *_event) { QPainter painter(this); drawLine(painter, _event->rect(), m_padding, m_padding, m_padding, m_padding); } double QDensityWidget::density(double _x) { double sum = 0; QList< double >::iterator i = m_data.begin(); QList< double >::iterator iend = m_data.end(); for (; i != iend; ++i) { sum += silverman((_x - *i) / m_bandwidth); } sum *= 1 / (m_data.size() * m_bandwidth); return sum; } double QDensityWidget::normal(double _x) { return exp(-.5 * _x * _x) / (m_bandwidth * sqrt(2.0 * 3.1415926535898)); } void QDensityWidget::drawLine(QPainter &_painter, const QRect &_rect, int _leftPadding, int _rightPadding, int _topPadding, int _bottomPadding) { if (m_data.size() > 1) { int graphHeight = _rect.height() - _topPadding - _bottomPadding; int graphWidth = _rect.width() - _leftPadding - _rightPadding; QPoint bl = _rect.bottomLeft(); QPainterPath path; double minX = *std::min_element(m_data.begin(), m_data.end()); double maxX = *std::max_element(m_data.begin(), m_data.end()); const double extendX = 0 * (maxX - minX); minX -= extendX; maxX += extendX; double minY = std::numeric_limits< double >::max(); double maxY = std::numeric_limits< double >::min(); const double xStep = (maxX - minX) / double(graphWidth - 1); const double mean = boost::accumulators::mean(m_accumulator); double minDiffToMean = std::numeric_limits< double >::max(); double meanX = 0; QList< QPair< double, double > > points; for (double x = minX; x < maxX; x += xStep) { double y = density(x); points.push_back(QPair< double, double >(x, y)); minY = std::min(minY, y); maxY = std::max(maxY, y); const double diffToMean = fabs(mean - x); if (diffToMean < minDiffToMean) { meanX = x; minDiffToMean = diffToMean; } } const double yStep = double(graphHeight - 1) / (maxY); bool first = true; QList< QPair< double, double > >::iterator i = points.begin(); QList< QPair< double, double > >::iterator iend = points.end(); int x = _leftPadding; double y = -_bottomPadding; for (; i != iend; ++i) { y = -_bottomPadding - (yStep * i->second); if (first) { path.moveTo(int(bl.x() + x), int(bl.y() + y)); first = false; } else { path.lineTo(int(bl.x() + x), int(bl.y() + y)); } if (i->first == meanX) { _painter.setRenderHint(QPainter::Antialiasing, false); _painter.setPen(QPen(QColor(Qt::lightGray), 1, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin)); _painter.drawLine(bl.x() + x, bl.y() - _bottomPadding, bl.x() + x, bl.y() - _bottomPadding - graphHeight); } ++x; } if (!path.isEmpty()) { _painter.setRenderHint(QPainter::Antialiasing, true); _painter.setPen( QPen(m_color, 2, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin)); _painter.drawPath(path); } } } void QDensityWidget::onObservationInserted(double _data) { if (m_data.size() == m_maxObservations) { QList< double > newList; boost::accumulators::accumulator_set< double, boost::accumulators::stats< boost::accumulators::tag::variance, boost::accumulators::tag::mean > > accumulator; int index = 0; QList< double >::iterator i = m_data.begin(); QList< double >::iterator iend = m_data.end(); for (; i != iend; ++i) { if (index % 2) { newList.push_back(*i); accumulator(*i); } ++index; } m_data = newList; m_accumulator = accumulator; } m_data.push_back(_data); m_accumulator(_data); updateBandwidth(); updateToolTip(); update(); } void QDensityWidget::onColorChanged(QColor _color) { m_color = _color; update(); } void QDensityWidget::onPaddingChanged(int _padding) { m_padding = _padding; update(); } void QDensityWidget::onMaxObservationsChanged(int _max) { m_maxObservations = _max; while (m_data.size() > m_maxObservations) { QList< double > newList; boost::accumulators::accumulator_set< double, boost::accumulators::stats< boost::accumulators::tag::variance, boost::accumulators::tag::mean > > accumulator; int index = 0; QList< double >::iterator i = m_data.begin(); QList< double >::iterator iend = m_data.end(); for (; i != iend; ++i) { if (index % 2) { newList.push_back(*i); accumulator(*i); } ++index; } m_data = newList; m_accumulator = accumulator; } updateBandwidth(); updateToolTip(); update(); } void QDensityWidget::updateBandwidth() { const double variance = boost::accumulators::variance(m_accumulator); const double sigma = sqrt(variance); m_bandwidth = .9 * pow(m_data.size(), -.2) * sigma; //(std::min(sigma, interQuartile / 1.34)); } void QDensityWidget::updateToolTip() { const double variance = boost::accumulators::variance(m_accumulator); const double sigma = sqrt(variance); const double min = *std::min_element(m_data.begin(), m_data.end()); const double max = *std::max_element(m_data.begin(), m_data.end()); const double mean = boost::accumulators::mean(m_accumulator); setToolTip(QString("%1: %2\n%3: %4\nMin: %5\nMax: %6\nbw: %7") .arg(QString(QChar(0x03BC)), QString::number(mean), QString(QChar(0x03C3)), QString::number(sigma), QString::number(min), QString::number(max), QString::number(m_bandwidth))); } } // namespace dqtx <commit_msg>Fixed stupid bug where I left silverman in there<commit_after>/* Copyright (c) 2015, Daniel C. Dillon * 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. */ #include <dqtx/QDensityWidget.hpp> #include <QPainter> #include <QPen> #include <QPainterPath> #include <iostream> #include <QPaintEvent> #include <algorithm> #include <limits> #include <stdint.h> namespace dqtx { QDensityWidget::QDensityWidget(QWidget *_parent, Qt::WindowFlags _flags) : QWidget(_parent, _flags) , m_accumulator() , m_color(QColor(Qt::black)) , m_padding(5) , m_bandwidth(.5) , m_maxObservations(600) { QObject::connect(this, SIGNAL(observationInserted(double)), this, SLOT(onObservationInserted(double))); QObject::connect(this, SIGNAL(colorChanged(QColor)), this, SLOT(onColorChanged(QColor))); QObject::connect(this, SIGNAL(paddingChanged(int)), this, SLOT(onPaddingChanged(int))); QObject::connect(this, SIGNAL(maxObservationsChanged(int)), this, SLOT(onMaxObservationsChanged(int))); } void QDensityWidget::insertObservation(const double _data) { emit observationInserted(_data); } void QDensityWidget::setColor(const QColor &_color) { emit colorChanged(_color); } void QDensityWidget::setPadding(int _padding) { emit paddingChanged(_padding); } void QDensityWidget::setMaxObservations(int _max) { emit maxObservationsChanged(_max); } QSize QDensityWidget::sizeHint() const { return QSize(68, 29); } void QDensityWidget::paintEvent(QPaintEvent *_event) { QPainter painter(this); drawLine(painter, _event->rect(), m_padding, m_padding, m_padding, m_padding); } double QDensityWidget::density(double _x) { double sum = 0; QList< double >::iterator i = m_data.begin(); QList< double >::iterator iend = m_data.end(); for (; i != iend; ++i) { sum += normal((_x - *i) / m_bandwidth); } sum *= 1 / (m_data.size() * m_bandwidth); return sum; } double QDensityWidget::normal(double _x) { return exp(-.5 * _x * _x) / (m_bandwidth * sqrt(2.0 * 3.1415926535898)); } void QDensityWidget::drawLine(QPainter &_painter, const QRect &_rect, int _leftPadding, int _rightPadding, int _topPadding, int _bottomPadding) { if (m_data.size() > 1) { int graphHeight = _rect.height() - _topPadding - _bottomPadding; int graphWidth = _rect.width() - _leftPadding - _rightPadding; QPoint bl = _rect.bottomLeft(); QPainterPath path; double minX = *std::min_element(m_data.begin(), m_data.end()); double maxX = *std::max_element(m_data.begin(), m_data.end()); const double extendX = 0 * (maxX - minX); minX -= extendX; maxX += extendX; double minY = std::numeric_limits< double >::max(); double maxY = std::numeric_limits< double >::min(); const double xStep = (maxX - minX) / double(graphWidth - 1); const double mean = boost::accumulators::mean(m_accumulator); double minDiffToMean = std::numeric_limits< double >::max(); double meanX = 0; QList< QPair< double, double > > points; for (double x = minX; x < maxX; x += xStep) { double y = density(x); points.push_back(QPair< double, double >(x, y)); minY = std::min(minY, y); maxY = std::max(maxY, y); const double diffToMean = fabs(mean - x); if (diffToMean < minDiffToMean) { meanX = x; minDiffToMean = diffToMean; } } const double yStep = double(graphHeight - 1) / (maxY); bool first = true; QList< QPair< double, double > >::iterator i = points.begin(); QList< QPair< double, double > >::iterator iend = points.end(); int x = _leftPadding; double y = -_bottomPadding; for (; i != iend; ++i) { y = -_bottomPadding - (yStep * i->second); if (first) { path.moveTo(int(bl.x() + x), int(bl.y() + y)); first = false; } else { path.lineTo(int(bl.x() + x), int(bl.y() + y)); } if (i->first == meanX) { _painter.setRenderHint(QPainter::Antialiasing, false); _painter.setPen(QPen(QColor(Qt::lightGray), 1, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin)); _painter.drawLine(bl.x() + x, bl.y() - _bottomPadding, bl.x() + x, bl.y() - _bottomPadding - graphHeight); } ++x; } if (!path.isEmpty()) { _painter.setRenderHint(QPainter::Antialiasing, true); _painter.setPen( QPen(m_color, 2, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin)); _painter.drawPath(path); } } } void QDensityWidget::onObservationInserted(double _data) { if (m_data.size() == m_maxObservations) { QList< double > newList; boost::accumulators::accumulator_set< double, boost::accumulators::stats< boost::accumulators::tag::variance, boost::accumulators::tag::mean > > accumulator; int index = 0; QList< double >::iterator i = m_data.begin(); QList< double >::iterator iend = m_data.end(); for (; i != iend; ++i) { if (index % 2) { newList.push_back(*i); accumulator(*i); } ++index; } m_data = newList; m_accumulator = accumulator; } m_data.push_back(_data); m_accumulator(_data); updateBandwidth(); updateToolTip(); update(); } void QDensityWidget::onColorChanged(QColor _color) { m_color = _color; update(); } void QDensityWidget::onPaddingChanged(int _padding) { m_padding = _padding; update(); } void QDensityWidget::onMaxObservationsChanged(int _max) { m_maxObservations = _max; while (m_data.size() > m_maxObservations) { QList< double > newList; boost::accumulators::accumulator_set< double, boost::accumulators::stats< boost::accumulators::tag::variance, boost::accumulators::tag::mean > > accumulator; int index = 0; QList< double >::iterator i = m_data.begin(); QList< double >::iterator iend = m_data.end(); for (; i != iend; ++i) { if (index % 2) { newList.push_back(*i); accumulator(*i); } ++index; } m_data = newList; m_accumulator = accumulator; } updateBandwidth(); updateToolTip(); update(); } void QDensityWidget::updateBandwidth() { const double variance = boost::accumulators::variance(m_accumulator); const double sigma = sqrt(variance); m_bandwidth = .9 * pow(m_data.size(), -.2) * sigma; //(std::min(sigma, interQuartile / 1.34)); } void QDensityWidget::updateToolTip() { const double variance = boost::accumulators::variance(m_accumulator); const double sigma = sqrt(variance); const double min = *std::min_element(m_data.begin(), m_data.end()); const double max = *std::max_element(m_data.begin(), m_data.end()); const double mean = boost::accumulators::mean(m_accumulator); setToolTip(QString("%1: %2\n%3: %4\nMin: %5\nMax: %6\nbw: %7") .arg(QString(QChar(0x03BC)), QString::number(mean), QString(QChar(0x03C3)), QString::number(sigma), QString::number(min), QString::number(max), QString::number(m_bandwidth))); } } // namespace dqtx <|endoftext|>
<commit_before>#include <Rcpp.h> #include <iostream> using namespace std; using namespace Rcpp; #include"somoclu.h" RcppExport SEXP Rtrain(SEXP data_p, SEXP nEpoch_p, SEXP nSomX_p, SEXP nSomY_p, SEXP radius0_p, SEXP radiusN_p, SEXP radiusCooling_p, SEXP scale0_p, SEXP scaleN_p, SEXP scaleCooling_p, SEXP kernelType_p, SEXP mapType_p, SEXP gridType_p, SEXP compactSupport_p, SEXP neighborhood_p, SEXP codebook_p) { Rcpp::NumericMatrix dataMatrix(data_p); Rcpp::NumericVector codebook_vec(codebook_p); int nVectors = dataMatrix.rows(); int nDimensions = dataMatrix.cols(); int nEpoch = as<int>(nEpoch_p); unsigned int nSomX = (unsigned int) as<int> (nSomX_p); unsigned int nSomY = (unsigned int) as<int> (nSomY_p); unsigned int radius0 = (unsigned int) as<int> (radius0_p); unsigned int radiusN = (unsigned int) as<int> (radiusN_p); string radiusCooling = as<string>(radiusCooling_p); unsigned int scale0 = (unsigned int) as<int> (scale0_p); unsigned int scaleN = (unsigned int) as<int> (scaleN_p); string scaleCooling = as<string> (scaleCooling_p); unsigned int kernelType = (unsigned int) as<int>(kernelType_p); bool compactSupport = as<bool>(compactSupport_p); string mapType = as<string>(mapType_p); string gridType = as<string>(gridType_p); string neighborhood = as<string>(neighborhood_p); int data_length = nVectors * nDimensions; float* data = new float[data_length]; int uMatrix_size = nSomX * nSomY; // convert matrix to data c float array for(int i = 0; i < nVectors; i++) { for(int j = 0; j < nDimensions; j++) { data[i * nDimensions + j] = (float) dataMatrix(i, j); } } int codebook_size = nSomY * nSomX * nDimensions; float* codebook = new float[codebook_size]; for(int i = 0; i < uMatrix_size; i++) { for(int j = 0; j < nDimensions; j++) { codebook[i * nDimensions + j] = (float) codebook_vec(i ,j); } } int globalBmus_size = nVectors * 2; int* globalBmus = new int[globalBmus_size]; float* uMatrix = new float[uMatrix_size]; train(data, data_length, nEpoch, nSomX, nSomY, nDimensions, nVectors, radius0, radiusN, radiusCooling, scale0, scaleN, scaleCooling, kernelType, mapType, gridType, compactSupport, neighborhood == "gaussian", codebook, codebook_size, globalBmus, globalBmus_size, uMatrix, uMatrix_size); Rcpp::NumericVector globalBmus_vec(globalBmus_size); Rcpp::NumericVector uMatrix_vec(uMatrix_size); if(codebook != NULL) { for(int i = 0; i < uMatrix_size; i++) { for(int j = 0; j < nDimensions; j++) { codebook_vec(i ,j) = (float) codebook[i * nDimensions + j]; } } } if(globalBmus != NULL) { for(int i = 0; i < globalBmus_size; i++) { globalBmus_vec(i) = globalBmus[i]; } } if(uMatrix != NULL) { for(int i = 0; i < uMatrix_size; i++) { uMatrix_vec(i) = uMatrix[i]; } } delete[] codebook; delete[] globalBmus; delete[] uMatrix; return Rcpp::List::create(Rcpp::Named("codebook") = codebook_vec, Rcpp::Named("globalBmus") = globalBmus_vec, Rcpp::Named("uMatrix") = uMatrix_vec);; } RCPP_MODULE(Rsomoclu) { Rcpp::function("Rtrain", &Rtrain); } <commit_msg>return matrix<commit_after>#include <Rcpp.h> #include <iostream> using namespace std; using namespace Rcpp; #include"somoclu.h" RcppExport SEXP Rtrain(SEXP data_p, SEXP nEpoch_p, SEXP nSomX_p, SEXP nSomY_p, SEXP radius0_p, SEXP radiusN_p, SEXP radiusCooling_p, SEXP scale0_p, SEXP scaleN_p, SEXP scaleCooling_p, SEXP kernelType_p, SEXP mapType_p, SEXP gridType_p, SEXP compactSupport_p, SEXP neighborhood_p, SEXP codebook_p) { Rcpp::NumericMatrix dataMatrix(data_p); Rcpp::NumericMatrix codebookMatrix(codebook_p); int nVectors = dataMatrix.rows(); int nDimensions = dataMatrix.cols(); int nEpoch = as<int>(nEpoch_p); unsigned int nSomX = (unsigned int) as<int> (nSomX_p); unsigned int nSomY = (unsigned int) as<int> (nSomY_p); unsigned int radius0 = (unsigned int) as<int> (radius0_p); unsigned int radiusN = (unsigned int) as<int> (radiusN_p); string radiusCooling = as<string>(radiusCooling_p); unsigned int scale0 = (unsigned int) as<int> (scale0_p); unsigned int scaleN = (unsigned int) as<int> (scaleN_p); string scaleCooling = as<string> (scaleCooling_p); unsigned int kernelType = (unsigned int) as<int>(kernelType_p); bool compactSupport = as<bool>(compactSupport_p); string mapType = as<string>(mapType_p); string gridType = as<string>(gridType_p); string neighborhood = as<string>(neighborhood_p); int data_length = nVectors * nDimensions; float* data = new float[data_length]; int uMatrix_size = nSomX * nSomY; // convert matrix to data c float array for(int i = 0; i < nVectors; i++) { for(int j = 0; j < nDimensions; j++) { data[i * nDimensions + j] = (float) dataMatrix(i, j); } } int codebook_size = nSomY * nSomX * nDimensions; float* codebook = new float[codebook_size]; for(int i = 0; i < uMatrix_size; i++) { for(int j = 0; j < nDimensions; j++) { codebook[i * nDimensions + j] = (float) codebookMatrix(i ,j); } } int globalBmus_size = nVectors * 2; int* globalBmus = new int[globalBmus_size]; float* uMatrix = new float[uMatrix_size]; train(data, data_length, nEpoch, nSomX, nSomY, nDimensions, nVectors, radius0, radiusN, radiusCooling, scale0, scaleN, scaleCooling, kernelType, mapType, gridType, compactSupport, neighborhood == "gaussian", codebook, codebook_size, globalBmus, globalBmus_size, uMatrix, uMatrix_size); Rcpp::NumericMatrix globalBmusMatrix(nVectors, 2); Rcpp::NumericMatrix uMatrixMatrix(nSomX, nSomY); if(codebook != NULL) { for(int i = 0; i < uMatrix_size; i++) { for(int j = 0; j < nDimensions; j++) { codebookMatrix(i ,j) = (float) codebook[i * nDimensions + j]; } } } if(globalBmus != NULL) { for(int i = 0; i < nVectors; i++) { for (int j = 0; j < 2; j++) { globalBmusMatrix(i, j) = globalBmus[i * 2 + j]; } } } if(uMatrix != NULL) { for(int i = 0; i < nSomX; i++) { for (int j = 0; j < nSomY; j++) { uMatrixMatrix(i, j) = uMatrix[i * nSomY + j]; } } } delete[] codebook; delete[] globalBmus; delete[] uMatrix; return Rcpp::List::create(Rcpp::Named("codebook") = codebookMatrix, Rcpp::Named("globalBmus") = globalBmusMatrix, Rcpp::Named("uMatrix") = uMatrixMatrix);; } RCPP_MODULE(Rsomoclu) { Rcpp::function("Rtrain", &Rtrain); } <|endoftext|>
<commit_before>/** * @file cache.cpp * * @date Nov 21, 2012 * @author perämäki */ #include "cache.h" #include "logger_factory.h" #include "info.h" #include <time.h> #include "plugin_factory.h" #include <boost/lexical_cast.hpp> using namespace std; using namespace himan::plugin; typedef lock_guard<mutex> Lock; cache::cache() { itsLogger = std::unique_ptr<logger> (logger_factory::Instance()->GetLog("cache")); } string cache::UniqueName(const shared_ptr<const himan::info> info) { string forecast_time = info->Time().OriginDateTime()->String("%Y-%m-%d_%H:%M:%S"); string valid_time = info->Time().ValidDateTime()->String("%Y-%m-%d_%H:%M:%S"); string param = info->Param().Name(); string projection = boost::lexical_cast<string> (info->Projection()); string level_value = boost::lexical_cast<string>(info->Level().Value()); string level = HPLevelTypeToString.at(info->Level().Type()); return forecast_time + '_' + valid_time + '_' + param + '_' + level + '_' + projection + '_' + level_value; } string cache::UniqueNameFromOptions(const search_options& options) { string forecast_time = (options.time.OriginDateTime())->String("%Y-%m-%d_%H:%M:%S"); string valid_time = (options.time.ValidDateTime())->String("%Y-%m-%d_%H:%M:%S"); string param = (options.param).Name(); string projection = (options.configuration)->TargetProjection(); string level_value = boost::lexical_cast<string>((options.level).Value()); string level = HPLevelTypeToString.at(options.level.Type()); return forecast_time + '_' + valid_time + '_' + param + '_' + level + '_' + projection + '_' + level_value; } void cache::Insert(shared_ptr<himan::info> anInfo, bool activeOnly) { if (activeOnly) { SplitToPool(anInfo); } else { for (anInfo->ResetTime(); anInfo->NextTime(); ) { for (anInfo->ResetLevel(); anInfo->NextLevel(); ) { for (anInfo->ResetParam(); anInfo->NextParam(); ) { SplitToPool(anInfo); } } } } } void cache::SplitToPool(const shared_ptr<info> anInfo) { vector<param> params; vector<level> levels; vector<forecast_time> times; params.push_back(anInfo->Param()); levels.push_back(anInfo->Level()); times.push_back(anInfo->Time()); shared_ptr<grid> aGrid = anInfo->Grid(); shared_ptr<info> newInfo (new info(*anInfo)); newInfo->Params(params); newInfo->Levels(levels); newInfo->Times(times); newInfo->Create(); newInfo->First(); newInfo->Grid(aGrid); string uniqueName = UniqueName(newInfo); if (!(cache_pool::Instance()->Find(uniqueName))) { cache_pool::Instance()->Insert(uniqueName, newInfo); } } void cache::Insert(const vector<shared_ptr<himan::info>>& infos, bool activeOnly) { for (size_t i = 0; i < infos.size(); i++) { Insert(infos[i], activeOnly); //Clean(); } } vector<shared_ptr<himan::info>> cache::GetInfo(const search_options& options) { string uniqueName = UniqueNameFromOptions(options); vector<shared_ptr<himan::info>> info; if (cache_pool::Instance()->Find(uniqueName)) { info.push_back(cache_pool::Instance()->GetInfo(uniqueName)); itsLogger->Debug( "Found matching data for " + uniqueName); } return info; } void cache::Clean() { cache_pool::Instance()->Clean(); } cache_pool* cache_pool::itsInstance = NULL; cache_pool::cache_pool() { itsLogger = std::unique_ptr<logger> (logger_factory::Instance()->GetLog("cache_pool")); } cache_pool* cache_pool::Instance() { if (!itsInstance) { itsInstance = new cache_pool(); } return itsInstance; } bool cache_pool::Find(const string& uniqueName) { for (map<string, shared_ptr<himan::info>>::iterator it = itsCache.begin(); it != itsCache.end(); ++it) { if (it->first == uniqueName) { return true; } } return false; } void cache_pool::Insert(const string& uniqueName, shared_ptr<himan::info> anInfo) { Lock lock(itsInsertMutex); itsCache.insert(pair<string, shared_ptr<himan::info>>(uniqueName, anInfo)); time_t timer; time(&timer); itsCacheItems.insert(pair<string, time_t>(uniqueName, timer)); itsLogger->Debug("Data added to cache. UniqueName: " + uniqueName); } void cache_pool::Clean() { Lock lock(itsDeleteMutex); for (map<string, time_t>::iterator it = itsCacheItems.begin(); it != itsCacheItems.end(); ++it) { time_t timer; time(&timer); if (timer - it->second > 10) { string name = it->first; itsCache.erase(name); itsCacheItems.erase(name); itsLogger->Debug("Data cleared from cache: " + name); } } } shared_ptr<himan::info> cache_pool::GetInfo(const string& uniqueName) { Lock lock(itsGetMutex); return itsCache[uniqueName]; } <commit_msg>Changing log level<commit_after>/** * @file cache.cpp * * @date Nov 21, 2012 * @author perämäki */ #include "cache.h" #include "logger_factory.h" #include "info.h" #include <time.h> #include "plugin_factory.h" #include <boost/lexical_cast.hpp> using namespace std; using namespace himan::plugin; typedef lock_guard<mutex> Lock; cache::cache() { itsLogger = std::unique_ptr<logger> (logger_factory::Instance()->GetLog("cache")); } string cache::UniqueName(const shared_ptr<const himan::info> info) { string forecast_time = info->Time().OriginDateTime()->String("%Y-%m-%d_%H:%M:%S"); string valid_time = info->Time().ValidDateTime()->String("%Y-%m-%d_%H:%M:%S"); string param = info->Param().Name(); string level_value = boost::lexical_cast<string>(info->Level().Value()); string level = HPLevelTypeToString.at(info->Level().Type()); return forecast_time + '_' + valid_time + '_' + param + '_' + level + '_' + level_value; } string cache::UniqueNameFromOptions(const search_options& options) { string forecast_time = (options.time.OriginDateTime())->String("%Y-%m-%d_%H:%M:%S"); string valid_time = (options.time.ValidDateTime())->String("%Y-%m-%d_%H:%M:%S"); string param = (options.param).Name(); string level_value = boost::lexical_cast<string>((options.level).Value()); string level = HPLevelTypeToString.at(options.level.Type()); return forecast_time + '_' + valid_time + '_' + param + '_' + level + '_' + level_value; } void cache::Insert(shared_ptr<himan::info> anInfo, bool activeOnly) { if (activeOnly) { SplitToPool(anInfo); } else { for (anInfo->ResetTime(); anInfo->NextTime(); ) { for (anInfo->ResetLevel(); anInfo->NextLevel(); ) { for (anInfo->ResetParam(); anInfo->NextParam(); ) { SplitToPool(anInfo); } } } } } void cache::SplitToPool(const shared_ptr<info> anInfo) { vector<param> params; vector<level> levels; vector<forecast_time> times; params.push_back(anInfo->Param()); levels.push_back(anInfo->Level()); times.push_back(anInfo->Time()); shared_ptr<grid> aGrid = anInfo->Grid(); shared_ptr<info> newInfo (new info(*anInfo)); newInfo->Params(params); newInfo->Levels(levels); newInfo->Times(times); newInfo->Create(); newInfo->First(); newInfo->Grid(aGrid); string uniqueName = UniqueName(newInfo); if (!(cache_pool::Instance()->Find(uniqueName))) { cache_pool::Instance()->Insert(uniqueName, newInfo); } } void cache::Insert(const vector<shared_ptr<himan::info>>& infos, bool activeOnly) { for (size_t i = 0; i < infos.size(); i++) { Insert(infos[i], activeOnly); //Clean(); } } vector<shared_ptr<himan::info>> cache::GetInfo(const search_options& options) { string uniqueName = UniqueNameFromOptions(options); vector<shared_ptr<himan::info>> info; if (cache_pool::Instance()->Find(uniqueName)) { info.push_back(cache_pool::Instance()->GetInfo(uniqueName)); itsLogger->Trace( "Found matching data for " + uniqueName); } return info; } void cache::Clean() { cache_pool::Instance()->Clean(); } cache_pool* cache_pool::itsInstance = NULL; cache_pool::cache_pool() { itsLogger = std::unique_ptr<logger> (logger_factory::Instance()->GetLog("cache_pool")); } cache_pool* cache_pool::Instance() { if (!itsInstance) { itsInstance = new cache_pool(); } return itsInstance; } bool cache_pool::Find(const string& uniqueName) { for (map<string, shared_ptr<himan::info>>::iterator it = itsCache.begin(); it != itsCache.end(); ++it) { if (it->first == uniqueName) { return true; } } return false; } void cache_pool::Insert(const string& uniqueName, shared_ptr<himan::info> anInfo) { Lock lock(itsInsertMutex); itsCache.insert(pair<string, shared_ptr<himan::info>>(uniqueName, anInfo)); time_t timer; time(&timer); itsCacheItems.insert(pair<string, time_t>(uniqueName, timer)); itsLogger->Trace("Data added to cache. UniqueName: " + uniqueName); } void cache_pool::Clean() { Lock lock(itsDeleteMutex); for (map<string, time_t>::iterator it = itsCacheItems.begin(); it != itsCacheItems.end(); ++it) { time_t timer; time(&timer); if (timer - it->second > 10) { string name = it->first; itsCache.erase(name); itsCacheItems.erase(name); itsLogger->Trace("Data cleared from cache: " + name); } } } shared_ptr<himan::info> cache_pool::GetInfo(const string& uniqueName) { Lock lock(itsGetMutex); return itsCache[uniqueName]; } <|endoftext|>
<commit_before>/** * @file radon.cpp * * @date Oct 28, 2012 * @author tack */ #include "radon.h" #include "logger_factory.h" #include "plugin_factory.h" #include <thread> #include <sstream> #include "util.h" #include "unistd.h" // getuid()) #include "regular_grid.h" using namespace std; using namespace himan::plugin; const int MAX_WORKERS = 16; static once_flag oflag; radon::radon() : itsInit(false), itsRadonDB() { itsLogger = unique_ptr<logger> (logger_factory::Instance()->GetLog("radon")); // no lambda functions for gcc 4.4 :( // call_once(oflag, [](){ NFmiNeonsDBPool::MaxWorkers(MAX_WORKERS); }); call_once(oflag, &himan::plugin::radon::InitPool, this); } void radon::InitPool() { NFmiRadonDBPool::Instance()->MaxWorkers(MAX_WORKERS); uid_t uid = getuid(); if (uid == 1459) // weto { NFmiRadonDBPool::Instance()->Username("wetodb"); NFmiRadonDBPool::Instance()->Password("3loHRgdio"); } } vector<string> radon::Files(search_options& options) { Init(); vector<string> files; string analtime = options.time.OriginDateTime().String("%Y-%m-%d %H:%M:%S+00"); string levelvalue = boost::lexical_cast<string> (options.level.Value()); string ref_prod = options.prod.Name(); // long no_vers = options.prod.TableVersion(); string level_name = HPLevelTypeToString.at(options.level.Type()); vector<vector<string> > gridgeoms; vector<string> sourceGeoms = options.configuration->SourceGeomNames(); if (sourceGeoms.empty()) { // Get all geometries gridgeoms = itsRadonDB->GetGridGeoms(ref_prod, analtime); } else { for (size_t i = 0; i < sourceGeoms.size(); i++) { vector<vector<string>> geoms = itsRadonDB->GetGridGeoms(ref_prod, analtime, sourceGeoms[i]); gridgeoms.insert(gridgeoms.end(), geoms.begin(), geoms.end()); } } if (gridgeoms.empty()) { itsLogger->Warning("No geometries found for producer " + ref_prod + ", analysistime " + analtime + ", source geom name(s) '" + util::Join(sourceGeoms, ",") +"', param " + options.param.Name()); return files; } string forecastTypeValue = (options.ftype.Type() == kEpsPerturbation) ? boost::lexical_cast<string> (options.ftype.Value()) : "-1"; for (size_t i = 0; i < gridgeoms.size(); i++) { string tablename = gridgeoms[i][1]; string geomid = gridgeoms[i][0]; string parm_name = options.param.Name(); string query = "SELECT param_id, level_id, level_value, forecast_period, file_location, file_server " "FROM "+tablename+"_v " "WHERE analysis_time = '"+analtime+"' " "AND param_name = '"+parm_name+"' " "AND level_name = upper('"+level_name+"') " "AND level_value = "+levelvalue+" " "AND forecast_period = '"+util::MakeSQLInterval(options.time)+"' " "AND geometry_id = "+geomid+" " "AND forecast_type_id = "+boost::lexical_cast<string> (options.ftype.Type())+" " "AND forecast_type_value = "+forecastTypeValue+" " "ORDER BY forecast_period, level_id, level_value"; itsRadonDB->Query(query); vector<string> values = itsRadonDB->FetchRow(); if (values.empty()) { continue; } itsLogger->Trace("Found data for parameter " + parm_name + " from radon geometry " + gridgeoms[i][3]); files.push_back(values[4]); break; // discontinue loop on first positive match } return files; } bool radon::Save(const info& resultInfo, const string& theFileName) { Init(); stringstream query; if (resultInfo.Grid()->Type() != kRegularGrid) { itsLogger->Error("Only grid data can be stored to radon for now"); return false; } const regular_grid* g = dynamic_cast<regular_grid*> (resultInfo.Grid()); /* * 1. Get grid information * 2. Get model information * 3. Get data set information (ie model run) * 4. Insert or update */ himan::point firstGridPoint = g->FirstGridPoint(); // get grib1 gridType int gridType = -1; switch (g->Projection()) { case 10: gridType = 0; // latlon break; case 11: gridType = 10; // rot latlon break; case 13: gridType = 5; // polster break; default: throw runtime_error("Unsupported projection: " + HPProjectionTypeToString.at(g->Projection())); } auto geominfo = itsRadonDB->GetGeometryDefinition(g->Ni(), g->Nj(), firstGridPoint.Y(), firstGridPoint.X(), g->Di(), g->Dj(), 1, gridType); if (geominfo.empty()) { itsLogger->Warning("Grid geometry not found from radon"); return false; } string geom_id = geominfo["id"]; query.str(""); query << "SELECT " << "id, table_name " << "FROM as_grid " << "WHERE geometry_id = '" << geom_id << "'" << " AND analysis_time = '" << resultInfo.OriginDateTime().String("%Y-%m-%d %H:%M:%S+00") << "'" << " AND producer_id = " << resultInfo.Producer().Id(); itsRadonDB->Query(query.str()); auto row = itsRadonDB->FetchRow(); if (row.empty()) { itsLogger->Warning("Data set definition not found from radon"); return false; } string table_name = row[1]; string dset_id = row[0]; query.str(""); char host[255]; gethostname(host, 255); auto paraminfo = itsRadonDB->GetParameterFromDatabaseName(resultInfo.Producer().Id(), resultInfo.Param().Name()); if (paraminfo.empty()) { itsLogger->Error("Parameter information not found from radon for parameter " + resultInfo.Param().Name()); return false; } auto levelinfo = itsRadonDB->GetLevelFromGrib(resultInfo.Producer().Id(), resultInfo.Level().Type(), 1); if (levelinfo.empty()) { itsLogger->Error("Level information not found from radon for level " + resultInfo.Level().Name()); return false; } /* * We have our own error logging for unique key violations */ // itsRadonDB->Verbose(false); double forecastTypeValue = (resultInfo.ForecastType().Type() == kEpsPerturbation) ? resultInfo.ForecastType().Value() : -1.; string analysisTime = resultInfo.OriginDateTime().String("%Y-%m-%d %H:%M:%S+00"); query << "INSERT INTO data." << table_name << " (producer_id, analysis_time, geometry_id, param_id, level_id, level_value, forecast_period, forecast_type_id, forecast_type_value, file_location, file_server) VALUES (" << resultInfo.Producer().Id() << ", " << "'" << analysisTime << "', " << geom_id << ", " << paraminfo["id"] << ", " << levelinfo["id"] << ", " << resultInfo.Level().Value() << ", " << "'" << util::MakeSQLInterval(resultInfo.Time()) << "', " << resultInfo.ForecastType().Type() << ", " << forecastTypeValue << "," << "'" << theFileName << "', " << "'" << host << "')" ; try { itsRadonDB->Execute(query.str()); query.str(""); query << "UPDATE as_grid SET record_count = record_count+1 WHERE producer_id = " << resultInfo.Producer().Id() << " AND geometry_id = " << geom_id << " AND analysis_time = '" << analysisTime << "'"; itsRadonDB->Execute(query.str()); itsRadonDB->Commit(); } catch (const pqxx::unique_violation& e) { itsRadonDB->Rollback(); query.str(""); query << "UPDATE data." << table_name << " SET " << "file_location = '" << theFileName << "', " << "file_server = '" << host << "' WHERE " << "producer_id = " << resultInfo.Producer().Id() << " AND " << "analysis_time = '" << analysisTime << "' AND " << "geometry_id = " << geom_id << " AND " << "param_id = " << paraminfo["id"] << " AND " << "level_id = " << levelinfo["id"] << " AND " << "level_value = " << resultInfo.Level().Value() << " AND " << "forecast_period = " << "'" << util::MakeSQLInterval(resultInfo.Time()) << "' AND " << "forecast_type_id = " << resultInfo.ForecastType().Type() << " AND " << "forecast_type_value = " << forecastTypeValue; itsRadonDB->Execute(query.str()); itsRadonDB->Commit(); } itsLogger->Trace("Saved information on file '" + theFileName + "' to radon"); return true; } map<string,string> radon::Grib1ParameterName(long producer, long fmiParameterId, long codeTableVersion, long timeRangeIndicator, long levelId, double level_value) { Init(); map<string,string> paramName = itsRadonDB->GetParameterFromGrib1(producer, codeTableVersion, fmiParameterId, timeRangeIndicator, levelId, level_value); return paramName; } map<string,string> radon::Grib2ParameterName(long fmiParameterId, long category, long discipline, long producer, long levelId, double level_value) { Init(); map<string,string> paramName = itsRadonDB->GetParameterFromGrib2(producer, discipline, category, fmiParameterId, levelId, level_value); return paramName; } string radon::ProducerMetaData(long producerId, const string& attribute) const { string ret; if (attribute == "last hybrid level number") { switch (producerId) { case 1: case 199: case 210: case 230: ret = "65"; break; case 131: case 240: ret = "137"; break; default: throw runtime_error(ClassName() + ": Producer not supported"); break; } } else if (attribute == "first hybrid level number") { switch (producerId) { case 1: case 199: case 210: case 230: ret = "1"; break; case 131: case 240: ret = "24"; break; default: throw runtime_error(ClassName() + ": Producer not supported"); break; } } else { throw runtime_error(ClassName() + ": Attribute not recognized"); } return ret; // In the future maybe something like this: //Init(); //string query = "SELECT value FROM producers_eav WHERE producer_id = " + boost::lexical_cast<string> (producerId) + " AND attribute = '" + attribute + "'"; } <commit_msg>read analysis fields for ecmwf<commit_after>/** * @file radon.cpp * * @date Oct 28, 2012 * @author tack */ #include "radon.h" #include "logger_factory.h" #include "plugin_factory.h" #include <thread> #include <sstream> #include "util.h" #include "unistd.h" // getuid()) #include "regular_grid.h" using namespace std; using namespace himan::plugin; const int MAX_WORKERS = 16; static once_flag oflag; radon::radon() : itsInit(false), itsRadonDB() { itsLogger = unique_ptr<logger> (logger_factory::Instance()->GetLog("radon")); // no lambda functions for gcc 4.4 :( // call_once(oflag, [](){ NFmiNeonsDBPool::MaxWorkers(MAX_WORKERS); }); call_once(oflag, &himan::plugin::radon::InitPool, this); } void radon::InitPool() { NFmiRadonDBPool::Instance()->MaxWorkers(MAX_WORKERS); uid_t uid = getuid(); if (uid == 1459) // weto { NFmiRadonDBPool::Instance()->Username("wetodb"); NFmiRadonDBPool::Instance()->Password("3loHRgdio"); } } vector<string> radon::Files(search_options& options) { Init(); vector<string> files; string analtime = options.time.OriginDateTime().String("%Y-%m-%d %H:%M:%S+00"); string levelvalue = boost::lexical_cast<string> (options.level.Value()); string ref_prod = options.prod.Name(); // long no_vers = options.prod.TableVersion(); string level_name = HPLevelTypeToString.at(options.level.Type()); vector<vector<string> > gridgeoms; vector<string> sourceGeoms = options.configuration->SourceGeomNames(); if (sourceGeoms.empty()) { // Get all geometries gridgeoms = itsRadonDB->GetGridGeoms(ref_prod, analtime); } else { for (size_t i = 0; i < sourceGeoms.size(); i++) { vector<vector<string>> geoms = itsRadonDB->GetGridGeoms(ref_prod, analtime, sourceGeoms[i]); gridgeoms.insert(gridgeoms.end(), geoms.begin(), geoms.end()); } } if (gridgeoms.empty()) { itsLogger->Warning("No geometries found for producer " + ref_prod + ", analysistime " + analtime + ", source geom name(s) '" + util::Join(sourceGeoms, ",") +"', param " + options.param.Name()); return files; } string forecastTypeValue = (options.ftype.Type() == kEpsPerturbation) ? boost::lexical_cast<string> (options.ftype.Value()) : "-1"; string forecastTypeId = boost::lexical_cast<string> (options.ftype.Type()); if (options.time.Step() == 0 && options.ftype.Type() == 1) { // ECMWF (and maybe others) use forecast type id == 2 for analysis hour forecastTypeId += ",2"; } for (size_t i = 0; i < gridgeoms.size(); i++) { string tablename = gridgeoms[i][1]; string geomid = gridgeoms[i][0]; string parm_name = options.param.Name(); string query = "SELECT param_id, level_id, level_value, forecast_period, file_location, file_server " "FROM "+tablename+"_v " "WHERE analysis_time = '"+analtime+"' " "AND param_name = '"+parm_name+"' " "AND level_name = upper('"+level_name+"') " "AND level_value = "+levelvalue+" " "AND forecast_period = '"+util::MakeSQLInterval(options.time)+"' " "AND geometry_id = "+geomid+" " "AND forecast_type_id IN ("+forecastTypeId+") " "AND forecast_type_value = "+forecastTypeValue+" " "ORDER BY forecast_period, level_id, level_value"; itsRadonDB->Query(query); vector<string> values = itsRadonDB->FetchRow(); if (values.empty()) { continue; } itsLogger->Trace("Found data for parameter " + parm_name + " from radon geometry " + gridgeoms[i][3]); files.push_back(values[4]); break; // discontinue loop on first positive match } return files; } bool radon::Save(const info& resultInfo, const string& theFileName) { Init(); stringstream query; if (resultInfo.Grid()->Type() != kRegularGrid) { itsLogger->Error("Only grid data can be stored to radon for now"); return false; } const regular_grid* g = dynamic_cast<regular_grid*> (resultInfo.Grid()); /* * 1. Get grid information * 2. Get model information * 3. Get data set information (ie model run) * 4. Insert or update */ himan::point firstGridPoint = g->FirstGridPoint(); // get grib1 gridType int gridType = -1; switch (g->Projection()) { case 10: gridType = 0; // latlon break; case 11: gridType = 10; // rot latlon break; case 13: gridType = 5; // polster break; default: throw runtime_error("Unsupported projection: " + HPProjectionTypeToString.at(g->Projection())); } auto geominfo = itsRadonDB->GetGeometryDefinition(g->Ni(), g->Nj(), firstGridPoint.Y(), firstGridPoint.X(), g->Di(), g->Dj(), 1, gridType); if (geominfo.empty()) { itsLogger->Warning("Grid geometry not found from radon"); return false; } string geom_id = geominfo["id"]; query.str(""); query << "SELECT " << "id, table_name " << "FROM as_grid " << "WHERE geometry_id = '" << geom_id << "'" << " AND analysis_time = '" << resultInfo.OriginDateTime().String("%Y-%m-%d %H:%M:%S+00") << "'" << " AND producer_id = " << resultInfo.Producer().Id(); itsRadonDB->Query(query.str()); auto row = itsRadonDB->FetchRow(); if (row.empty()) { itsLogger->Warning("Data set definition not found from radon"); return false; } string table_name = row[1]; string dset_id = row[0]; query.str(""); char host[255]; gethostname(host, 255); auto paraminfo = itsRadonDB->GetParameterFromDatabaseName(resultInfo.Producer().Id(), resultInfo.Param().Name()); if (paraminfo.empty()) { itsLogger->Error("Parameter information not found from radon for parameter " + resultInfo.Param().Name()); return false; } auto levelinfo = itsRadonDB->GetLevelFromGrib(resultInfo.Producer().Id(), resultInfo.Level().Type(), 1); if (levelinfo.empty()) { itsLogger->Error("Level information not found from radon for level " + resultInfo.Level().Name()); return false; } /* * We have our own error logging for unique key violations */ // itsRadonDB->Verbose(false); double forecastTypeValue = (resultInfo.ForecastType().Type() == kEpsPerturbation) ? resultInfo.ForecastType().Value() : -1.; string analysisTime = resultInfo.OriginDateTime().String("%Y-%m-%d %H:%M:%S+00"); query << "INSERT INTO data." << table_name << " (producer_id, analysis_time, geometry_id, param_id, level_id, level_value, forecast_period, forecast_type_id, forecast_type_value, file_location, file_server) VALUES (" << resultInfo.Producer().Id() << ", " << "'" << analysisTime << "', " << geom_id << ", " << paraminfo["id"] << ", " << levelinfo["id"] << ", " << resultInfo.Level().Value() << ", " << "'" << util::MakeSQLInterval(resultInfo.Time()) << "', " << resultInfo.ForecastType().Type() << ", " << forecastTypeValue << "," << "'" << theFileName << "', " << "'" << host << "')" ; try { itsRadonDB->Execute(query.str()); query.str(""); query << "UPDATE as_grid SET record_count = record_count+1 WHERE producer_id = " << resultInfo.Producer().Id() << " AND geometry_id = " << geom_id << " AND analysis_time = '" << analysisTime << "'"; itsRadonDB->Execute(query.str()); itsRadonDB->Commit(); } catch (const pqxx::unique_violation& e) { itsRadonDB->Rollback(); query.str(""); query << "UPDATE data." << table_name << " SET " << "file_location = '" << theFileName << "', " << "file_server = '" << host << "' WHERE " << "producer_id = " << resultInfo.Producer().Id() << " AND " << "analysis_time = '" << analysisTime << "' AND " << "geometry_id = " << geom_id << " AND " << "param_id = " << paraminfo["id"] << " AND " << "level_id = " << levelinfo["id"] << " AND " << "level_value = " << resultInfo.Level().Value() << " AND " << "forecast_period = " << "'" << util::MakeSQLInterval(resultInfo.Time()) << "' AND " << "forecast_type_id = " << resultInfo.ForecastType().Type() << " AND " << "forecast_type_value = " << forecastTypeValue; itsRadonDB->Execute(query.str()); itsRadonDB->Commit(); } itsLogger->Trace("Saved information on file '" + theFileName + "' to radon"); return true; } map<string,string> radon::Grib1ParameterName(long producer, long fmiParameterId, long codeTableVersion, long timeRangeIndicator, long levelId, double level_value) { Init(); map<string,string> paramName = itsRadonDB->GetParameterFromGrib1(producer, codeTableVersion, fmiParameterId, timeRangeIndicator, levelId, level_value); return paramName; } map<string,string> radon::Grib2ParameterName(long fmiParameterId, long category, long discipline, long producer, long levelId, double level_value) { Init(); map<string,string> paramName = itsRadonDB->GetParameterFromGrib2(producer, discipline, category, fmiParameterId, levelId, level_value); return paramName; } string radon::ProducerMetaData(long producerId, const string& attribute) const { string ret; if (attribute == "last hybrid level number") { switch (producerId) { case 1: case 199: case 210: case 230: ret = "65"; break; case 131: case 240: ret = "137"; break; default: throw runtime_error(ClassName() + ": Producer not supported"); break; } } else if (attribute == "first hybrid level number") { switch (producerId) { case 1: case 199: case 210: case 230: ret = "1"; break; case 131: case 240: ret = "24"; break; default: throw runtime_error(ClassName() + ": Producer not supported"); break; } } else { throw runtime_error(ClassName() + ": Attribute not recognized"); } return ret; // In the future maybe something like this: //Init(); //string query = "SELECT value FROM producers_eav WHERE producer_id = " + boost::lexical_cast<string> (producerId) + " AND attribute = '" + attribute + "'"; } <|endoftext|>
<commit_before><commit_msg>Aborted setSource if no output formats are available<commit_after><|endoftext|>
<commit_before>/**************************************************************************** * * Copyright (c) 2019-2020 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #pragma once #include <stdint.h> namespace px4 { class WorkQueue; // forward declaration struct wq_config_t { const char *name; uint16_t stacksize; int8_t relative_priority; // relative to max }; namespace wq_configurations { static constexpr wq_config_t rate_ctrl{"wq:rate_ctrl", 1664, 0}; // PX4 inner loop highest priority static constexpr wq_config_t SPI0{"wq:SPI0", 2336, -1}; static constexpr wq_config_t SPI1{"wq:SPI1", 2336, -2}; static constexpr wq_config_t SPI2{"wq:SPI2", 2336, -3}; static constexpr wq_config_t SPI3{"wq:SPI3", 2336, -4}; static constexpr wq_config_t SPI4{"wq:SPI4", 2336, -5}; static constexpr wq_config_t SPI5{"wq:SPI5", 2336, -6}; static constexpr wq_config_t SPI6{"wq:SPI6", 2336, -7}; static constexpr wq_config_t I2C0{"wq:I2C0", 1472, -8}; static constexpr wq_config_t I2C1{"wq:I2C1", 1472, -9}; static constexpr wq_config_t I2C2{"wq:I2C2", 1472, -10}; static constexpr wq_config_t I2C3{"wq:I2C3", 1472, -11}; static constexpr wq_config_t I2C4{"wq:I2C4", 1472, -12}; // PX4 att/pos controllers, highest priority after sensors. static constexpr wq_config_t attitude_ctrl{"wq:attitude_ctrl", 1640, -13}; static constexpr wq_config_t nav_and_controllers{"wq:nav_and_controllers", 7200, -14}; static constexpr wq_config_t hp_default{"wq:hp_default", 1900, -15}; static constexpr wq_config_t uavcan{"wq:uavcan", 3000, -16}; static constexpr wq_config_t UART0{"wq:UART0", 1400, -17}; static constexpr wq_config_t UART1{"wq:UART1", 1400, -18}; static constexpr wq_config_t UART2{"wq:UART2", 1400, -19}; static constexpr wq_config_t UART3{"wq:UART3", 1400, -20}; static constexpr wq_config_t UART4{"wq:UART4", 1400, -21}; static constexpr wq_config_t UART5{"wq:UART5", 1400, -22}; static constexpr wq_config_t UART6{"wq:UART6", 1400, -23}; static constexpr wq_config_t UART7{"wq:UART7", 1400, -24}; static constexpr wq_config_t UART8{"wq:UART8", 1400, -25}; static constexpr wq_config_t UART_UNKNOWN{"wq:UART_UNKNOWN", 1400, -26}; static constexpr wq_config_t lp_default{"wq:lp_default", 1700, -50}; static constexpr wq_config_t test1{"wq:test1", 2000, 0}; static constexpr wq_config_t test2{"wq:test2", 2000, 0}; } // namespace wq_configurations /** * Start the work queue manager task. */ int WorkQueueManagerStart(); /** * Stop the work queue manager task. */ int WorkQueueManagerStop(); /** * Work queue manager status. */ int WorkQueueManagerStatus(); /** * Create (or find) a work queue with a particular configuration. * * @param new_wq The work queue configuration (see WorkQueueManager.hpp). * @return A pointer to the WorkQueue, or nullptr on failure. */ WorkQueue *WorkQueueFindOrCreate(const wq_config_t &new_wq); /** * Map a PX4 driver device id to a work queue (by sensor bus). * * @param device_id The PX4 driver's device id. * @return A work queue configuration. */ const wq_config_t &device_bus_to_wq(uint32_t device_id); /** * Map a serial device path (eg /dev/ttyS1) to a work queue. * * @param device_id The device path. * @return A work queue configuration. */ const wq_config_t &serial_port_to_wq(const char *serial); } // namespace px4 <commit_msg>wq:attitude_ctrl increase stack<commit_after>/**************************************************************************** * * Copyright (c) 2019-2020 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #pragma once #include <stdint.h> namespace px4 { class WorkQueue; // forward declaration struct wq_config_t { const char *name; uint16_t stacksize; int8_t relative_priority; // relative to max }; namespace wq_configurations { static constexpr wq_config_t rate_ctrl{"wq:rate_ctrl", 1664, 0}; // PX4 inner loop highest priority static constexpr wq_config_t SPI0{"wq:SPI0", 2336, -1}; static constexpr wq_config_t SPI1{"wq:SPI1", 2336, -2}; static constexpr wq_config_t SPI2{"wq:SPI2", 2336, -3}; static constexpr wq_config_t SPI3{"wq:SPI3", 2336, -4}; static constexpr wq_config_t SPI4{"wq:SPI4", 2336, -5}; static constexpr wq_config_t SPI5{"wq:SPI5", 2336, -6}; static constexpr wq_config_t SPI6{"wq:SPI6", 2336, -7}; static constexpr wq_config_t I2C0{"wq:I2C0", 1472, -8}; static constexpr wq_config_t I2C1{"wq:I2C1", 1472, -9}; static constexpr wq_config_t I2C2{"wq:I2C2", 1472, -10}; static constexpr wq_config_t I2C3{"wq:I2C3", 1472, -11}; static constexpr wq_config_t I2C4{"wq:I2C4", 1472, -12}; // PX4 att/pos controllers, highest priority after sensors. static constexpr wq_config_t attitude_ctrl{"wq:attitude_ctrl", 1656, -13}; static constexpr wq_config_t nav_and_controllers{"wq:nav_and_controllers", 7200, -14}; static constexpr wq_config_t hp_default{"wq:hp_default", 1900, -15}; static constexpr wq_config_t uavcan{"wq:uavcan", 3000, -16}; static constexpr wq_config_t UART0{"wq:UART0", 1400, -17}; static constexpr wq_config_t UART1{"wq:UART1", 1400, -18}; static constexpr wq_config_t UART2{"wq:UART2", 1400, -19}; static constexpr wq_config_t UART3{"wq:UART3", 1400, -20}; static constexpr wq_config_t UART4{"wq:UART4", 1400, -21}; static constexpr wq_config_t UART5{"wq:UART5", 1400, -22}; static constexpr wq_config_t UART6{"wq:UART6", 1400, -23}; static constexpr wq_config_t UART7{"wq:UART7", 1400, -24}; static constexpr wq_config_t UART8{"wq:UART8", 1400, -25}; static constexpr wq_config_t UART_UNKNOWN{"wq:UART_UNKNOWN", 1400, -26}; static constexpr wq_config_t lp_default{"wq:lp_default", 1700, -50}; static constexpr wq_config_t test1{"wq:test1", 2000, 0}; static constexpr wq_config_t test2{"wq:test2", 2000, 0}; } // namespace wq_configurations /** * Start the work queue manager task. */ int WorkQueueManagerStart(); /** * Stop the work queue manager task. */ int WorkQueueManagerStop(); /** * Work queue manager status. */ int WorkQueueManagerStatus(); /** * Create (or find) a work queue with a particular configuration. * * @param new_wq The work queue configuration (see WorkQueueManager.hpp). * @return A pointer to the WorkQueue, or nullptr on failure. */ WorkQueue *WorkQueueFindOrCreate(const wq_config_t &new_wq); /** * Map a PX4 driver device id to a work queue (by sensor bus). * * @param device_id The PX4 driver's device id. * @return A work queue configuration. */ const wq_config_t &device_bus_to_wq(uint32_t device_id); /** * Map a serial device path (eg /dev/ttyS1) to a work queue. * * @param device_id The device path. * @return A work queue configuration. */ const wq_config_t &serial_port_to_wq(const char *serial); } // namespace px4 <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/lib/phy/adr32s.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file adr32s.C /// @brief Subroutines for the PHY ADR32S registers /// // *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com> // *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com> // *HWP Team: Memory // *HWP Level: 2 // *HWP Consumed by: FSP:HB #include <fapi2.H> #include <lib/phy/adr32s.H> #include <lib/utils/find.H> using fapi2::TARGET_TYPE_MCA; using fapi2::TARGET_TYPE_SYSTEM; using fapi2::FAPI2_RC_SUCCESS; namespace mss { // Definition of the ADR32S DLL Config registers const std::vector<uint64_t> adr32sTraits<fapi2::TARGET_TYPE_MCA>::DLL_CNFG_REG = { MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0, MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S1 }; // Definition of the ADR32S output driver registers const std::vector<uint64_t> adr32sTraits<fapi2::TARGET_TYPE_MCA>::OUTPUT_DRIVER_REG = { MCA_DDRPHY_ADR_OUTPUT_FORCE_ATEST_CNTL_P0_ADR32S0, MCA_DDRPHY_ADR_OUTPUT_FORCE_ATEST_CNTL_P0_ADR32S1, }; // Definition of the ADR32S duty cycle distortion registers const std::vector<uint64_t> adr32sTraits<fapi2::TARGET_TYPE_MCA>::DUTY_CYCLE_DISTORTION_REG = { MCA_DDRPHY_ADR_DCD_CONTROL_P0_ADR32S0, MCA_DDRPHY_ADR_DCD_CONTROL_P0_ADR32S1, MCA_DDRPHY_DP16_DCD_CONTROL0_P0_0, MCA_DDRPHY_DP16_DCD_CONTROL1_P0_0, MCA_DDRPHY_DP16_DCD_CONTROL0_P0_1, MCA_DDRPHY_DP16_DCD_CONTROL1_P0_1, MCA_DDRPHY_DP16_DCD_CONTROL0_P0_2, MCA_DDRPHY_DP16_DCD_CONTROL1_P0_2, MCA_DDRPHY_DP16_DCD_CONTROL0_P0_3, MCA_DDRPHY_DP16_DCD_CONTROL1_P0_3, MCA_DDRPHY_DP16_DCD_CONTROL0_P0_4, MCA_DDRPHY_DP16_DCD_CONTROL1_P0_4, }; // Definition of the ADR32S write clock static offset registers const std::vector<uint64_t> adr32sTraits<fapi2::TARGET_TYPE_MCA>::PR_STATIC_OFFSET_REG = { MCA_DDRPHY_ADR_MCCLK_WRCLK_PR_STATIC_OFFSET_P0_ADR32S0, MCA_DDRPHY_ADR_MCCLK_WRCLK_PR_STATIC_OFFSET_P0_ADR32S1, }; namespace adr32s { /// /// @brief Helper to iterate over ADR32S 'sides' when performing DCD cal /// @param[in] i_target the MCA to iterate for /// @param[in] i_reg the register (ADR0 or ADR1's register) /// @param[in] i_seed the seed value for the adjuster /// @param[in] i_side bool; true if this is side a, false for side b /// @param[out] o_value the value of the adjuster when the compare bit changes state /// @return FAPI2_RC_SUCCESS iff ok /// fapi2::ReturnCode dcd_cal_helper( const fapi2::Target<TARGET_TYPE_MCA>& i_target, const uint64_t i_reg, const uint64_t i_seed, const bool i_side, uint64_t& o_value ) { typedef adr32sTraits<TARGET_TYPE_MCA> TT; constexpr uint64_t l_dcd_adjust_overflow = 0b1111111; constexpr uint64_t l_dcd_adjust_underflow = 0b0000000; // If compare out is 0, we tick up ... // Signed value which helps us increment or decrement the adjustment int64_t l_tick = 1; // ... and we expect a transition to 1 bool l_expected = 1; // ... and we don't expect to overflow uint64_t l_overrun = l_dcd_adjust_overflow; fapi2::buffer<uint64_t> l_read; uint64_t l_current_adjust = i_seed; size_t l_iter = 0; // More or less mirror's Bialas's logic for DD2 so we can kind of try out the algorithm on DD1. FAPI_INF("enter dcd_cal_helper %s 0x%016lx seed: 0x%016lx side: %d", mss::c_str(i_target), i_reg, i_seed, i_side ); // Prime the system with the starting values. We don't need to read/modify/write here as we're resetting // the world and saving a scom here is likely benificial. Clear the compare out bit as writing it set // will cause the PHY to throw a parity error l_read.insertFromRight<TT::DCD_CONTROL_DLL_ADJUST, TT::DCD_CONTROL_DLL_ADJUST_LEN>(l_current_adjust); l_read.writeBit<TT::DCD_CONTROL_DLL_ITER_A>(i_side); l_read.clearBit<TT::DCD_CONTROL_DLL_COMPARE_OUT>(); FAPI_TRY( mss::putScom(i_target, i_reg, l_read) ); // Algorithm waits 128ck (~100ns) between steps. However, scom takes so long (and rippling up thru // the platforms takes time too) that there's no need to actually delay - plenty of time has elapsed. // Read. Note the register is volatile in that l_read which we just wrote isn't what we'll read // as the distortion logic will take the seeded adjustment value and give us information on the next // read (so don't get cute and remove this getScom.) FAPI_TRY( mss::getScom(i_target, i_reg, l_read) ); // Based on the 'direction' we're going, we have some values to setup. We setup the bit == 0 case // when we initialized these variables above. if (l_read.getBit<TT::DCD_CONTROL_DLL_COMPARE_OUT>() != 0) { // If compare out is 1, we tick down ... l_tick = -1; // ... and we expect a transition to 0 l_expected = 0; // ... and we don't expect to underflow l_overrun = l_dcd_adjust_underflow; } do { l_iter += 1; bool l_current_compare = l_read.getBit<TT::DCD_CONTROL_DLL_COMPARE_OUT>(); FAPI_INF("dcd_cal_helper: iter %d tick: %d expected: %d overrun: 0x%x out: %d adj: 0x%x", l_iter, l_tick, l_expected, l_overrun, l_current_compare, l_current_adjust); if (l_current_compare == l_expected) { break; } // If we're here we're not done, so just adjust and try again. Clear the compare out bit, it must // always be 0 or the PHY will parity error l_read.insertFromRight<TT::DCD_CONTROL_DLL_ADJUST, TT::DCD_CONTROL_DLL_ADJUST_LEN>(l_current_adjust + l_tick); l_read.clearBit<TT::DCD_CONTROL_DLL_COMPARE_OUT>(); FAPI_TRY( mss::putScom(i_target, i_reg, l_read) ); // Wait 128ck (~100ns) ... FAPI_TRY( mss::getScom(i_target, i_reg, l_read) ); l_read.extractToRight<TT::DCD_CONTROL_DLL_ADJUST, TT::DCD_CONTROL_DLL_ADJUST_LEN>(l_current_adjust); } while (l_current_adjust != l_overrun); FAPI_ASSERT( l_current_adjust != l_overrun, fapi2::MSS_DUTY_CLOCK_DISTORTION_CAL_FAILED() .set_TARGET(i_target) .set_CURRENT_ADJUST(l_current_adjust) .set_SIDE(i_side) .set_REGISTER(i_reg) .set_REGISTER_VALUE(l_read), "Failed ADR DCD for %s 0x%016lx", mss::c_str(i_target), i_reg ); // If we're here, we were done and there were no errors. So we can return back the current adjust value // as the output/result of our operation o_value = l_current_adjust; FAPI_INF("side: %d final adjust value: 0x%x (0x%x)", i_side, o_value, l_current_adjust); return FAPI2_RC_SUCCESS; fapi_try_exit: return fapi2::current_err; } /// /// @brief Perform ADR DCD calibration - Nimbus Only /// @param[in] i_target the MCBIST (controler) to perform calibration on /// @return FAPI2_RC_SUCCESS iff ok /// fapi2::ReturnCode duty_cycle_distortion_calibration( const fapi2::Target<fapi2::TARGET_TYPE_MCBIST>& i_target ) { typedef adr32sTraits<TARGET_TYPE_MCA> TT; const auto l_mca = mss::find_targets<TARGET_TYPE_MCA>(i_target); fapi2::buffer<uint64_t> l_read; uint8_t is_sim = 0; FAPI_TRY( FAPI_ATTR_GET(fapi2::ATTR_IS_SIMULATION, fapi2::Target<TARGET_TYPE_SYSTEM>(), is_sim) ); // Nothing works here in cycle sim ... if (is_sim) { return FAPI2_RC_SUCCESS; } if (l_mca.size() == 0) { FAPI_INF("No MCA, skipping duty cycle distortion calibration"); return FAPI2_RC_SUCCESS; } // Do a quick check to make sure this chip doesn't have the DCD logic built in (e.g., DD1 Nimbus) // TODO RTC:159687 For DD2 all we need to do is kick off the h/w cal and wait. We can check any ADR_DCD // register, they all should reflect the inclusion of the DCD logic. FAPI_TRY( mss::getScom(l_mca[0], TT::DUTY_CYCLE_DISTORTION_REG[0], l_read) ); if (l_read.getBit<TT::DCD_CONTROL_DLL_CORRECT_EN>() == 1) { FAPI_ERR("seeing ADR DCD algorithm is in the logic but we didn't code it?"); fapi2::Assert(false); } // We must calibrate each of our ports. Each has 2 ADR units and each unit needs it's A-side and B-side calibrated. for (const auto& p : mss::find_targets<TARGET_TYPE_MCA>(i_target)) { uint64_t l_seed = TT::DCD_ADJUST_DEFAULT; for (const auto& r : TT::DUTY_CYCLE_DISTORTION_REG) { uint64_t l_a_side_value = 0; uint64_t l_b_side_value = 0; FAPI_TRY( dcd_cal_helper(p, r, l_seed, true, l_a_side_value) ); // We want to seed the other side (and each subsequent port) with the // value found in the pervious iteration as that will likely reduce the number // of iterations to find the transition. We back up one so that if we're on // a transition, we don't 'bounce' from a 1 to a 0. This will give us a good // transition if the a-side value is really to be the b-side value too. FAPI_TRY( dcd_cal_helper(p, r, l_a_side_value - 1, false, l_b_side_value) ); // The final value is the average of the a-side and b-side values. l_seed = (l_a_side_value + l_b_side_value) / 2; FAPI_INF("average for both sides 0x%02x", l_seed); // Note this writes all the other values to 0's which is OK for DD1 FAPI_TRY( mss::putScom(p, r, l_seed) ); } } fapi_try_exit: return fapi2::current_err; } } // close namespace adrs32 } // close namespace mss <commit_msg>Change accesses to IS_SIM to use mss accessor<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/lib/phy/adr32s.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file adr32s.C /// @brief Subroutines for the PHY ADR32S registers /// // *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com> // *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com> // *HWP Team: Memory // *HWP Level: 2 // *HWP Consumed by: FSP:HB #include <fapi2.H> #include <lib/phy/adr32s.H> #include <lib/utils/find.H> using fapi2::TARGET_TYPE_MCA; using fapi2::TARGET_TYPE_SYSTEM; using fapi2::FAPI2_RC_SUCCESS; namespace mss { // Definition of the ADR32S DLL Config registers const std::vector<uint64_t> adr32sTraits<fapi2::TARGET_TYPE_MCA>::DLL_CNFG_REG = { MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0, MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S1 }; // Definition of the ADR32S output driver registers const std::vector<uint64_t> adr32sTraits<fapi2::TARGET_TYPE_MCA>::OUTPUT_DRIVER_REG = { MCA_DDRPHY_ADR_OUTPUT_FORCE_ATEST_CNTL_P0_ADR32S0, MCA_DDRPHY_ADR_OUTPUT_FORCE_ATEST_CNTL_P0_ADR32S1, }; // Definition of the ADR32S duty cycle distortion registers const std::vector<uint64_t> adr32sTraits<fapi2::TARGET_TYPE_MCA>::DUTY_CYCLE_DISTORTION_REG = { MCA_DDRPHY_ADR_DCD_CONTROL_P0_ADR32S0, MCA_DDRPHY_ADR_DCD_CONTROL_P0_ADR32S1, MCA_DDRPHY_DP16_DCD_CONTROL0_P0_0, MCA_DDRPHY_DP16_DCD_CONTROL1_P0_0, MCA_DDRPHY_DP16_DCD_CONTROL0_P0_1, MCA_DDRPHY_DP16_DCD_CONTROL1_P0_1, MCA_DDRPHY_DP16_DCD_CONTROL0_P0_2, MCA_DDRPHY_DP16_DCD_CONTROL1_P0_2, MCA_DDRPHY_DP16_DCD_CONTROL0_P0_3, MCA_DDRPHY_DP16_DCD_CONTROL1_P0_3, MCA_DDRPHY_DP16_DCD_CONTROL0_P0_4, MCA_DDRPHY_DP16_DCD_CONTROL1_P0_4, }; // Definition of the ADR32S write clock static offset registers const std::vector<uint64_t> adr32sTraits<fapi2::TARGET_TYPE_MCA>::PR_STATIC_OFFSET_REG = { MCA_DDRPHY_ADR_MCCLK_WRCLK_PR_STATIC_OFFSET_P0_ADR32S0, MCA_DDRPHY_ADR_MCCLK_WRCLK_PR_STATIC_OFFSET_P0_ADR32S1, }; namespace adr32s { /// /// @brief Helper to iterate over ADR32S 'sides' when performing DCD cal /// @param[in] i_target the MCA to iterate for /// @param[in] i_reg the register (ADR0 or ADR1's register) /// @param[in] i_seed the seed value for the adjuster /// @param[in] i_side bool; true if this is side a, false for side b /// @param[out] o_value the value of the adjuster when the compare bit changes state /// @return FAPI2_RC_SUCCESS iff ok /// fapi2::ReturnCode dcd_cal_helper( const fapi2::Target<TARGET_TYPE_MCA>& i_target, const uint64_t i_reg, const uint64_t i_seed, const bool i_side, uint64_t& o_value ) { typedef adr32sTraits<TARGET_TYPE_MCA> TT; constexpr uint64_t l_dcd_adjust_overflow = 0b1111111; constexpr uint64_t l_dcd_adjust_underflow = 0b0000000; // If compare out is 0, we tick up ... // Signed value which helps us increment or decrement the adjustment int64_t l_tick = 1; // ... and we expect a transition to 1 bool l_expected = 1; // ... and we don't expect to overflow uint64_t l_overrun = l_dcd_adjust_overflow; fapi2::buffer<uint64_t> l_read; uint64_t l_current_adjust = i_seed; size_t l_iter = 0; // More or less mirror's Bialas's logic for DD2 so we can kind of try out the algorithm on DD1. FAPI_INF("enter dcd_cal_helper %s 0x%016lx seed: 0x%016lx side: %d", mss::c_str(i_target), i_reg, i_seed, i_side ); // Prime the system with the starting values. We don't need to read/modify/write here as we're resetting // the world and saving a scom here is likely benificial. Clear the compare out bit as writing it set // will cause the PHY to throw a parity error l_read.insertFromRight<TT::DCD_CONTROL_DLL_ADJUST, TT::DCD_CONTROL_DLL_ADJUST_LEN>(l_current_adjust); l_read.writeBit<TT::DCD_CONTROL_DLL_ITER_A>(i_side); l_read.clearBit<TT::DCD_CONTROL_DLL_COMPARE_OUT>(); FAPI_TRY( mss::putScom(i_target, i_reg, l_read) ); // Algorithm waits 128ck (~100ns) between steps. However, scom takes so long (and rippling up thru // the platforms takes time too) that there's no need to actually delay - plenty of time has elapsed. // Read. Note the register is volatile in that l_read which we just wrote isn't what we'll read // as the distortion logic will take the seeded adjustment value and give us information on the next // read (so don't get cute and remove this getScom.) FAPI_TRY( mss::getScom(i_target, i_reg, l_read) ); // Based on the 'direction' we're going, we have some values to setup. We setup the bit == 0 case // when we initialized these variables above. if (l_read.getBit<TT::DCD_CONTROL_DLL_COMPARE_OUT>() != 0) { // If compare out is 1, we tick down ... l_tick = -1; // ... and we expect a transition to 0 l_expected = 0; // ... and we don't expect to underflow l_overrun = l_dcd_adjust_underflow; } do { l_iter += 1; bool l_current_compare = l_read.getBit<TT::DCD_CONTROL_DLL_COMPARE_OUT>(); FAPI_INF("dcd_cal_helper: iter %d tick: %d expected: %d overrun: 0x%x out: %d adj: 0x%x", l_iter, l_tick, l_expected, l_overrun, l_current_compare, l_current_adjust); if (l_current_compare == l_expected) { break; } // If we're here we're not done, so just adjust and try again. Clear the compare out bit, it must // always be 0 or the PHY will parity error l_read.insertFromRight<TT::DCD_CONTROL_DLL_ADJUST, TT::DCD_CONTROL_DLL_ADJUST_LEN>(l_current_adjust + l_tick); l_read.clearBit<TT::DCD_CONTROL_DLL_COMPARE_OUT>(); FAPI_TRY( mss::putScom(i_target, i_reg, l_read) ); // Wait 128ck (~100ns) ... FAPI_TRY( mss::getScom(i_target, i_reg, l_read) ); l_read.extractToRight<TT::DCD_CONTROL_DLL_ADJUST, TT::DCD_CONTROL_DLL_ADJUST_LEN>(l_current_adjust); } while (l_current_adjust != l_overrun); FAPI_ASSERT( l_current_adjust != l_overrun, fapi2::MSS_DUTY_CLOCK_DISTORTION_CAL_FAILED() .set_TARGET(i_target) .set_CURRENT_ADJUST(l_current_adjust) .set_SIDE(i_side) .set_REGISTER(i_reg) .set_REGISTER_VALUE(l_read), "Failed ADR DCD for %s 0x%016lx", mss::c_str(i_target), i_reg ); // If we're here, we were done and there were no errors. So we can return back the current adjust value // as the output/result of our operation o_value = l_current_adjust; FAPI_INF("side: %d final adjust value: 0x%x (0x%x)", i_side, o_value, l_current_adjust); return FAPI2_RC_SUCCESS; fapi_try_exit: return fapi2::current_err; } /// /// @brief Perform ADR DCD calibration - Nimbus Only /// @param[in] i_target the MCBIST (controler) to perform calibration on /// @return FAPI2_RC_SUCCESS iff ok /// fapi2::ReturnCode duty_cycle_distortion_calibration( const fapi2::Target<fapi2::TARGET_TYPE_MCBIST>& i_target ) { typedef adr32sTraits<TARGET_TYPE_MCA> TT; const auto l_mca = mss::find_targets<TARGET_TYPE_MCA>(i_target); fapi2::buffer<uint64_t> l_read; uint8_t l_sim = 0; FAPI_TRY( mss::is_simulation( l_sim) ); // Nothing works here in cycle sim ... if (l_sim) { return FAPI2_RC_SUCCESS; } if (l_mca.size() == 0) { FAPI_INF("No MCA, skipping duty cycle distortion calibration"); return FAPI2_RC_SUCCESS; } // Do a quick check to make sure this chip doesn't have the DCD logic built in (e.g., DD1 Nimbus) // TODO RTC:159687 For DD2 all we need to do is kick off the h/w cal and wait. We can check any ADR_DCD // register, they all should reflect the inclusion of the DCD logic. FAPI_TRY( mss::getScom(l_mca[0], TT::DUTY_CYCLE_DISTORTION_REG[0], l_read) ); if (l_read.getBit<TT::DCD_CONTROL_DLL_CORRECT_EN>() == 1) { FAPI_ERR("seeing ADR DCD algorithm is in the logic but we didn't code it?"); fapi2::Assert(false); } // We must calibrate each of our ports. Each has 2 ADR units and each unit needs it's A-side and B-side calibrated. for (const auto& p : mss::find_targets<TARGET_TYPE_MCA>(i_target)) { uint64_t l_seed = TT::DCD_ADJUST_DEFAULT; for (const auto& r : TT::DUTY_CYCLE_DISTORTION_REG) { uint64_t l_a_side_value = 0; uint64_t l_b_side_value = 0; FAPI_TRY( dcd_cal_helper(p, r, l_seed, true, l_a_side_value) ); // We want to seed the other side (and each subsequent port) with the // value found in the pervious iteration as that will likely reduce the number // of iterations to find the transition. We back up one so that if we're on // a transition, we don't 'bounce' from a 1 to a 0. This will give us a good // transition if the a-side value is really to be the b-side value too. FAPI_TRY( dcd_cal_helper(p, r, l_a_side_value - 1, false, l_b_side_value) ); // The final value is the average of the a-side and b-side values. l_seed = (l_a_side_value + l_b_side_value) / 2; FAPI_INF("average for both sides 0x%02x", l_seed); // Note this writes all the other values to 0's which is OK for DD1 FAPI_TRY( mss::putScom(p, r, l_seed) ); } } fapi_try_exit: return fapi2::current_err; } } // close namespace adrs32 } // close namespace mss <|endoftext|>
<commit_before>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: SlsPageObjectViewObjectContact.hxx,v $ * $Revision: 1.13 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef SD_SLIDESORTER_PAGE_OBJECT_VIEW_OBJECT_CONTACT_HXX #define SD_SLIDESORTER_PAGE_OBJECT_VIEW_OBJECT_CONTACT_HXX #include "model/SlsSharedPageDescriptor.hxx" #include <svx/sdr/contact/viewobjectcontact.hxx> #include <vcl/bitmapex.hxx> #include <vcl/image.hxx> #include <sfx2/viewfrm.hxx> #include <memory> #include <boost/shared_ptr.hpp> class SdrPage; namespace sdr { namespace contact { class DisplayInfo; } } namespace sd { namespace slidesorter { namespace cache { class PageCache; } } } namespace sd { namespace slidesorter { namespace controller { class Properties; } } } namespace sd { namespace slidesorter { namespace view { class PageNotificationObjectContact; class SlideSorterView; /** This object-view-contact of page objects maintains a preview bitmap for the page to speed up redraws of the same. It does so by colaborating with a cache of bitmaps (see ../cache). This class started as a subclass of ::sdr::contact::VOCBitmapBuffer but the class specific code had to be copied and adapted. Therefore, it is now derived directly from ::sdr::contact::ViewObjectContact. */ class PageObjectViewObjectContact : public ::sdr::contact::ViewObjectContact { public: /** Create a new view-object-contact object for the given contact objects of both model and view. @param pCache The caller should provide a pointer to a preview cache, if available. If given then the cache is used to control when to create a preview and to store it. If NULL is given then the preview is created every time when requested. */ PageObjectViewObjectContact ( ::sdr::contact::ObjectContact& rObjectContact, ::sdr::contact::ViewContact& rViewContact, const ::boost::shared_ptr<cache::PageCache>& rpCache, const ::boost::shared_ptr<controller::Properties>& rpProperties); virtual ~PageObjectViewObjectContact (void); /** This method is primarily for releasing the current preview cache (by providing a NULL pointer.) */ void SetCache (const ::boost::shared_ptr<cache::PageCache>& rpCache); virtual void PaintObject (::sdr::contact::DisplayInfo& rDisplayInfo); /** The object is about to be deleted. Tell the cache that it has not to rendere a preview anymore and absolutely must not call back. */ virtual void PrepareDelete (void); /** Return the page that is painted by this object. */ const SdrPage* GetPage (void) const; /** This fallback method is called when no preview cache is available. It creates a preview for the page. */ BitmapEx CreatePreview (OutputDevice& rDevice) const; /** This paint method calls the more specialized paint methods that paint single aspects of the content. */ virtual void PaintContent (OutputDevice& rDevice); /** Return the page descriptor of the slide sorter model that is associated with the same page object as this contact object is. */ model::SharedPageDescriptor GetPageDescriptor (void) const; /** Return the device independent part of the page border. This border is returned in pixel coordinates. Note that the device dependent parts--for the page number and the page title--have to be added. This is done by CalculatePageModelBorder(). */ static SvBorder GetPagePixelBorder (void); /** Return the border widths in the screen coordinate system of the border arround the page object. The border contains frames for selection, focus, the page name and number, and the indicator for the page transition. @param pDevice The output device is used to convert pixel coordinates into model coordinates. When NULL is given then the device dependent part is not re-calculated but taken from an earlier calculation or from the default values. @param nPageCount The total number of pages is used to determine the width of the box that contains the page number. */ static SvBorder CalculatePageModelBorder ( OutputDevice* pDevice, int nPageCount); /** Calculate the size of the page number area so that all page numbers including the given number fit in. Because this is device dependent we need the device as parameter. The result is returned and stored in maPageNumberAreaPixelSize so that it can be used later without access to the device or page count. */ static Size CalculatePageNumberAreaModelSize ( OutputDevice* pDevice, int nPageCount); /** Paint all parts of the frame arround a preview. These are the border, the selection frame, the focus rectangle, and the mouse over effect. @param rDevice The output device to paint on. @param bShowMouseOverEffect This flag specifies whether to paint the mouse over effect or not. */ void PaintFrame ( OutputDevice& rDevice, bool bShowMouseOverEffect = false) const; /** Paint a mouse over effect. @param bVisible When bVisible is <FALSE/> then paint the area of the mouse over effect in the background color, i.e. erase it. */ void PaintMouseOverEffect (OutputDevice& rDevice, bool bVisible) const; enum BoundingBoxType { // This is the outer bounding box that includes the preview, page // number, title. PageObjectBoundingBox, // Bounding box of the actual preview. PreviewBoundingBox, // Bounding box of the mouse indicator indicator frame. MouseOverIndicatorBoundingBox, // Bounding box of the focus indicator frame. FocusIndicatorBoundingBox, // Bounding box of the selection indicator frame. SelectionIndicatorBoundingBox, // Bounding box of the page number. PageNumberBoundingBox, // Bounding box of the pane name. NameBoundingBox, FadeEffectIndicatorBoundingBox }; enum CoordinateSystem { ModelCoordinateSystem, PixelCoordinateSystem }; /** Return the bounding box of the page object or one of its graphical parts. @param rDevice This device is used to translate between model and window coordinates. @param eType The part of the page object for which to return the bounding box. @param eCoodinateSystem The bounding box can be returned in model and in pixel (window) coordinates. */ Rectangle GetBoundingBox ( OutputDevice& rDevice, BoundingBoxType eType, CoordinateSystem eCoordinateSystem) const; /** This convenience method paints a dotted or dashed rectangle. The length of dots or dashes is indepent of zoom factor or map mode. */ enum DashType { Dotted, Dashed }; static void PaintDottedRectangle ( OutputDevice& rDevice, const Rectangle& rRectangle, const DashType eDashType = Dotted); enum ColorSpec { CS_SELECTION, CS_BACKGROUND, CS_WINDOW, CS_TEXT }; /** Return a color for one of the screen elements in ColorSpec. For Background the background color is updated when mbIsBackgroundColorUpdatePending is <TRUE/>. @param rDevice Base colors are taken from the device. @param eSpec The type of color to return. @param nOpacity This parameter controls the blending between the background and the actual color. */ Color GetColor ( const OutputDevice& rDevice, const ColorSpec eSpec, const double nOpacity = 1.0) const; private: /// Gap between border of page object and inside of selection rectangle. static const sal_Int32 mnSelectionIndicatorOffset; /// Thickness of the selection rectangle. static const sal_Int32 mnSelectionIndicatorThickness; /// Gap between border of page object and inside of focus rectangle. static const sal_Int32 mnFocusIndicatorOffset; /// Size of width and height of the fade effect indicator in pixels. static const sal_Int32 mnFadeEffectIndicatorSize; static const sal_Int32 mnFadeEffectIndicatorOffset; /// Gap between border of page object and number rectangle. static const sal_Int32 mnPageNumberOffset; /// Offset and thickness of the mouse over effect rectangle. static const sal_Int32 mnMouseOverEffectOffset; static const sal_Int32 mnMouseOverEffectThickness; model::SharedPageDescriptor mpPageDescriptor; /** This flag is set to <FALSE/> when PrepareDelete() is called to indicate that further calls made to it must not call outside. */ bool mbIsValid; bool mbInPrepareDelete; /** Set this flag to <TRUE/> to update the background color on the next call to GetBackgroundColor(). */ mutable bool mbIsBackgroundColorUpdatePending; ::boost::shared_ptr<cache::PageCache> mpCache; ::std::auto_ptr<PageNotificationObjectContact> mpNotifier; ::boost::shared_ptr<controller::Properties> mpProperties; /** Do not use this member directly. Use GetColor(Background) instead. That method determines the background color when mbIsBackgroundColorUpdatePending is <TRUE/>. */ mutable Color maBackgroundColor; BitmapEx GetPreview ( OutputDevice& rDevice, const Rectangle& rNewSizePixel); virtual void ActionChanged (void); /** Return the bounding box of where the page number is painted (when it is painted). */ Rectangle GetPageNumberArea (OutputDevice& rDevice) const; void PaintBackground (OutputDevice& rDevice) const; /** Paint the preview bitmap. */ void PaintPreview (OutputDevice& rDevice); /** Paint a border arround the page preview. */ void PaintBorder (OutputDevice& rDevice) const; /** Paint the focus indicator for the specified page. */ void PaintFocusIndicator ( OutputDevice& rDevice, bool bEraseBackground) const; /** Paint the selection indicator when the page is currently selected. Otherwise the call is ignored. */ void PaintSelectionIndicator (OutputDevice& rDevice) const; /** Paint the fade effect indicator which indicates whether a fade effect is currently associated with a page. @param rDescriptor The descriptor of the page for which to paint the fade effect indicator. */ void PaintFadeEffectIndicator (OutputDevice& rDevice) const; /** Paint the name of the page to the bottom right of the page object. */ void PaintPageName (OutputDevice& rDevice) const; /** Paint the number of the page to the upper left of the page object. */ void PaintPageNumber (OutputDevice& rDevice) const; Color GetBackgroundColor (const OutputDevice& rDevice) const; }; } } } // end of namespace ::sd::slidesorter::view #endif <commit_msg>INTEGRATION: CWS aw033 (1.10.188); FILE MERGED 2008/07/10 12:56:27 aw 1.10.188.12: #i39532# XOutputDevice removed, PrepareDelete removed 2008/05/27 15:18:02 aw 1.10.188.11: #i39532# changes DEV300 m12 resync corrections 2008/05/16 13:06:04 aw 1.10.188.10: adaptions after resync 2008/05/14 14:51:03 aw 1.10.188.9: RESYNC: (1.11-1.13); FILE MERGED 2008/03/17 14:34:20 cl 1.10.188.8: fixed merge conflict 2008/03/14 14:02:02 cl 1.10.188.7: RESYNC: (1.10-1.11); FILE MERGED 2008/01/29 10:34:21 aw 1.10.188.6: updated refresh for ActionChanged(), diverse removals 2008/01/22 12:16:41 aw 1.10.188.5: adaptions and 1st stripping 2007/10/22 10:26:50 aw 1.10.188.4: #i39523# joined #i82710# and adaptions to primitives 2007/07/06 13:46:12 aw 1.10.188.3: #i39532# moved from Primitive2DReference to Primitive2DSequence where possible to avoid extra-group primitive creations and deeper hierarchies as necessary 2006/11/28 11:13:41 aw 1.10.188.2: #i39532# 2006/11/09 17:04:09 aw 1.10.188.1: #i39532# Prepared PageObjectViewObjectContact for primitive usage, see comments there.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: SlsPageObjectViewObjectContact.hxx,v $ * $Revision: 1.14 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef SD_SLIDESORTER_PAGE_OBJECT_VIEW_OBJECT_CONTACT_HXX #define SD_SLIDESORTER_PAGE_OBJECT_VIEW_OBJECT_CONTACT_HXX #include <svx/sdr/contact/viewobjectcontactofpageobj.hxx> #include "model/SlsSharedPageDescriptor.hxx" #include <svx/sdr/contact/viewobjectcontact.hxx> #include <vcl/bitmapex.hxx> #include <vcl/image.hxx> #include <sfx2/viewfrm.hxx> #include <memory> #include <boost/shared_ptr.hpp> class SdrPage; namespace sdr { namespace contact { class DisplayInfo; } } namespace sd { namespace slidesorter { namespace cache { class PageCache; } } } namespace sd { namespace slidesorter { namespace controller { class Properties; } } } namespace sd { namespace slidesorter { namespace view { class SlideSorterView; /** This object-view-contact of page objects maintains a preview bitmap for the page to speed up redraws of the same. It does so by colaborating with a cache of bitmaps (see ../cache). */ // needs to be derived from ViewObjectContactOfPageObj, else the calls to parent implementations // would use ViewObjectContact and thus not enable e.g. the correct primitive creation // for view-independent printer output // changed: ViewObjectContact -> ViewObjectContactOfPageObj class PageObjectViewObjectContact : public ::sdr::contact::ViewObjectContactOfPageObj { public: /** Create a new view-object-contact object for the given contact objects of both model and view. @param pCache The caller should provide a pointer to a preview cache, if available. If given then the cache is used to control when to create a preview and to store it. If NULL is given then the preview is created every time when requested. */ PageObjectViewObjectContact ( ::sdr::contact::ObjectContact& rObjectContact, ::sdr::contact::ViewContact& rViewContact, const ::boost::shared_ptr<cache::PageCache>& rpCache, const ::boost::shared_ptr<controller::Properties>& rpProperties); virtual ~PageObjectViewObjectContact (void); /** This method is primarily for releasing the current preview cache (by providing a NULL pointer.) */ void SetCache (const ::boost::shared_ptr<cache::PageCache>& rpCache); /** Return the page that is painted by this object. */ const SdrPage* GetPage (void) const; /** This fallback method is called when no preview cache is available. It creates a preview for the page. */ BitmapEx CreatePreview (const sdr::contact::DisplayInfo& rDisplayInfo); /** Return the page descriptor of the slide sorter model that is associated with the same page object as this contact object is. */ model::SharedPageDescriptor GetPageDescriptor (void) const; /** Return the device independent part of the page border. This border is returned in pixel coordinates. Note that the device dependent parts--for the page number and the page title--have to be added. This is done by CalculatePageModelBorder(). */ static SvBorder GetPagePixelBorder (void); /** Return the border widths in the screen coordinate system of the border arround the page object. The border contains frames for selection, focus, the page name and number, and the indicator for the page transition. @param pDevice The output device is used to convert pixel coordinates into model coordinates. When NULL is given then the device dependent part is not re-calculated but taken from an earlier calculation or from the default values. @param nPageCount The total number of pages is used to determine the width of the box that contains the page number. */ static SvBorder CalculatePageModelBorder ( OutputDevice* pDevice, int nPageCount); /** Calculate the size of the page number area so that all page numbers including the given number fit in. Because this is device dependent we need the device as parameter. The result is returned and stored in maPageNumberAreaPixelSize so that it can be used later without access to the device or page count. */ static Size CalculatePageNumberAreaModelSize ( OutputDevice* pDevice, int nPageCount); /** Paint a mouse over effect. @param bVisible When bVisible is <FALSE/> then paint the area of the mouse over effect in the background color, i.e. erase it. */ void PaintMouseOverEffect (OutputDevice& rDevice, bool bVisible) const; enum BoundingBoxType { // This is the outer bounding box that includes the preview, page // number, title. PageObjectBoundingBox, // Bounding box of the actual preview. PreviewBoundingBox, // Bounding box of the mouse indicator indicator frame. MouseOverIndicatorBoundingBox, // Bounding box of the focus indicator frame. FocusIndicatorBoundingBox, // Bounding box of the selection indicator frame. SelectionIndicatorBoundingBox, // Bounding box of the page number. PageNumberBoundingBox, // Bounding box of the pane name. NameBoundingBox, FadeEffectIndicatorBoundingBox }; enum CoordinateSystem { ModelCoordinateSystem, PixelCoordinateSystem }; /** Return the bounding box of the page object or one of its graphical parts. @param rDevice This device is used to translate between model and window coordinates. @param eType The part of the page object for which to return the bounding box. @param eCoodinateSystem The bounding box can be returned in model and in pixel (window) coordinates. */ Rectangle GetBoundingBox ( OutputDevice& rDevice, BoundingBoxType eType, CoordinateSystem eCoordinateSystem) const; // create the graphical visualisation data virtual drawinglayer::primitive2d::Primitive2DSequence createPrimitive2DSequence(const sdr::contact::DisplayInfo& rDisplayInfo) const; // access to the current page content primitive vector which may be used for visualisation const drawinglayer::primitive2d::Primitive2DSequence& getCurrentPageContents() const { return mxCurrentPageContents; } /** This convenience method paints a dotted or dashed rectangle. The length of dots or dashes is indepent of zoom factor or map mode. */ enum DashType { Dotted, Dashed }; static void PaintDottedRectangle ( OutputDevice& rDevice, const Rectangle& rRectangle, const DashType eDashType = Dotted); enum ColorSpec { CS_SELECTION, CS_BACKGROUND, CS_WINDOW, CS_TEXT }; /** Return a color for one of the screen elements in ColorSpec. For Background the background color is updated when mbIsBackgroundColorUpdatePending is <TRUE/>. @param rDevice Base colors are taken from the device. @param eSpec The type of color to return. @param nOpacity This parameter controls the blending between the background and the actual color. */ Color GetColor ( const OutputDevice& rDevice, const ColorSpec eSpec, const double nOpacity = 1.0) const; virtual void ActionChanged (void); private: /// Gap between border of page object and inside of selection rectangle. static const sal_Int32 mnSelectionIndicatorOffset; /// Thickness of the selection rectangle. static const sal_Int32 mnSelectionIndicatorThickness; /// Gap between border of page object and inside of focus rectangle. static const sal_Int32 mnFocusIndicatorOffset; /// Size of width and height of the fade effect indicator in pixels. static const sal_Int32 mnFadeEffectIndicatorSize; static const sal_Int32 mnFadeEffectIndicatorOffset; /// Gap between border of page object and number rectangle. static const sal_Int32 mnPageNumberOffset; /// Offset and thickness of the mouse over effect rectangle. static const sal_Int32 mnMouseOverEffectOffset; static const sal_Int32 mnMouseOverEffectThickness; /** This flag is set to <TRUE/> when the destructor is called to indicate that further calls made to it must not call outside. */ bool mbInDestructor; /** Set this flag to <TRUE/> to update the background color on the next call to GetBackgroundColor(). */ mutable bool mbIsBackgroundColorUpdatePending; /// The primitive sequence of the page contents, completely scaled /// and prepared for painiting drawinglayer::primitive2d::Primitive2DSequence mxCurrentPageContents; ::boost::shared_ptr<cache::PageCache> mpCache; ::boost::shared_ptr<controller::Properties> mpProperties; /** Do not use this member directly. Use GetColor(Background) instead. That method determines the background color when mbIsBackgroundColorUpdatePending is <TRUE/>. */ mutable Color maBackgroundColor; BitmapEx GetPreview ( const sdr::contact::DisplayInfo& rDisplayInfo, const Rectangle& rNewSizePixel); /** Return the bounding box of where the page number is painted (when it is painted). */ Rectangle GetPageNumberArea (OutputDevice& rDevice) const; void PaintBackground (OutputDevice& rDevice) const; /** Paint the preview bitmap. */ void PaintPreview (OutputDevice& rDevice); /** Paint a border arround the page preview. */ void PaintBorder (OutputDevice& rDevice) const; /** Paint the focus indicator for the specified page. */ void PaintFocusIndicator ( OutputDevice& rDevice, bool bEraseBackground) const; /** Paint the selection indicator when the page is currently selected. Otherwise the call is ignored. */ void PaintSelectionIndicator (OutputDevice& rDevice) const; /** Paint the fade effect indicator which indicates whether a fade effect is currently associated with a page. @param rDescriptor The descriptor of the page for which to paint the fade effect indicator. */ void PaintFadeEffectIndicator (OutputDevice& rDevice) const; /** Paint the name of the page to the bottom right of the page object. */ void PaintPageName (OutputDevice& rDevice) const; /** Paint the number of the page to the upper left of the page object. */ void PaintPageNumber ( ::sdr::contact::DisplayInfo& rDisplayInfo); Color GetBackgroundColor (const OutputDevice& rDevice) const; }; } } } // end of namespace ::sd::slidesorter::view #endif <|endoftext|>
<commit_before>/** * OpenCV (OCV) - Video capture on BBB * * GOAL: * This program takes continuous images from the host camera and detect a circular * object of specific color. The color and other configuration are provided as * input argument to the program. * * INPUT: * The program takes two arguments: * - The video device node (0/1) * - The object color (blue/red) * * OUTPUT: * On each frame captured by the program, three files are exported into the * host filesystem (apache directory specifically): * - A colored image with a green circular around the circular object * - A binarized image of the colored image (previous bullet) * - A text file containing information about the object captured * In addition to storing images, at each frame iteration, the program executes a shell script * to communicate information about the frame with the ATMEGA328. * * HOST REQUIREMENTS: * The following packages are required to be installed on the host: * - Apache2 server * - OpenSSH server **/ #include <fstream> #include <iostream> #include <cstring> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <string> #include <vector> #include <math.h> #include <stdlib.h> #include <cstdlib> #include <sstream> #include <stdio.h> #include <ctime> #include <unistd.h> #define PI 3.14159265 using namespace cv; using namespace std; // Keep track of video camera frame number long frameNumber = 0; // Write to files every time the counter reaches zero const int FRAME_EVERY = 3; int currentFrame = FRAME_EVERY; // Assign unique ID for each direction. // The ID must be in sync with the GUI direction values // (Please refer to the documentation for more information about the GUI code) int direction = 0; clock_t start_time; const int FORWARD = 1; const int REVERSE = 2; const int RIGHT = 3; const int LEFT = 4; const int ROTATE = 5; const int PAUSE = 6; const int STOP = 7; /** * Get the distance between the object and the camera * Please refer to the documentation report for more information * about the calculations * @return Distance in cm **/ double getDistance(double realDimention, double digitalDimention) { double FOCAL_LENGTH = 339.079; // in pixels int ERROR_MARGIN = 0; //pixels lost due to selection of circular shape return realDimention * FOCAL_LENGTH / (digitalDimention + ERROR_MARGIN); } /** * Detect the edge point of the object. This information allows the * conclusion of the object digial radius * @param imageDest Current video frame * @param def Default point value in case no object was found * @return arbitrary point on the object edge **/ Point edgePoint(Mat imageDest, Point def) { int thresh = 100; // Canny Algorithm for object edge detection Canny(imageDest, imageDest, thresh /*threshold1*/, thresh*2 /*threshold2*/, 3/*apertureSize*/); // Prepare data structure to store the edge points vector<vector<Point> > contours; vector<Vec4i> hierarchy; // Perform the countour finder findContours(imageDest, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE, Point(0, 0)); // If no object foud, return the provided default value if(contours.size() == 0) { return def; } // Return a point from the countour return contours[0][0]; } /** * Predefined set of colors that can be detected by the program * The colors supported by the current program are blue and red * @param specs Data strucutre to hold the HSV channel color information * based on the color specified * @param color Color of the object (blue/red) **/ void get_color_specs(vector<vector<int> > &specs, string color){ if (!color.compare("blue")) { specs[0][0] = 100; specs[0][1] = 115; specs[0][2] = 50; specs[1][0] = 130; specs[1][1] = 255; specs[1][2] = 255; } else if (!color.compare("red")) { specs[0][0] = 0; specs[0][1] = 197; specs[0][2] = 109; specs[1][0] = 182; specs[1][1] = 255; specs[1][2] = 255; } else { specs[0][0] = 255; specs[0][1] = 255; specs[0][2] = 255; specs[1][0] = 255; specs[1][1] = 255; specs[1][2] = 255; } } void drive(int left, int right) { stringstream ss; ss << "/home/debian/mr_robot/tools/control/write " << left << "," << right << "#" << endl; cout << left << "," << right << "#" << endl; system(ss.str().c_str()); } /** * Drive the car based on the angle and distance * Decisions are mainly taken based on experiments * @param angle Car angel * @param distance Distance of the car from the camera * @param diameter Digital diameter of the circular object * @param loop_count Necessary to keep from writing to Atmega328p faster than it can read messages * @return Direction code **/ void find_ball(double angle, double distance, double diameter, int &loop_count) { int full_speed = 255; int rotation_speed = 140; int turn_speed = 40; int pausing_distance = 45; int target_angle = 4; if (loop_count > 1) { // If no object found: rotate if(diameter == 0 && direction != ROTATE) { cout << endl << "rotating "; drive(rotation_speed, -rotation_speed); direction = ROTATE; loop_count = 0; start_time = clock(); // If object is within pausing_distance and visible: pause } else if(distance <= pausing_distance && diameter > 0 && direction != PAUSE) { cout << endl << "pausing "; drive(0, 0); direction = PAUSE; loop_count = 0; cout << "\n**** BALL FOUND ****\n" << endl; // If object more than target_angle degrees to right and farther than pausing distance: turn right } else if (angle > target_angle && distance >= pausing_distance && direction != RIGHT){ cout << endl << "turning right "; drive(turn_speed, -turn_speed); direction = RIGHT; loop_count = 0; // If object more than target_angle degrees to left and farther than pausing distance: turn left } else if (angle < -target_angle && distance >= pausing_distance && direction != LEFT) { cout << endl << "turning left "; drive(-turn_speed, turn_speed); direction = LEFT; loop_count = 0; // If ball is past pausing distance and within target_angle: forward } else if (distance > pausing_distance && angle < target_angle && angle > -target_angle && direction != FORWARD) { cout << endl << "going forward "; drive(full_speed, full_speed); direction = FORWARD; loop_count = 0; // If ball rotates ~360 degrees and doesn't see ball: stop } else if (direction == ROTATE) { clock_t rotation_duration = (clock() - start_time) / (double)(CLOCKS_PER_SEC); cout << "\trot time: " << rotation_duration << " s" << endl; if (rotation_duration > 12) { drive(0, 0); cout << "\n**** BALL NOT FOUND ****\n" << endl; direction = STOP; } } } loop_count++; } /** * Start the OpenCV program **/ int main( int argc, char** argv ) { // Capture video number is: /dev/video(0/1) int cap_num = atoi(argv[1]); // Color blue/red string color = argv[2]; // Start camera VideoCapture cap; if(!cap.open(cap_num)) return 1; // Configure the camera for fast capture and good resolution cap.set(CV_CAP_PROP_FRAME_WIDTH, 432); cap.set(CV_CAP_PROP_FRAME_HEIGHT,240); cap.set(CV_CAP_PROP_FPS , 30); // loop_count is used to make sure that the find_ball function has looped at least twice // before sending a message to the Atmega328p. This was created in response to a bug found // when writing too fast to the Atmega328p. The direction variable would be modified however // the write message wouldn't be interpreted. This causes the car to get stuck in a // certain direction. Initialized to 2 so that the car begins moving immediately int loop_count = 2; // Keep taking pictures while(1) { // Store the frame in a matrix Mat imageSrc; cap >> imageSrc; // Fetch the color information vector<vector<int> > color_specs(2, vector<int>(3)); get_color_specs(color_specs, color); // HSV low-high values int lowH = color_specs[0][0]; int highH = color_specs[1][0]; int lowS = color_specs[0][1]; int highS = color_specs[1][1]; int lowV = color_specs[0][2]; int highV = color_specs[1][2]; // Destination image Mat imageDest; // Convert BGR to HSV cvtColor(imageSrc, imageDest, COLOR_BGR2HSV); // Get colors in specified range inRange(imageDest, Scalar(lowH, lowS, lowV), Scalar(highH, highS, highV), imageDest); // Morphological opening erode(imageDest, imageDest, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)) ); dilate(imageDest, imageDest, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)) ); // Morphological closing dilate(imageDest, imageDest, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)) ); erode(imageDest, imageDest, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)) ); // Create moment Moments mmts = moments(imageDest); // Calculate center x and y (Centroids) double x_object = mmts.m10 / mmts.m00; double y_object = mmts.m01 / mmts.m00; // Center of image cv::Size size = imageSrc.size(); double x_center = size.width/2.0f; double y_center = size.height/2.0f; // Contour Mat tmpDest = imageDest.clone(); Point point = edgePoint(tmpDest, Point(x_center, y_center)); // Calculate digital diameter in cm double diameter = norm(Point(x_object, y_object)- point)*2; double realDiameter = 6.5; // Calculate the real distance double distance = getDistance(realDiameter, diameter); // Get rotation angle int digitalDiff = x_object - x_center; double realDiff = digitalDiff * (realDiameter / diameter); double rotation_angle = atan(realDiff / distance) * 180 / PI; // If no object found, then diameter is set to zero if(isnan((double)x_object) && isnan((double)y_object)) { diameter = 0.0;; } // Log the calculated information cout << endl; printf("\t%-10s%4.2f\n", "angle:", rotation_angle); printf("\t%-10s%4.2f\n", "distance:", distance); printf("\t%-10s%4.2f\n", "diameter:", diameter); // Draw circle at x and y Mat tmpSource = imageSrc.clone(); circle(tmpSource, Point(x_object,y_object), 3, Scalar(229, 240, 76), 2); circle(tmpSource, Point(x_object,y_object), diameter/2, Scalar(44, 252, 14), 3); // Center circle(tmpSource, Point(x_center,y_center), 2, Scalar(255, 255, 255), 2); // Logic to navigate to ball find_ball(rotation_angle, distance, diameter, loop_count); // Write images and text into the file system/ // Director /var/www/html correspond to the path for // Apache2 server. All files placed in this directory will be // accessible on all users in the network over host IP and port 80 string path = "/home/debian/mr_robot/dashboard/mr-robot-node/public/debug/"; string outPath = path + "out.jpg"; string bwPath = path + "bw.jpg"; string infoPath = path + "info.txt"; if(--currentFrame == 0) { imwrite(outPath, tmpSource); imwrite(bwPath, imageDest); currentFrame = FRAME_EVERY; } ofstream myfile; myfile.open (infoPath.c_str()); myfile << "Distance from camera: " << distance << " cm\n"; myfile << "Rotation angle: " << rotation_angle << "\n"; myfile << "Digital diameter: " << diameter << " px\n"; myfile << "Frame number: " << ++frameNumber << "\n"; string dir_message = "Direction: "; switch (direction) { case FORWARD: myfile << dir_message << "Forward" << endl; break; case REVERSE: myfile << dir_message << "Reversing" << endl; break; case RIGHT: myfile << dir_message << "Right" << endl; break; case LEFT: myfile << dir_message << "Left" << endl; break; case ROTATE: myfile << dir_message << "Rotating" << endl; break; case PAUSE: myfile << dir_message << "Pause" << endl; break; case STOP: myfile << dir_message << "Stop" << endl; break; } myfile << "DIR_CODE: " << direction << "\n"; myfile.close(); if (direction == STOP) { return 0; } } return 0; } <commit_msg>Changed resolution of OCV<commit_after>/** * OpenCV (OCV) - Video capture on BBB * * GOAL: * This program takes continuous images from the host camera and detect a circular * object of specific color. The color and other configuration are provided as * input argument to the program. * * INPUT: * The program takes two arguments: * - The video device node (0/1) * - The object color (blue/red) * * OUTPUT: * On each frame captured by the program, three files are exported into the * host filesystem (apache directory specifically): * - A colored image with a green circular around the circular object * - A binarized image of the colored image (previous bullet) * - A text file containing information about the object captured * In addition to storing images, at each frame iteration, the program executes a shell script * to communicate information about the frame with the ATMEGA328. * * HOST REQUIREMENTS: * The following packages are required to be installed on the host: * - Apache2 server * - OpenSSH server **/ #include <fstream> #include <iostream> #include <cstring> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <string> #include <vector> #include <math.h> #include <stdlib.h> #include <cstdlib> #include <sstream> #include <stdio.h> #include <ctime> #include <unistd.h> #define PI 3.14159265 using namespace cv; using namespace std; // Keep track of video camera frame number long frameNumber = 0; // Write to files every time the counter reaches zero const int FRAME_EVERY = 3; int currentFrame = FRAME_EVERY; // Assign unique ID for each direction. // The ID must be in sync with the GUI direction values // (Please refer to the documentation for more information about the GUI code) int direction = 0; clock_t start_time; const int FORWARD = 1; const int REVERSE = 2; const int RIGHT = 3; const int LEFT = 4; const int ROTATE = 5; const int PAUSE = 6; const int STOP = 7; /** * Get the distance between the object and the camera * Please refer to the documentation report for more information * about the calculations * @return Distance in cm **/ double getDistance(double realDimention, double digitalDimention) { double FOCAL_LENGTH = 339.079; // in pixels int ERROR_MARGIN = 0; //pixels lost due to selection of circular shape return realDimention * FOCAL_LENGTH / (digitalDimention + ERROR_MARGIN); } /** * Detect the edge point of the object. This information allows the * conclusion of the object digial radius * @param imageDest Current video frame * @param def Default point value in case no object was found * @return arbitrary point on the object edge **/ Point edgePoint(Mat imageDest, Point def) { int thresh = 100; // Canny Algorithm for object edge detection Canny(imageDest, imageDest, thresh /*threshold1*/, thresh*2 /*threshold2*/, 3/*apertureSize*/); // Prepare data structure to store the edge points vector<vector<Point> > contours; vector<Vec4i> hierarchy; // Perform the countour finder findContours(imageDest, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE, Point(0, 0)); // If no object foud, return the provided default value if(contours.size() == 0) { return def; } // Return a point from the countour return contours[0][0]; } /** * Predefined set of colors that can be detected by the program * The colors supported by the current program are blue and red * @param specs Data strucutre to hold the HSV channel color information * based on the color specified * @param color Color of the object (blue/red) **/ void get_color_specs(vector<vector<int> > &specs, string color){ if (!color.compare("blue")) { specs[0][0] = 100; specs[0][1] = 115; specs[0][2] = 50; specs[1][0] = 130; specs[1][1] = 255; specs[1][2] = 255; } else if (!color.compare("red")) { specs[0][0] = 0; specs[0][1] = 197; specs[0][2] = 109; specs[1][0] = 182; specs[1][1] = 255; specs[1][2] = 255; } else { specs[0][0] = 255; specs[0][1] = 255; specs[0][2] = 255; specs[1][0] = 255; specs[1][1] = 255; specs[1][2] = 255; } } void drive(int left, int right) { stringstream ss; ss << "/home/debian/mr_robot/tools/control/write " << left << "," << right << "#" << endl; cout << left << "," << right << "#" << endl; system(ss.str().c_str()); } /** * Drive the car based on the angle and distance * Decisions are mainly taken based on experiments * @param angle Car angel * @param distance Distance of the car from the camera * @param diameter Digital diameter of the circular object * @param loop_count Necessary to keep from writing to Atmega328p faster than it can read messages * @return Direction code **/ void find_ball(double angle, double distance, double diameter, int &loop_count) { int full_speed = 255; int rotation_speed = 140; int turn_speed = 40; int pausing_distance = 45; int target_angle = 4; if (loop_count > 1) { // If no object found: rotate if(diameter == 0 && direction != ROTATE) { cout << endl << "rotating "; drive(rotation_speed, -rotation_speed); direction = ROTATE; loop_count = 0; start_time = clock(); // If object is within pausing_distance and visible: pause } else if(distance <= pausing_distance && diameter > 0 && direction != PAUSE) { cout << endl << "pausing "; drive(0, 0); direction = PAUSE; loop_count = 0; cout << "\n**** BALL FOUND ****\n" << endl; // If object more than target_angle degrees to right and farther than pausing distance: turn right } else if (angle > target_angle && distance >= pausing_distance && direction != RIGHT){ cout << endl << "turning right "; drive(turn_speed, -turn_speed); direction = RIGHT; loop_count = 0; // If object more than target_angle degrees to left and farther than pausing distance: turn left } else if (angle < -target_angle && distance >= pausing_distance && direction != LEFT) { cout << endl << "turning left "; drive(-turn_speed, turn_speed); direction = LEFT; loop_count = 0; // If ball is past pausing distance and within target_angle: forward } else if (distance > pausing_distance && angle < target_angle && angle > -target_angle && direction != FORWARD) { cout << endl << "going forward "; drive(full_speed, full_speed); direction = FORWARD; loop_count = 0; // If ball rotates ~360 degrees and doesn't see ball: stop } else if (direction == ROTATE) { clock_t rotation_duration = (clock() - start_time) / (double)(CLOCKS_PER_SEC); cout << "\trot time: " << rotation_duration << " s" << endl; if (rotation_duration > 12) { drive(0, 0); cout << "\n**** BALL NOT FOUND ****\n" << endl; direction = STOP; } } } loop_count++; } /** * Start the OpenCV program **/ int main( int argc, char** argv ) { // Capture video number is: /dev/video(0/1) int cap_num = atoi(argv[1]); // Color blue/red string color = argv[2]; // Start camera VideoCapture cap; if(!cap.open(cap_num)) return 1; // Configure the camera for fast capture and good resolution cap.set(CV_CAP_PROP_FRAME_WIDTH, 320); cap.set(CV_CAP_PROP_FRAME_HEIGHT,180); cap.set(CV_CAP_PROP_FPS , 30); // loop_count is used to make sure that the find_ball function has looped at least twice // before sending a message to the Atmega328p. This was created in response to a bug found // when writing too fast to the Atmega328p. The direction variable would be modified however // the write message wouldn't be interpreted. This causes the car to get stuck in a // certain direction. Initialized to 2 so that the car begins moving immediately int loop_count = 2; // Keep taking pictures while(1) { // Store the frame in a matrix Mat imageSrc; cap >> imageSrc; // Fetch the color information vector<vector<int> > color_specs(2, vector<int>(3)); get_color_specs(color_specs, color); // HSV low-high values int lowH = color_specs[0][0]; int highH = color_specs[1][0]; int lowS = color_specs[0][1]; int highS = color_specs[1][1]; int lowV = color_specs[0][2]; int highV = color_specs[1][2]; // Destination image Mat imageDest; // Convert BGR to HSV cvtColor(imageSrc, imageDest, COLOR_BGR2HSV); // Get colors in specified range inRange(imageDest, Scalar(lowH, lowS, lowV), Scalar(highH, highS, highV), imageDest); // Morphological opening erode(imageDest, imageDest, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)) ); dilate(imageDest, imageDest, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)) ); // Morphological closing dilate(imageDest, imageDest, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)) ); erode(imageDest, imageDest, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)) ); // Create moment Moments mmts = moments(imageDest); // Calculate center x and y (Centroids) double x_object = mmts.m10 / mmts.m00; double y_object = mmts.m01 / mmts.m00; // Center of image cv::Size size = imageSrc.size(); double x_center = size.width/2.0f; double y_center = size.height/2.0f; // Contour Mat tmpDest = imageDest.clone(); Point point = edgePoint(tmpDest, Point(x_center, y_center)); // Calculate digital diameter in cm double diameter = norm(Point(x_object, y_object)- point)*2; double realDiameter = 6.5; // Calculate the real distance double distance = getDistance(realDiameter, diameter); // Get rotation angle int digitalDiff = x_object - x_center; double realDiff = digitalDiff * (realDiameter / diameter); double rotation_angle = atan(realDiff / distance) * 180 / PI; // If no object found, then diameter is set to zero if(isnan((double)x_object) && isnan((double)y_object)) { diameter = 0.0;; } // Log the calculated information cout << endl; printf("\t%-10s%4.2f\n", "angle:", rotation_angle); printf("\t%-10s%4.2f\n", "distance:", distance); printf("\t%-10s%4.2f\n", "diameter:", diameter); // Draw circle at x and y Mat tmpSource = imageSrc.clone(); circle(tmpSource, Point(x_object,y_object), 3, Scalar(229, 240, 76), 2); circle(tmpSource, Point(x_object,y_object), diameter/2, Scalar(44, 252, 14), 3); // Center circle(tmpSource, Point(x_center,y_center), 2, Scalar(255, 255, 255), 2); // Logic to navigate to ball find_ball(rotation_angle, distance, diameter, loop_count); // Write images and text into the file system/ // Director /var/www/html correspond to the path for // Apache2 server. All files placed in this directory will be // accessible on all users in the network over host IP and port 80 string path = "/home/debian/mr_robot/dashboard/mr-robot-node/public/debug/"; string outPath = path + "out.jpg"; string bwPath = path + "bw.jpg"; string infoPath = path + "info.txt"; if(--currentFrame == 0) { imwrite(outPath, tmpSource); imwrite(bwPath, imageDest); currentFrame = FRAME_EVERY; } ofstream myfile; myfile.open (infoPath.c_str()); myfile << "Distance from camera: " << distance << " cm\n"; myfile << "Rotation angle: " << rotation_angle << "\n"; myfile << "Digital diameter: " << diameter << " px\n"; myfile << "Frame number: " << ++frameNumber << "\n"; string dir_message = "Direction: "; switch (direction) { case FORWARD: myfile << dir_message << "Forward" << endl; break; case REVERSE: myfile << dir_message << "Reversing" << endl; break; case RIGHT: myfile << dir_message << "Right" << endl; break; case LEFT: myfile << dir_message << "Left" << endl; break; case ROTATE: myfile << dir_message << "Rotating" << endl; break; case PAUSE: myfile << dir_message << "Pause" << endl; break; case STOP: myfile << dir_message << "Stop" << endl; break; } myfile << "DIR_CODE: " << direction << "\n"; myfile.close(); if (direction == STOP) { return 0; } } return 0; } <|endoftext|>
<commit_before>#include "cache.h" #include <stdlib.h> BlockCache::BlockCache(void) { firstItem = NULL; lastItem = NULL; } BlockCache::~BlockCache(void) { // TODO: Free all items } void BlockCache::Set(void *key, void *val) { BlockCacheItem *item; item = (BlockCacheItem *)malloc(sizeof(BlockCacheItem)); item->key = key; item->val = val; item->next = NULL; if (!firstItem) { firstItem = item; } else { lastItem->next = item; } lastItem = item; } void *BlockCache::Get(void *key) { BlockCacheItem *cur; cur = firstItem; while (cur) { if (cur->key == key) return cur->val; cur = cur->next; } return NULL; } ColorMaterialCache::ColorMaterialCache(void) { firstItem = NULL; lastItem = NULL; } ColorMaterialCache::~ColorMaterialCache(void) { // TODO: Free all items } void ColorMaterialCache::Set(awd_color color, AWDMaterial *mtl) { ColorMaterialCacheItem *item; item = (ColorMaterialCacheItem *)malloc(sizeof(ColorMaterialCacheItem)); item->color = color; item->mtl = mtl; item->next = NULL; if (!firstItem) { firstItem = item; } else { lastItem->next = item; } lastItem = item; } AWDMaterial *ColorMaterialCache::Get(awd_color color) { ColorMaterialCacheItem *cur; cur = firstItem; while (cur) { if (cur->color == color) return cur->mtl; cur = cur->next; } return NULL; } SkeletonCacheItem::SkeletonCacheItem(INode *maxRootBone) { next = NULL; rootBone = maxRootBone; firstJoint = NULL; lastJoint = NULL; numJoints = 0; // Create AWD skeleton structure and begin // gathering joints recursively char *name = rootBone->GetName(); awdSkel = new AWDSkeleton(name, strlen(name)); GatherJoint(rootBone, NULL); } SkeletonCacheItem::~SkeletonCacheItem(void) { // TODO: Delete all joints } void SkeletonCacheItem::AppendCacheJoint(SkeletonCacheJoint *cacheJoint) { if (!firstJoint) { firstJoint = cacheJoint; } else { lastJoint->next = cacheJoint; } lastJoint = cacheJoint; lastJoint->index = numJoints++; lastJoint->next = NULL; } /** * Gather joints using the same order that the AWD SDK uses, so that the * binding code can then look-up indices using this structure. */ void SkeletonCacheItem::GatherJoint(INode *bone, AWDSkeletonJoint *awdParent) { int i; char *name; SkeletonCacheJoint *cacheJoint; AWDSkeletonJoint *awdJoint; name = bone->GetName(); awdJoint = new AWDSkeletonJoint(name, strlen(name), NULL); if (awdParent != NULL) { awdParent->add_child_joint(awdJoint); } else { awdSkel->set_root_joint(awdJoint); } // Add to cache cacheJoint = (SkeletonCacheJoint*)malloc(sizeof(SkeletonCacheJoint)); cacheJoint->awdJoint = awdJoint; cacheJoint->maxBone = bone; AppendCacheJoint(cacheJoint); for (i=0; i<bone->NumberOfChildren(); i++) { INode *child = bone->GetChildNode(i); Object *obj = bone->GetObjectRef(); if (obj && obj->ClassID()==BONE_OBJ_CLASSID) { GatherJoint(child, awdJoint); } } } int SkeletonCacheItem::IndexOfBone(INode *bone) { SkeletonCacheJoint *cur; cur = firstJoint; while (cur) { if (cur->maxBone == bone) return cur->index; cur = cur->next; } return -1; } SkeletonCache::SkeletonCache(void) { firstItem = NULL; lastItem = NULL; cur = NULL; } SkeletonCache::~SkeletonCache(void) { // TODO: Free all items } AWDSkeleton *SkeletonCache::Add(INode *rootBone) { SkeletonCacheItem *item; item = new SkeletonCacheItem(rootBone); if (!firstItem) { firstItem = item; } else { lastItem->next = item; } lastItem = item; // Return skeleton return item->awdSkel; } SkeletonCacheItem *SkeletonCache::GetFromBone(INode *bone) { SkeletonCacheItem *cur; cur = firstItem; while (cur) { // Check if this cache item is a skeleton // containing the supplied bone. if (cur->IndexOfBone(bone) >= 0) return cur; cur = cur->next; } return NULL; } bool SkeletonCache::HasItems() { return (firstItem != NULL); } void SkeletonCache::IterReset() { cur = firstItem; } SkeletonCacheItem *SkeletonCache::IterNext() { // Stop if end was reached if (!cur) return NULL; SkeletonCacheItem *ret = cur; cur = cur->next; return ret; }<commit_msg>Using bone node TM as default bind matrix. Will be overwritten by skin export.<commit_after>#include "cache.h" #include "utils.h" #include <stdlib.h> BlockCache::BlockCache(void) { firstItem = NULL; lastItem = NULL; } BlockCache::~BlockCache(void) { // TODO: Free all items } void BlockCache::Set(void *key, void *val) { BlockCacheItem *item; item = (BlockCacheItem *)malloc(sizeof(BlockCacheItem)); item->key = key; item->val = val; item->next = NULL; if (!firstItem) { firstItem = item; } else { lastItem->next = item; } lastItem = item; } void *BlockCache::Get(void *key) { BlockCacheItem *cur; cur = firstItem; while (cur) { if (cur->key == key) return cur->val; cur = cur->next; } return NULL; } ColorMaterialCache::ColorMaterialCache(void) { firstItem = NULL; lastItem = NULL; } ColorMaterialCache::~ColorMaterialCache(void) { // TODO: Free all items } void ColorMaterialCache::Set(awd_color color, AWDMaterial *mtl) { ColorMaterialCacheItem *item; item = (ColorMaterialCacheItem *)malloc(sizeof(ColorMaterialCacheItem)); item->color = color; item->mtl = mtl; item->next = NULL; if (!firstItem) { firstItem = item; } else { lastItem->next = item; } lastItem = item; } AWDMaterial *ColorMaterialCache::Get(awd_color color) { ColorMaterialCacheItem *cur; cur = firstItem; while (cur) { if (cur->color == color) return cur->mtl; cur = cur->next; } return NULL; } SkeletonCacheItem::SkeletonCacheItem(INode *maxRootBone) { next = NULL; rootBone = maxRootBone; firstJoint = NULL; lastJoint = NULL; numJoints = 0; // Create AWD skeleton structure and begin // gathering joints recursively char *name = rootBone->GetName(); awdSkel = new AWDSkeleton(name, strlen(name)); GatherJoint(rootBone, NULL); } SkeletonCacheItem::~SkeletonCacheItem(void) { // TODO: Delete all joints } void SkeletonCacheItem::AppendCacheJoint(SkeletonCacheJoint *cacheJoint) { if (!firstJoint) { firstJoint = cacheJoint; } else { lastJoint->next = cacheJoint; } lastJoint = cacheJoint; lastJoint->index = numJoints++; lastJoint->next = NULL; } /** * Gather joints using the same order that the AWD SDK uses, so that the * binding code can then look-up indices using this structure. */ void SkeletonCacheItem::GatherJoint(INode *bone, AWDSkeletonJoint *awdParent) { int i; char *name; SkeletonCacheJoint *cacheJoint; AWDSkeletonJoint *awdJoint; Matrix3 boneTM; awd_float64 *bindMtx; // Use bone transform as bind matrix for now. This will be // overwritten by the skin export if exporting skins. boneTM = bone->GetNodeTM(0); bindMtx = (awd_float64*)malloc(sizeof(awd_float64)*12); SerializeMatrix3(Inverse(boneTM), bindMtx); name = bone->GetName(); awdJoint = new AWDSkeletonJoint(name, strlen(name), bindMtx); if (awdParent != NULL) { awdParent->add_child_joint(awdJoint); } else { awdSkel->set_root_joint(awdJoint); } // Add to cache cacheJoint = (SkeletonCacheJoint*)malloc(sizeof(SkeletonCacheJoint)); cacheJoint->awdJoint = awdJoint; cacheJoint->maxBone = bone; AppendCacheJoint(cacheJoint); for (i=0; i<bone->NumberOfChildren(); i++) { INode *child = bone->GetChildNode(i); Object *obj = bone->GetObjectRef(); if (obj && obj->ClassID()==BONE_OBJ_CLASSID) { GatherJoint(child, awdJoint); } } } int SkeletonCacheItem::IndexOfBone(INode *bone) { SkeletonCacheJoint *cur; cur = firstJoint; while (cur) { if (cur->maxBone == bone) return cur->index; cur = cur->next; } return -1; } SkeletonCache::SkeletonCache(void) { firstItem = NULL; lastItem = NULL; cur = NULL; } SkeletonCache::~SkeletonCache(void) { // TODO: Free all items } AWDSkeleton *SkeletonCache::Add(INode *rootBone) { SkeletonCacheItem *item; item = new SkeletonCacheItem(rootBone); if (!firstItem) { firstItem = item; } else { lastItem->next = item; } lastItem = item; // Return skeleton return item->awdSkel; } SkeletonCacheItem *SkeletonCache::GetFromBone(INode *bone) { SkeletonCacheItem *cur; cur = firstItem; while (cur) { // Check if this cache item is a skeleton // containing the supplied bone. if (cur->IndexOfBone(bone) >= 0) return cur; cur = cur->next; } return NULL; } bool SkeletonCache::HasItems() { return (firstItem != NULL); } void SkeletonCache::IterReset() { cur = firstItem; } SkeletonCacheItem *SkeletonCache::IterNext() { // Stop if end was reached if (!cur) return NULL; SkeletonCacheItem *ret = cur; cur = cur->next; return ret; }<|endoftext|>
<commit_before>/* * This file is part of Poedit (https://poedit.net) * * Copyright (C) 2016 Vaclav Slavik * * 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 "win10_menubar.h" #include "utility.h" #include <wx/msw/uxtheme.h> #include <wx/nativewin.h> #include <wx/recguard.h> #include <mCtrl/menubar.h> namespace { int g_mctrlInitialized = 0; } // anonymous namespace class wxFrameWithWindows10Menubar::MenuBarWindow : public wxWindow { public: MenuBarWindow(wxWindow *parent) : wxWindow(parent, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxFULL_REPAINT_ON_RESIZE), m_mctrlWin(nullptr), m_mctrlHandle(0), m_flagReenterMctrl(0) { if (g_mctrlInitialized++ == 0) mcMenubar_Initialize(); m_mctrlHandle = CreateWindowEx ( WS_EX_COMPOSITED, MC_WC_MENUBAR, _T(""), WS_CHILD | WS_VISIBLE | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | CCS_NORESIZE | CCS_NOPARENTALIGN, 0, 0, 1000, 23*2, (HWND)this->GetHWND(), (HMENU) -1, wxGetInstance(), NULL ); SendMessage(m_mctrlHandle, TB_SETEXTENDEDSTYLE, 0, TBSTYLE_EX_HIDECLIPPEDBUTTONS); SendMessage(m_mctrlHandle, CCM_SETNOTIFYWINDOW, (WPARAM)parent->GetHWND(), 0); m_mctrlWin = new mCtrlWrapper(this, m_mctrlHandle); { wxUxThemeHandle hTheme(this, L"ExplorerMenu::Toolbar"); SetBackgroundColour(wxRGBToColour(wxUxThemeEngine::GetIfActive()->GetThemeSysColor(hTheme, COLOR_WINDOW))); } } ~MenuBarWindow() { m_mctrlWin->Destroy(); ::DestroyWindow(m_mctrlHandle); if (--g_mctrlInitialized == 0) mcMenubar_Terminate(); } void SetHMENU(WXHMENU menu) { SendMessage(m_mctrlHandle, MC_MBM_SETMENU, 0, (LPARAM) menu); SendMessage(m_mctrlHandle, MC_MBM_REFRESH, 0, 0); } bool TranslateMenubarMessage(WXMSG *pMsg) { wxRecursionGuard guard(m_flagReenterMctrl); if (!guard.IsInside()) { MSG *msg = (MSG *) pMsg; if (mcIsMenubarMessage(m_mctrlHandle, msg)) return true; } return false; } void DoSetSize(int x, int y, int width, int height, int sizeFlags) override { wxWindow::DoSetSize(x, y, width, height, sizeFlags); SendMessage(m_mctrlHandle, MC_MBM_REFRESH, 0, 0); } wxSize DoGetBestSize() const override { wxSize sizeBest = wxDefaultSize; SIZE size; if (::SendMessage(m_mctrlHandle, TB_GETMAXSIZE, 0, (LPARAM) &size)) { sizeBest.x = size.cx; sizeBest.y = size.cy + 1; CacheBestSize(sizeBest); } return sizeBest; } private: class mCtrlWrapper : public wxNativeWindow { public: mCtrlWrapper(wxWindow *parent, WXHWND wnd) : wxNativeWindow(parent, wxID_ANY, wnd) {} WXLRESULT MSWWindowProc(WXUINT nMsg, WXWPARAM wParam, WXLPARAM lParam) override { switch (nMsg) { case WM_COMMAND: case WM_NOTIFY: return MSWDefWindowProc(nMsg, wParam, lParam); } return wxNativeWindow::MSWWindowProc(nMsg, wParam, lParam); } }; mCtrlWrapper *m_mctrlWin; WXHWND m_mctrlHandle; wxRecursionGuardFlag m_flagReenterMctrl; }; wxFrameWithWindows10Menubar::wxFrameWithWindows10Menubar(wxWindow *parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style, const wxString& name) : wxFrame(parent, id, title, pos, size, style, name), m_menuBar(nullptr) { if (ShouldUse()) { m_menuBar = new MenuBarWindow(this); } } bool wxFrameWithWindows10Menubar::ShouldUse() const { if (!IsWindows10OrGreater()) return false; if (!wxUxThemeEngine::GetIfActive()) return false; // Detect screen readers and use normal menubar with them, because the // mCtrl one isn't accessible. BOOL running; BOOL ret = SystemParametersInfo(SPI_GETSCREENREADER, 0, &running, 0); if (ret && running) return false; return true; } wxPoint wxFrameWithWindows10Menubar::GetClientAreaOrigin() const { wxPoint pt = wxFrame::GetClientAreaOrigin(); if (IsUsed()) { pt.y += m_menuBar->GetSize().y; } return pt; } void wxFrameWithWindows10Menubar::PositionToolBar() { // Position both the toolbar and our menu bar (which is really another toolbar) here. if (!IsUsed()) { wxFrame::PositionToolBar(); return; } // don't call our (or even wxTopLevelWindow) version because we want // the real (full) client area size, not excluding the tool/status bar int width, height; wxWindow::DoGetClientSize(&width, &height); int y = 0; // use the 'real' MSW position here, don't offset relatively to the // client area origin int mch = m_menuBar->GetBestSize().y; m_menuBar->SetSize(0, y, width, mch, wxSIZE_NO_ADJUSTMENTS); y += mch; wxToolBar *toolbar = GetToolBar(); if (toolbar && toolbar->IsShown()) { int tbh = toolbar->GetSize().y; toolbar->SetSize(0, y, width, tbh, wxSIZE_NO_ADJUSTMENTS); } } bool wxFrameWithWindows10Menubar::MSWTranslateMessage(WXMSG *msg) { if (wxFrame::MSWTranslateMessage(msg)) return true; if (IsUsed() && m_menuBar->TranslateMenubarMessage(msg)) return true; return false; } WXLRESULT wxFrameWithWindows10Menubar::MSWWindowProc(WXUINT message, WXWPARAM wParam, WXLPARAM lParam) { if (IsUsed()) { // mCtrl doesn't play nice with the wxMSW's menus interaction where accelerators are updated // when a menu is opened (which works because TranslateAccelerators() normally sends a fake // event for that... if there's a normal menu). We need to refresh menus before accelerators // are used so that e.g. disabled state is accurately updated. if (message == WM_COMMAND && HIWORD(wParam) == 1/*accel*/) GetMenuBar()->UpdateMenus(); } return wxFrame::MSWWindowProc(message, wParam, lParam); } void wxFrameWithWindows10Menubar::InternalSetMenuBar() { if (IsUsed()) { m_menuBar->SetHMENU(m_hMenu); } else { wxFrame::InternalSetMenuBar(); } } <commit_msg>Fix rendering artifacts around mCtrl menu on Win10<commit_after>/* * This file is part of Poedit (https://poedit.net) * * Copyright (C) 2016 Vaclav Slavik * * 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 "win10_menubar.h" #include "utility.h" #include <wx/msw/uxtheme.h> #include <wx/nativewin.h> #include <wx/recguard.h> #include <mCtrl/menubar.h> namespace { int g_mctrlInitialized = 0; const int MENUBAR_OFFSET = -2; } // anonymous namespace class wxFrameWithWindows10Menubar::MenuBarWindow : public wxWindow { public: MenuBarWindow(wxWindow *parent) : wxWindow(parent, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxFULL_REPAINT_ON_RESIZE), m_mctrlWin(nullptr), m_mctrlHandle(0), m_flagReenterMctrl(0) { if (g_mctrlInitialized++ == 0) mcMenubar_Initialize(); m_mctrlHandle = CreateWindowEx ( WS_EX_COMPOSITED, MC_WC_MENUBAR, _T(""), WS_CHILD | WS_VISIBLE | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | CCS_NORESIZE | CCS_NOPARENTALIGN, 0, 0, 1000, 23*2, (HWND)this->GetHWND(), (HMENU) -1, wxGetInstance(), NULL ); SendMessage(m_mctrlHandle, TB_SETEXTENDEDSTYLE, 0, TBSTYLE_EX_HIDECLIPPEDBUTTONS); SendMessage(m_mctrlHandle, CCM_SETNOTIFYWINDOW, (WPARAM)parent->GetHWND(), 0); m_mctrlWin = new mCtrlWrapper(this, m_mctrlHandle); { wxUxThemeHandle hTheme(this, L"ExplorerMenu::Toolbar"); SetBackgroundColour(wxRGBToColour(wxUxThemeEngine::GetIfActive()->GetThemeSysColor(hTheme, COLOR_WINDOW))); } } ~MenuBarWindow() { m_mctrlWin->Destroy(); ::DestroyWindow(m_mctrlHandle); if (--g_mctrlInitialized == 0) mcMenubar_Terminate(); } void SetHMENU(WXHMENU menu) { SendMessage(m_mctrlHandle, MC_MBM_SETMENU, 0, (LPARAM) menu); SendMessage(m_mctrlHandle, MC_MBM_REFRESH, 0, 0); } bool TranslateMenubarMessage(WXMSG *pMsg) { wxRecursionGuard guard(m_flagReenterMctrl); if (!guard.IsInside()) { MSG *msg = (MSG *) pMsg; if (mcIsMenubarMessage(m_mctrlHandle, msg)) return true; } return false; } void DoSetSize(int x, int y, int width, int height, int sizeFlags) override { wxWindow::DoSetSize(x, y, width, height, sizeFlags); SendMessage(m_mctrlHandle, MC_MBM_REFRESH, 0, 0); } wxSize DoGetBestSize() const override { wxSize sizeBest = wxDefaultSize; SIZE size; if (::SendMessage(m_mctrlHandle, TB_GETMAXSIZE, 0, (LPARAM) &size)) { sizeBest.x = size.cx; sizeBest.y = size.cy + 1; CacheBestSize(sizeBest); } return sizeBest; } private: class mCtrlWrapper : public wxNativeWindow { public: mCtrlWrapper(wxWindow *parent, WXHWND wnd) : wxNativeWindow(parent, wxID_ANY, wnd) {} WXLRESULT MSWWindowProc(WXUINT nMsg, WXWPARAM wParam, WXLPARAM lParam) override { switch (nMsg) { case WM_COMMAND: case WM_NOTIFY: return MSWDefWindowProc(nMsg, wParam, lParam); } return wxNativeWindow::MSWWindowProc(nMsg, wParam, lParam); } }; mCtrlWrapper *m_mctrlWin; WXHWND m_mctrlHandle; wxRecursionGuardFlag m_flagReenterMctrl; }; wxFrameWithWindows10Menubar::wxFrameWithWindows10Menubar(wxWindow *parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style, const wxString& name) : wxFrame(parent, id, title, pos, size, style, name), m_menuBar(nullptr) { if (ShouldUse()) { m_menuBar = new MenuBarWindow(this); } } bool wxFrameWithWindows10Menubar::ShouldUse() const { if (!IsWindows10OrGreater()) return false; if (!wxUxThemeEngine::GetIfActive()) return false; // Detect screen readers and use normal menubar with them, because the // mCtrl one isn't accessible. BOOL running; BOOL ret = SystemParametersInfo(SPI_GETSCREENREADER, 0, &running, 0); if (ret && running) return false; return true; } wxPoint wxFrameWithWindows10Menubar::GetClientAreaOrigin() const { wxPoint pt = wxFrame::GetClientAreaOrigin(); if (IsUsed()) { pt.y += m_menuBar->GetSize().y + MENUBAR_OFFSET; } return pt; } void wxFrameWithWindows10Menubar::PositionToolBar() { // Position both the toolbar and our menu bar (which is really another toolbar) here. if (!IsUsed()) { wxFrame::PositionToolBar(); return; } // don't call our (or even wxTopLevelWindow) version because we want // the real (full) client area size, not excluding the tool/status bar int width, height; wxWindow::DoGetClientSize(&width, &height); int y = MENUBAR_OFFSET; // use the 'real' MSW position here, don't offset relatively to the // client area origin int mch = m_menuBar->GetBestSize().y; m_menuBar->SetSize(0, y, width, mch, wxSIZE_NO_ADJUSTMENTS); y += mch; wxToolBar *toolbar = GetToolBar(); if (toolbar && toolbar->IsShown()) { int tbh = toolbar->GetSize().y; toolbar->SetSize(0, y, width + 8, tbh, wxSIZE_NO_ADJUSTMENTS); } } bool wxFrameWithWindows10Menubar::MSWTranslateMessage(WXMSG *msg) { if (wxFrame::MSWTranslateMessage(msg)) return true; if (IsUsed() && m_menuBar->TranslateMenubarMessage(msg)) return true; return false; } WXLRESULT wxFrameWithWindows10Menubar::MSWWindowProc(WXUINT message, WXWPARAM wParam, WXLPARAM lParam) { if (IsUsed()) { // mCtrl doesn't play nice with the wxMSW's menus interaction where accelerators are updated // when a menu is opened (which works because TranslateAccelerators() normally sends a fake // event for that... if there's a normal menu). We need to refresh menus before accelerators // are used so that e.g. disabled state is accurately updated. if (message == WM_COMMAND && HIWORD(wParam) == 1/*accel*/) GetMenuBar()->UpdateMenus(); } return wxFrame::MSWWindowProc(message, wParam, lParam); } void wxFrameWithWindows10Menubar::InternalSetMenuBar() { if (IsUsed()) { m_menuBar->SetHMENU(m_hMenu); } else { wxFrame::InternalSetMenuBar(); } } <|endoftext|>
<commit_before>//----------------------------------*-C++-*----------------------------------// /*! * \file core/test/tstTransfer_Map.cc * \author Stuart Slattery * \date Mon Oct 31 12:15:31 2011 * \brief Unit test for the transfer map. * \note Copyright (C) 2008 Oak Ridge National Laboratory, UT-Battelle, LLC. */ //---------------------------------------------------------------------------// // $Id: template_c4_test.cc,v 1.7 2008/01/02 22:50:26 9te Exp $ //---------------------------------------------------------------------------// #include <iostream> #include <vector> #include <cmath> #include <sstream> #include <map> #include <set> #include <iterator> #include "harness/DBC.hh" #include "harness/Soft_Equivalence.hh" #include "comm/global.hh" #include "comm/Parallel_Unit_Test.hh" #include "release/Release.hh" #include "../Transfer_Map.hh" using namespace std; using nemesis::Parallel_Unit_Test; using nemesis::soft_equiv; using coupler::Transfer_Map; int node = 0; int nodes = 0; #define ITFAILS ut.failure(__LINE__); #define UNIT_TEST(a) if (!(a)) ut.failure(__LINE__); //---------------------------------------------------------------------------// // TESTS //---------------------------------------------------------------------------// void map_test(Parallel_Unit_Test &ut) { // Useful typedefs. typedef typename Transfer_Map::Map_Iterator Map_Iterator; typedef typename Transfer_Map::Map_Pair Map_Pair; typedef typename Transfer_Map::Set_Iterator Set_Iterator; typedef typename Transfer_Map::Set_Pair Set_Pair; // Make a map object with integer handles and ranks. Transfer_Map tmap; // Add domain pairs. tmap.add_domain_pair(1, 21); tmap.add_domain_pair(1, 32); tmap.add_domain_pair(1, 12); tmap.add_domain_pair(3, 2); tmap.add_domain_pair(4, 22); tmap.add_domain_pair(2, 54); tmap.add_domain_pair(3, 5); // Check the size of the domains. UNIT_TEST( tmap.domain_size(1) == 3 ); UNIT_TEST( tmap.domain_size(2) == 1 ); UNIT_TEST( tmap.domain_size(3) == 2 ); UNIT_TEST( tmap.domain_size(4) == 1 ); // Check the contents of the domains. Map_Pair domain_1 = tmap.domain(1); UNIT_TEST( std::distance(domain_1.first, domain_1.second) == 3 ); UNIT_TEST( domain_1.first->second == 12 ); UNIT_TEST( (domain_1.first+1)->second == 21 ); UNIT_TEST( (domain_1.first+2)->second == 32 ); Map_Pair domain_2 = tmap.domain(2); UNIT_TEST( std::distance(domain_2.first, domain_2.second) == 1 ); UNIT_TEST( *((domain_2.first)->second) == 54 ); Map_Pair domain_3 = tmap.domain(3); UNIT_TEST( std::distance(domain_3.first, domain_3.second) == 2 ); UNIT_TEST( *((domain_3.first)->second) == 2 ); UNIT_TEST( *((domain_3.first+1)->second) == 5 ); Map_Pair domain_4 = tmap.domain(4); UNIT_TEST( std::distance(domain_4.first, domain_4.second) == 1 ); UNIT_TEST( *((domain_4.first)->second) == 22 ); // Add range pairs. tmap.add_range_pair(8, 9); tmap.add_range_pair(32, 1); tmap.add_range_pair(8, 4); tmap.add_range_pair(8, 34); tmap.add_range_pair(32, 3); // Check the size of the ranges. UNIT_TEST( tmap.range_size(8) == 3 ); UNIT_TEST( tmap.range_size(32) == 2 ); // Check the contents of the ranges. Map_Pair range_8 = tmap.range(8); UNIT_TEST( std::distance(range_8.first,range_8.second) == 3 ); UNIT_TEST( *((range_8.first)->second) == 4 ); UNIT_TEST( *((range_8.first+1)->second) == 9 ); UNIT_TEST( *((range_8.first+2)->second) == 34 ); Map_Pair range_32 = tmap.range(32); UNIT_TEST( std::distance(range_32.first,range_32.second) == 2 ); UNIT_TEST( *((range_32.first)->second) == 1 ); UNIT_TEST( *((range_32.first+1)->second) == 3 ); // Check the source and target sets. Set_Pair sources = tmap.sources(); UNIT_TEST( std::distance(sources.first, sources.second) == 2 ); UNIT_TEST( *(sources.first) == 8 ); UNIT_TEST( *(sources.first+1) == 32 ); Set_Pair targets = tmap.targets(); UNIT_TEST( std::distance(targets.first, targets.second) == 4 ); UNIT_TEST( *(targets.first) == 1 ); UNIT_TEST( *(targets.first+1) == 2 ); UNIT_TEST( *(targets.first+2) == 3 ); UNIT_TEST( *(targets.first+3) == 4 ); if (ut.numFails == 0) { std::ostringstream m; m << "Transfer_Map test passes on " << node; ut.passes( m.str() ); } } //---------------------------------------------------------------------------// int main(int argc, char *argv[]) { Parallel_Unit_Test ut(argc, argv, coupler::release); node = nemesis::node(); nodes = nemesis::nodes(); try { // >>> UNIT TESTS int gpass = 0; int gfail = 0; map_test(ut); gpass += ut.numPasses; gfail += ut.numFails; ut.reset(); // add up global passes and fails nemesis::global_sum(gpass); nemesis::global_sum(gfail); ut.numPasses = gpass; ut.numFails = gfail; } catch (std::exception &err) { std::cout << "ERROR: While testing tstTransfer_Map, " << err.what() << endl; ut.numFails++; } catch( ... ) { std::cout << "ERROR: While testing tstTransfer_Map, " << "An unknown exception was thrown." << endl; ut.numFails++; } return ut.numFails; } //---------------------------------------------------------------------------// // end of tstTransfer_Map.cc //---------------------------------------------------------------------------// <commit_msg>Fixed Transfer_Map unit test. Passes in parallel<commit_after>//----------------------------------*-C++-*----------------------------------// /*! * \file core/test/tstTransfer_Map.cc * \author Stuart Slattery * \date Mon Oct 31 12:15:31 2011 * \brief Unit test for the transfer map. * \note Copyright (C) 2008 Oak Ridge National Laboratory, UT-Battelle, LLC. */ //---------------------------------------------------------------------------// // $Id: template_c4_test.cc,v 1.7 2008/01/02 22:50:26 9te Exp $ //---------------------------------------------------------------------------// #include <iostream> #include <vector> #include <cmath> #include <sstream> #include <map> #include <set> #include <iterator> #include "harness/DBC.hh" #include "harness/Soft_Equivalence.hh" #include "comm/global.hh" #include "comm/Parallel_Unit_Test.hh" #include "release/Release.hh" #include "../Transfer_Map.hh" using namespace std; using nemesis::Parallel_Unit_Test; using nemesis::soft_equiv; using coupler::Transfer_Map; int node = 0; int nodes = 0; #define ITFAILS ut.failure(__LINE__); #define UNIT_TEST(a) if (!(a)) ut.failure(__LINE__); //---------------------------------------------------------------------------// // TESTS //---------------------------------------------------------------------------// void map_test(Parallel_Unit_Test &ut) { // Useful typedefs. typedef typename Transfer_Map::Map_Iterator Map_Iterator; typedef typename Transfer_Map::Map_Pair Map_Pair; typedef typename Transfer_Map::Set_Iterator Set_Iterator; typedef typename Transfer_Map::Set_Pair Set_Pair; // Make a map object with integer handles and ranks. Transfer_Map tmap; // Add domain pairs. tmap.add_domain_pair(1, 21); tmap.add_domain_pair(1, 32); tmap.add_domain_pair(1, 12); tmap.add_domain_pair(3, 2); tmap.add_domain_pair(4, 22); tmap.add_domain_pair(2, 54); tmap.add_domain_pair(3, 5); // Check the size of the domains. UNIT_TEST( tmap.domain_size(1) == 3 ); UNIT_TEST( tmap.domain_size(2) == 1 ); UNIT_TEST( tmap.domain_size(3) == 2 ); UNIT_TEST( tmap.domain_size(4) == 1 ); // Check the contents of the domains. Map_Pair domain_1 = tmap.domain(1); UNIT_TEST( std::distance(domain_1.first, domain_1.second) == 3 ); Map_Iterator domain_it_1 = domain_1.first; UNIT_TEST( domain_it_1->second == 21 ); ++domain_it_1; UNIT_TEST( domain_it_1->second == 32 ); ++domain_it_1; UNIT_TEST( domain_it_1->second == 12 ); Map_Pair domain_2 = tmap.domain(2); UNIT_TEST( std::distance(domain_2.first, domain_2.second) == 1 ); Map_Iterator domain_it_2 = domain_2.first; UNIT_TEST( domain_it_2->second == 54 ); Map_Pair domain_3 = tmap.domain(3); UNIT_TEST( std::distance(domain_3.first, domain_3.second) == 2 ); Map_Iterator domain_it_3 = domain_3.first; UNIT_TEST( domain_it_3->second == 2 ); ++domain_it_3; UNIT_TEST( domain_it_3->second == 5 ); Map_Pair domain_4 = tmap.domain(4); UNIT_TEST( std::distance(domain_4.first, domain_4.second) == 1 ); Map_Iterator domain_it_4 = domain_4.first; UNIT_TEST( domain_it_4->second == 22 ); // Add range pairs. tmap.add_range_pair(8, 9); tmap.add_range_pair(32, 1); tmap.add_range_pair(8, 4); tmap.add_range_pair(8, 34); tmap.add_range_pair(32, 3); // Check the size of the ranges. UNIT_TEST( tmap.range_size(8) == 3 ); UNIT_TEST( tmap.range_size(32) == 2 ); // Check the contents of the ranges. Map_Pair range_8 = tmap.range(8); UNIT_TEST( std::distance(range_8.first,range_8.second) == 3 ); Map_Iterator range_it_8 = range_8.first; UNIT_TEST( range_it_8->second == 9 ); ++range_it_8; UNIT_TEST( range_it_8->second == 4 ); ++range_it_8; UNIT_TEST( range_it_8->second == 34 ); Map_Pair range_32 = tmap.range(32); UNIT_TEST( std::distance(range_32.first,range_32.second) == 2 ); Map_Iterator range_it_32 = range_32.first; UNIT_TEST( range_it_32->second == 1 ); ++range_it_32; UNIT_TEST( range_it_32->second == 3 ); // Check the source and target sets. Set_Pair sources = tmap.sources(); UNIT_TEST( std::distance(sources.first, sources.second) == 2 ); Set_Iterator source_it = sources.first; UNIT_TEST( *source_it == 8 ); ++source_it; UNIT_TEST( *source_it == 32 ); Set_Pair targets = tmap.targets(); UNIT_TEST( std::distance(targets.first, targets.second) == 4 ); Set_Iterator target_it = targets.first; UNIT_TEST( *target_it == 1 ); ++target_it; UNIT_TEST( *target_it == 2 ); ++target_it; UNIT_TEST( *target_it == 3 ); ++target_it; UNIT_TEST( *target_it == 4 ); if (ut.numFails == 0) { std::ostringstream m; m << "Transfer_Map test passes on " << node; ut.passes( m.str() ); } } //---------------------------------------------------------------------------// int main(int argc, char *argv[]) { Parallel_Unit_Test ut(argc, argv, coupler::release); node = nemesis::node(); nodes = nemesis::nodes(); try { // >>> UNIT TESTS int gpass = 0; int gfail = 0; map_test(ut); gpass += ut.numPasses; gfail += ut.numFails; ut.reset(); // add up global passes and fails nemesis::global_sum(gpass); nemesis::global_sum(gfail); ut.numPasses = gpass; ut.numFails = gfail; } catch (std::exception &err) { std::cout << "ERROR: While testing tstTransfer_Map, " << err.what() << endl; ut.numFails++; } catch( ... ) { std::cout << "ERROR: While testing tstTransfer_Map, " << "An unknown exception was thrown." << endl; ut.numFails++; } return ut.numFails; } //---------------------------------------------------------------------------// // end of tstTransfer_Map.cc //---------------------------------------------------------------------------// <|endoftext|>
<commit_before>// Copyright 2010 Google // 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 "base/random.h" namespace operations_research { int32 ACMRandom::Next() { const int32 M = 2147483647L; // 2^31-1 const int32 A = 16807; // In effect, we are computing seed_ = (seed_ * A) % M, where M = 2^31-1 uint32 lo = A * static_cast<int32>(seed_ & 0xFFFF); uint32 hi = A * static_cast<int32>(static_cast<uint32>(seed_) >> 16); lo += (hi & 0x7FFF) << 16; if (lo > M) { lo &= M; ++lo; } lo += hi >> 15; if (lo > M) { lo &= M; ++lo; } return (seed_ = static_cast<int32>(lo)); } int32 ACMRandom::Uniform(int32 n) { return Next() % n; } int64 ACMRandom::Next64() { const int64 next = Next(); return (next - 1) * 2147483646L + Next(); } namespace { static inline uint32 Word32At(const char *ptr) { return ((static_cast<uint32>(ptr[0])) + (static_cast<uint32>(ptr[1]) << 8) + (static_cast<uint32>(ptr[2]) << 16) + (static_cast<uint32>(ptr[3]) << 24)); } } // namespace #if defined(__GNUC__) && defined(__linux__) #include <linux/limits.h> #endif #if defined(_MSC_VER) #include <windows.h> #define PATH_MAX 4096 #endif int32 ACMRandom::HostnamePidTimeSeed() { char name[PATH_MAX + 20]; // need 12 bytes for 3 'empty' uint32's assert(sizeof(name) - PATH_MAX > sizeof(uint32) * 3); if (gethostname(name, PATH_MAX) != 0) { strcpy(name, "default-hostname"); } const int namelen = strlen(name); for (int i = 0; i < sizeof(uint32) * 3; ++i) { name[namelen + i] = '\0'; // so we mix 0's once we get to end-of-string } #if defined(__GNUC__) uint32 a = getpid(); struct timeval tv; gettimeofday(&tv, NULL); uint32 b = static_cast<uint32>((tv.tv_sec + tv.tv_usec) & 0xffffffff); #elif defined(_MSC_VER) uint32 a = GetCurrentProcessId(); uint32 b = GetTickCount(); #else // Do not know what to do, returning 0. return 0; #endif uint32 c = 0; for (int i = 0; i < namelen; i += sizeof(uint32) * 3) { a += Word32At(name + i); b += Word32At(name + i + sizeof(uint32)); c += Word32At(name + i + sizeof(uint32) + sizeof(uint32)); mix(a, b, c); } c += namelen; // one final mix mix(a,b,c); return static_cast<int32>(c); // I guess the seed can be negative } int32 ACMRandom::DeterministicSeed() { return 0; } } // namespace operations_research <commit_msg>fix random when seed == 0<commit_after>// Copyright 2010 Google // 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 "base/random.h" namespace operations_research { int32 ACMRandom::Next() { if (seed_ == 0) { seed_ = 0x14fd4603; // Arbitrary random constant } const int32 M = 2147483647L; // 2^31-1 const int32 A = 16807; // In effect, we are computing seed_ = (seed_ * A) % M, where M = 2^31-1 uint32 lo = A * static_cast<int32>(seed_ & 0xFFFF); uint32 hi = A * static_cast<int32>(static_cast<uint32>(seed_) >> 16); lo += (hi & 0x7FFF) << 16; if (lo > M) { lo &= M; ++lo; } lo += hi >> 15; if (lo > M) { lo &= M; ++lo; } seed_ = static_cast<int32>(lo); return seed_; } int32 ACMRandom::Uniform(int32 n) { return Next() % n; } int64 ACMRandom::Next64() { const int64 next = Next(); return (next - 1) * 2147483646L + Next(); } namespace { static inline uint32 Word32At(const char *ptr) { return ((static_cast<uint32>(ptr[0])) + (static_cast<uint32>(ptr[1]) << 8) + (static_cast<uint32>(ptr[2]) << 16) + (static_cast<uint32>(ptr[3]) << 24)); } } // namespace #if defined(__GNUC__) && defined(__linux__) #include <linux/limits.h> #endif #if defined(_MSC_VER) #include <windows.h> #define PATH_MAX 4096 #endif int32 ACMRandom::HostnamePidTimeSeed() { char name[PATH_MAX + 20]; // need 12 bytes for 3 'empty' uint32's assert(sizeof(name) - PATH_MAX > sizeof(uint32) * 3); if (gethostname(name, PATH_MAX) != 0) { strcpy(name, "default-hostname"); } const int namelen = strlen(name); for (int i = 0; i < sizeof(uint32) * 3; ++i) { name[namelen + i] = '\0'; // so we mix 0's once we get to end-of-string } #if defined(__GNUC__) uint32 a = getpid(); struct timeval tv; gettimeofday(&tv, NULL); uint32 b = static_cast<uint32>((tv.tv_sec + tv.tv_usec) & 0xffffffff); #elif defined(_MSC_VER) uint32 a = GetCurrentProcessId(); uint32 b = GetTickCount(); #else // Do not know what to do, returning 0. return 0; #endif uint32 c = 0; for (int i = 0; i < namelen; i += sizeof(uint32) * 3) { a += Word32At(name + i); b += Word32At(name + i + sizeof(uint32)); c += Word32At(name + i + sizeof(uint32) + sizeof(uint32)); mix(a, b, c); } c += namelen; // one final mix mix(a,b,c); return static_cast<int32>(c); // I guess the seed can be negative } int32 ACMRandom::DeterministicSeed() { return 0; } } // namespace operations_research <|endoftext|>
<commit_before>#include "gtest/gtest.h" #include "paxos/ledger.hpp" class LedgerUnitTest: public testing::Test { virtual void SetUp() { DisableLogging(); } }; TEST_F(LedgerUnitTest, testAppendIncrementsTheSize) { Ledger ledger(std::make_shared<VolatileQueue<Decree>>()); ASSERT_EQ(ledger.Size(), 0); ledger.Append(Decree(Replica("an_author"), 1, "decree_contents", DecreeType::UserDecree)); ASSERT_EQ(ledger.Size(), 1); } TEST_F(LedgerUnitTest, testRemoveDecrementsTheSize) { Ledger ledger(std::make_shared<VolatileQueue<Decree>>()); ledger.Append(Decree(Replica("an_author"), 1, "decree_contents", DecreeType::UserDecree)); ledger.Remove(); ASSERT_EQ(ledger.Size(), 0); } TEST_F(LedgerUnitTest, testEmptyHeadReturnsDefaultDecree) { Ledger ledger(std::make_shared<VolatileQueue<Decree>>()); Decree expected, actual = ledger.Head(); ASSERT_EQ(expected.author.hostname, actual.author.hostname); ASSERT_EQ(expected.author.port, actual.author.port); ASSERT_EQ(expected.number, actual.number); ASSERT_EQ(expected.content, actual.content); } TEST_F(LedgerUnitTest, testEmptyTailReturnsDefaultDecree) { Ledger ledger(std::make_shared<VolatileQueue<Decree>>()); Decree expected, actual = ledger.Tail(); ASSERT_EQ(expected.author.hostname, actual.author.hostname); ASSERT_EQ(expected.author.port, actual.author.port); ASSERT_EQ(expected.number, actual.number); ASSERT_EQ(expected.content, actual.content); } TEST_F(LedgerUnitTest, testEmptyNextWithFutureDecree) { Ledger ledger(std::make_shared<VolatileQueue<Decree>>()); Decree expected, actual = ledger.Next(Decree(Replica("b_author"), 2, "b_content", DecreeType::UserDecree)); ASSERT_EQ(expected.author.hostname, actual.author.hostname); ASSERT_EQ(expected.author.port, actual.author.port); ASSERT_EQ(expected.number, actual.number); ASSERT_EQ(expected.content, actual.content); } TEST_F(LedgerUnitTest, testHeadWithMultipleDecrees) { Ledger ledger(std::make_shared<VolatileQueue<Decree>>()); ledger.Append(Decree(Replica("a_author"), 1, "a_content", DecreeType::UserDecree)); ledger.Append(Decree(Replica("b_author"), 2, "b_content", DecreeType::UserDecree)); Decree expected = Decree(Replica("a_author"), 1, "a_content", DecreeType::UserDecree), actual = ledger.Head(); ASSERT_EQ(expected.author.hostname, actual.author.hostname); ASSERT_EQ(expected.author.port, actual.author.port); ASSERT_EQ(expected.number, actual.number); ASSERT_EQ(expected.content, actual.content); } TEST_F(LedgerUnitTest, testTailWithMultipleDecrees) { Ledger ledger(std::make_shared<VolatileQueue<Decree>>()); ledger.Append(Decree(Replica("a_author"), 1, "a_content", DecreeType::UserDecree)); ledger.Append(Decree(Replica("b_author"), 2, "b_content", DecreeType::UserDecree)); Decree expected = Decree(Replica("b_author"), 2, "b_content", DecreeType::UserDecree), actual = ledger.Tail(); ASSERT_EQ(expected.author.hostname, actual.author.hostname); ASSERT_EQ(expected.author.port, actual.author.port); ASSERT_EQ(expected.number, actual.number); ASSERT_EQ(expected.content, actual.content); } TEST_F(LedgerUnitTest, testNextWithMultipleDecrees) { Ledger ledger(std::make_shared<VolatileQueue<Decree>>()); ledger.Append(Decree(Replica("a_author"), 1, "a_content", DecreeType::UserDecree)); ledger.Append(Decree(Replica("b_author"), 2, "b_content", DecreeType::UserDecree)); ledger.Append(Decree(Replica("c_author"), 3, "c_content", DecreeType::UserDecree)); Decree expected = Decree(Replica("b_author"), 2, "b_content", DecreeType::UserDecree), actual = ledger.Next(Decree(Replica("a_author"), 1, "a_content", DecreeType::UserDecree)); ASSERT_EQ(expected.author.hostname, actual.author.hostname); ASSERT_EQ(expected.author.port, actual.author.port); ASSERT_EQ(expected.number, actual.number); ASSERT_EQ(expected.content, actual.content); } TEST_F(LedgerUnitTest, testAppendIgnoresOutOfOrderDecrees) { Ledger ledger(std::make_shared<VolatileQueue<Decree>>()); ledger.Append(Decree(Replica("b_author"), 2, "b_content", DecreeType::UserDecree)); ledger.Append(Decree(Replica("a_author"), 1, "a_content", DecreeType::UserDecree)); ASSERT_EQ(ledger.Size(), 1); } TEST_F(LedgerUnitTest, testAppendIgnoresDuplicateDecrees) { Ledger ledger(std::make_shared<VolatileQueue<Decree>>()); ledger.Append(Decree(Replica("a_author"), 1, "a_content", DecreeType::UserDecree)); ledger.Append(Decree(Replica("a_author"), 1, "a_content", DecreeType::UserDecree)); ASSERT_EQ(ledger.Size(), 1); } TEST_F(LedgerUnitTest, testDecreeHandlerOnAppend) { std::string concatenated_content; auto handler = [&](std::string entry) { concatenated_content += entry; }; Ledger ledger( std::make_shared<VolatileQueue<Decree>>(), DecreeHandler(handler), DecreeHandler()); ledger.Append(Decree(Replica("a_author"), 1, "AAAAA", DecreeType::UserDecree)); ledger.Append(Decree(Replica("b_author"), 2, "BBBBB", DecreeType::UserDecree)); ASSERT_EQ(concatenated_content, "AAAAABBBBB"); } <commit_msg>Add unittest on ledger append of system decree<commit_after>#include "gtest/gtest.h" #include "paxos/ledger.hpp" class LedgerUnitTest: public testing::Test { virtual void SetUp() { DisableLogging(); } }; TEST_F(LedgerUnitTest, testAppendIncrementsTheSize) { Ledger ledger(std::make_shared<VolatileQueue<Decree>>()); ASSERT_EQ(ledger.Size(), 0); ledger.Append(Decree(Replica("an_author"), 1, "decree_contents", DecreeType::UserDecree)); ASSERT_EQ(ledger.Size(), 1); } TEST_F(LedgerUnitTest, testAppendSystemDecreeIncrementsTheSize) { Ledger ledger(std::make_shared<VolatileQueue<Decree>>()); ASSERT_EQ(ledger.Size(), 0); ledger.Append(Decree(Replica("an_author"), 1, "decree_contents", DecreeType::SystemDecree)); ASSERT_EQ(ledger.Size(), 1); } TEST_F(LedgerUnitTest, testRemoveDecrementsTheSize) { Ledger ledger(std::make_shared<VolatileQueue<Decree>>()); ledger.Append(Decree(Replica("an_author"), 1, "decree_contents", DecreeType::UserDecree)); ledger.Remove(); ASSERT_EQ(ledger.Size(), 0); } TEST_F(LedgerUnitTest, testEmptyHeadReturnsDefaultDecree) { Ledger ledger(std::make_shared<VolatileQueue<Decree>>()); Decree expected, actual = ledger.Head(); ASSERT_EQ(expected.author.hostname, actual.author.hostname); ASSERT_EQ(expected.author.port, actual.author.port); ASSERT_EQ(expected.number, actual.number); ASSERT_EQ(expected.content, actual.content); } TEST_F(LedgerUnitTest, testEmptyTailReturnsDefaultDecree) { Ledger ledger(std::make_shared<VolatileQueue<Decree>>()); Decree expected, actual = ledger.Tail(); ASSERT_EQ(expected.author.hostname, actual.author.hostname); ASSERT_EQ(expected.author.port, actual.author.port); ASSERT_EQ(expected.number, actual.number); ASSERT_EQ(expected.content, actual.content); } TEST_F(LedgerUnitTest, testEmptyNextWithFutureDecree) { Ledger ledger(std::make_shared<VolatileQueue<Decree>>()); Decree expected, actual = ledger.Next(Decree(Replica("b_author"), 2, "b_content", DecreeType::UserDecree)); ASSERT_EQ(expected.author.hostname, actual.author.hostname); ASSERT_EQ(expected.author.port, actual.author.port); ASSERT_EQ(expected.number, actual.number); ASSERT_EQ(expected.content, actual.content); } TEST_F(LedgerUnitTest, testHeadWithMultipleDecrees) { Ledger ledger(std::make_shared<VolatileQueue<Decree>>()); ledger.Append(Decree(Replica("a_author"), 1, "a_content", DecreeType::UserDecree)); ledger.Append(Decree(Replica("b_author"), 2, "b_content", DecreeType::UserDecree)); Decree expected = Decree(Replica("a_author"), 1, "a_content", DecreeType::UserDecree), actual = ledger.Head(); ASSERT_EQ(expected.author.hostname, actual.author.hostname); ASSERT_EQ(expected.author.port, actual.author.port); ASSERT_EQ(expected.number, actual.number); ASSERT_EQ(expected.content, actual.content); } TEST_F(LedgerUnitTest, testTailWithMultipleDecrees) { Ledger ledger(std::make_shared<VolatileQueue<Decree>>()); ledger.Append(Decree(Replica("a_author"), 1, "a_content", DecreeType::UserDecree)); ledger.Append(Decree(Replica("b_author"), 2, "b_content", DecreeType::UserDecree)); Decree expected = Decree(Replica("b_author"), 2, "b_content", DecreeType::UserDecree), actual = ledger.Tail(); ASSERT_EQ(expected.author.hostname, actual.author.hostname); ASSERT_EQ(expected.author.port, actual.author.port); ASSERT_EQ(expected.number, actual.number); ASSERT_EQ(expected.content, actual.content); } TEST_F(LedgerUnitTest, testNextWithMultipleDecrees) { Ledger ledger(std::make_shared<VolatileQueue<Decree>>()); ledger.Append(Decree(Replica("a_author"), 1, "a_content", DecreeType::UserDecree)); ledger.Append(Decree(Replica("b_author"), 2, "b_content", DecreeType::UserDecree)); ledger.Append(Decree(Replica("c_author"), 3, "c_content", DecreeType::UserDecree)); Decree expected = Decree(Replica("b_author"), 2, "b_content", DecreeType::UserDecree), actual = ledger.Next(Decree(Replica("a_author"), 1, "a_content", DecreeType::UserDecree)); ASSERT_EQ(expected.author.hostname, actual.author.hostname); ASSERT_EQ(expected.author.port, actual.author.port); ASSERT_EQ(expected.number, actual.number); ASSERT_EQ(expected.content, actual.content); } TEST_F(LedgerUnitTest, testAppendIgnoresOutOfOrderDecrees) { Ledger ledger(std::make_shared<VolatileQueue<Decree>>()); ledger.Append(Decree(Replica("b_author"), 2, "b_content", DecreeType::UserDecree)); ledger.Append(Decree(Replica("a_author"), 1, "a_content", DecreeType::UserDecree)); ASSERT_EQ(ledger.Size(), 1); } TEST_F(LedgerUnitTest, testAppendIgnoresDuplicateDecrees) { Ledger ledger(std::make_shared<VolatileQueue<Decree>>()); ledger.Append(Decree(Replica("a_author"), 1, "a_content", DecreeType::UserDecree)); ledger.Append(Decree(Replica("a_author"), 1, "a_content", DecreeType::UserDecree)); ASSERT_EQ(ledger.Size(), 1); } TEST_F(LedgerUnitTest, testDecreeHandlerOnAppend) { std::string concatenated_content; auto handler = [&](std::string entry) { concatenated_content += entry; }; Ledger ledger( std::make_shared<VolatileQueue<Decree>>(), DecreeHandler(handler), DecreeHandler()); ledger.Append(Decree(Replica("a_author"), 1, "AAAAA", DecreeType::UserDecree)); ledger.Append(Decree(Replica("b_author"), 2, "BBBBB", DecreeType::UserDecree)); ASSERT_EQ(concatenated_content, "AAAAABBBBB"); } <|endoftext|>
<commit_before>/* Copyright (c) 2014-2016 AscEmu Team <http://www.ascemu.org/> This file is released under the MIT license. See README-MIT for more information. */ #include "StdAfx.h" SpellInfo::SpellInfo() { Id = 0; Category = 0; DispelType = 0; MechanicsType = 0; Attributes = 0; AttributesEx = 0; AttributesExB = 0; AttributesExC = 0; AttributesExD = 0; AttributesExE = 0; AttributesExF = 0; AttributesExG = 0; RequiredShapeShift = 0; ShapeshiftExclude = 0; Targets = 0; TargetCreatureType = 0; RequiresSpellFocus = 0; FacingCasterFlags = 0; CasterAuraState = 0; TargetAuraState = 0; CasterAuraStateNot = 0; TargetAuraStateNot = 0; casterAuraSpell = 0; targetAuraSpell = 0; casterAuraSpellNot = 0; CustomFlags = 0; for (uint8 i = 0; i < MAX_SPELL_EFFECTS; i++) EffectCustomFlag[i] = 0; SpellFactoryFunc = NULL; AuraFactoryFunc = NULL; custom_proc_interval = 0; custom_BGR_one_buff_on_target = 0; custom_BGR_one_buff_from_caster_on_self = 0; custom_c_is_flags = 0; custom_RankNumber = 0; custom_NameHash = 0; custom_ThreatForSpell = 0; custom_ThreatForSpellCoef = 0; custom_spell_coef_flags = 0; custom_base_range_or_radius_sqr = 0; cone_width = 0; casttime_coef = 0; fixed_dddhcoef = 0; fixed_hotdotcoef = 0; Dspell_coef_override = 0; OTspell_coef_override = 0; ai_target_type = 0; custom_self_cast_only = false; custom_apply_on_shapeshift_change = false; custom_always_apply = false; custom_is_melee_spell = false; custom_is_ranged_spell = false; custom_SchoolMask = 0; SpellVisual = 0; field114 = 0; spellIconID = 0; activeIconID = 0; spellPriority = 0; Name = ""; Rank = ""; Description = ""; BuffDescription = ""; ManaCostPercentage = 0; StartRecoveryCategory = 0; StartRecoveryTime = 0; MaxTargetLevel = 0; SpellFamilyName = 0; MaxTargets = 0; Spell_Dmg_Type = 0; PreventionType = 0; StanceBarOrder = 0; MinFactionID = 0; MinReputation = 0; RequiredAuraVision = 0; RequiresAreaId = 0; School = 0; RuneCostID = 0; SpellDifficultyID = 0; custom_DiminishStatus = 0; targetAuraSpellNot = 0; CastingTimeIndex = 0; RecoveryTime = 0; CategoryRecoveryTime = 0; InterruptFlags = 0; AuraInterruptFlags = 0; ChannelInterruptFlags = 0; procFlags = 0; procChance = 0; procCharges = 0; maxLevel = 0; baseLevel = 0; spellLevel = 0; DurationIndex = 0; powerType = 0; manaCost = 0; manaCostPerlevel = 0; manaPerSecond = 0; manaPerSecondPerLevel = 0; rangeIndex = 0; speed = 0; modalNextSpell = 0; maxstack = 0; EquippedItemClass = 0; EquippedItemSubClass = 0; RequiredItemFlags = 0; } SpellInfo::~SpellInfo() {} bool SpellInfo::HasEffect(uint32 effect) { for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) if (Effect[i] == effect) return true; return false; } bool SpellInfo::HasCustomFlagForEffect(uint32 effect, uint32 flag) { if (effect >= MAX_SPELL_EFFECTS) return false; if ((EffectCustomFlag[effect] & flag) != 0) return true; else return false; } bool SpellInfo::IsPassive() { return Attributes & ATTRIBUTES_PASSIVE; } bool SpellInfo::IsProfession() { for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) { if (Effect[i] == SPELL_EFFECT_SKILL) { uint32 skill = EffectMiscValue[i]; //Profession skill if (skill == SKILL_FISHING || skill == SKILL_COOKING || skill == SKILL_FIRST_AID) return true; if (IsPrimaryProfessionSkill(skill)) return true; } } return false; } bool SpellInfo::IsPrimaryProfession() { for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) { if (Effect[i] == SPELL_EFFECT_SKILL) { uint32 skill = EffectMiscValue[i]; if (IsPrimaryProfessionSkill(skill)) return true; } } return false; } bool SpellInfo::IsPrimaryProfessionSkill(uint32 skill_id) { if (DBC::Structures::SkillLineEntry const* skill_line = sSkillLineStore.LookupEntry(skill_id)) if (skill_line && skill_line->type == SKILL_TYPE_PROFESSION) return true; return false; } bool SpellInfo::IsDeathPersistent() { return AttributesExC & ATTRIBUTESEXC_CAN_PERSIST_AND_CASTED_WHILE_DEAD; } bool SpellInfo::AppliesAreaAura(uint32 aura) { for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) { if ((Effect[i] == 6 || /// SPELL_EFFECT_APPLY_GROUP_AREA_AURA <-wrong Effect[i] == SPELL_EFFECT_PERSISTENT_AREA_AURA || Effect[i] == SPELL_EFFECT_APPLY_GROUP_AREA_AURA || Effect[i] == SPELL_EFFECT_APPLY_RAID_AREA_AURA || Effect[i] == SPELL_EFFECT_APPLY_PET_AREA_AURA || Effect[i] == SPELL_EFFECT_APPLY_FRIEND_AREA_AURA || Effect[i] == SPELL_EFFECT_APPLY_ENEMY_AREA_AURA || Effect[i] == SPELL_EFFECT_APPLY_OWNER_AREA_AURA) && EffectApplyAuraName[i] == aura) return true; } return false; } uint32 SpellInfo::GetAreaAuraEffectId() { for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) { if (Effect[i] == SPELL_EFFECT_APPLY_GROUP_AREA_AURA || Effect[i] == SPELL_EFFECT_APPLY_RAID_AREA_AURA || Effect[i] == SPELL_EFFECT_APPLY_PET_AREA_AURA || Effect[i] == SPELL_EFFECT_APPLY_FRIEND_AREA_AURA || Effect[i] == SPELL_EFFECT_APPLY_ENEMY_AREA_AURA || Effect[i] == SPELL_EFFECT_APPLY_OWNER_AREA_AURA) return Effect[i]; } return 0; } <commit_msg>Feedback from danko<commit_after>/* Copyright (c) 2014-2016 AscEmu Team <http://www.ascemu.org/> This file is released under the MIT license. See README-MIT for more information. */ #include "StdAfx.h" SpellInfo::SpellInfo() { Id = 0; Category = 0; DispelType = 0; MechanicsType = 0; Attributes = 0; AttributesEx = 0; AttributesExB = 0; AttributesExC = 0; AttributesExD = 0; AttributesExE = 0; AttributesExF = 0; AttributesExG = 0; RequiredShapeShift = 0; ShapeshiftExclude = 0; Targets = 0; TargetCreatureType = 0; RequiresSpellFocus = 0; FacingCasterFlags = 0; CasterAuraState = 0; TargetAuraState = 0; CasterAuraStateNot = 0; TargetAuraStateNot = 0; casterAuraSpell = 0; targetAuraSpell = 0; casterAuraSpellNot = 0; CustomFlags = 0; for (uint8 i = 0; i < MAX_SPELL_EFFECTS; i++) EffectCustomFlag[i] = 0; SpellFactoryFunc = NULL; AuraFactoryFunc = NULL; custom_proc_interval = 0; custom_BGR_one_buff_on_target = 0; custom_BGR_one_buff_from_caster_on_self = 0; custom_c_is_flags = 0; custom_RankNumber = 0; custom_NameHash = 0; custom_ThreatForSpell = 0; custom_ThreatForSpellCoef = 0; custom_spell_coef_flags = 0; custom_base_range_or_radius_sqr = 0; cone_width = 0; casttime_coef = 0; fixed_dddhcoef = 0; fixed_hotdotcoef = 0; Dspell_coef_override = 0; OTspell_coef_override = 0; ai_target_type = 0; custom_self_cast_only = false; custom_apply_on_shapeshift_change = false; custom_always_apply = false; custom_is_melee_spell = false; custom_is_ranged_spell = false; custom_SchoolMask = 0; SpellVisual = 0; field114 = 0; spellIconID = 0; activeIconID = 0; spellPriority = 0; Name = ""; Rank = ""; Description = ""; BuffDescription = ""; ManaCostPercentage = 0; StartRecoveryCategory = 0; StartRecoveryTime = 0; MaxTargetLevel = 0; SpellFamilyName = 0; MaxTargets = 0; Spell_Dmg_Type = 0; PreventionType = 0; StanceBarOrder = 0; MinFactionID = 0; MinReputation = 0; RequiredAuraVision = 0; RequiresAreaId = 0; School = 0; RuneCostID = 0; SpellDifficultyID = 0; custom_DiminishStatus = 0; targetAuraSpellNot = 0; CastingTimeIndex = 0; RecoveryTime = 0; CategoryRecoveryTime = 0; InterruptFlags = 0; AuraInterruptFlags = 0; ChannelInterruptFlags = 0; procFlags = 0; procChance = 0; procCharges = 0; maxLevel = 0; baseLevel = 0; spellLevel = 0; DurationIndex = 0; powerType = 0; manaCost = 0; manaCostPerlevel = 0; manaPerSecond = 0; manaPerSecondPerLevel = 0; rangeIndex = 0; speed = 0; modalNextSpell = 0; maxstack = 0; EquippedItemClass = 0; EquippedItemSubClass = 0; RequiredItemFlags = 0; } SpellInfo::~SpellInfo() {} bool SpellInfo::HasEffect(uint32 effect) { for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) if (Effect[i] == effect) return true; return false; } bool SpellInfo::HasCustomFlagForEffect(uint32 effect, uint32 flag) { if (effect >= MAX_SPELL_EFFECTS) return false; if ((EffectCustomFlag[effect] & flag) != 0) return true; else return false; } bool SpellInfo::IsPassive() { return Attributes & ATTRIBUTES_PASSIVE; } bool SpellInfo::IsProfession() { for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) { if (Effect[i] == SPELL_EFFECT_SKILL) { uint32 skill = EffectMiscValue[i]; //Profession skill if (skill == SKILL_FISHING || skill == SKILL_COOKING || skill == SKILL_FIRST_AID) return true; if (IsPrimaryProfessionSkill(skill)) return true; } } return false; } bool SpellInfo::IsPrimaryProfession() { for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) { if (Effect[i] == SPELL_EFFECT_SKILL) { uint32 skill = EffectMiscValue[i]; if (IsPrimaryProfessionSkill(skill)) return true; } } return false; } bool SpellInfo::IsPrimaryProfessionSkill(uint32 skill_id) { if (DBC::Structures::SkillLineEntry const* skill_line = sSkillLineStore.LookupEntry(skill_id)) if (skill_line && skill_line->type == SKILL_TYPE_PROFESSION) return true; return false; } bool SpellInfo::IsDeathPersistent() { return AttributesExC & ATTRIBUTESEXC_CAN_PERSIST_AND_CASTED_WHILE_DEAD; } bool SpellInfo::AppliesAreaAura(uint32 aura) { for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) { if ((Effect[i] == SPELL_EFFECT_PERSISTENT_AREA_AURA || Effect[i] == SPELL_EFFECT_APPLY_GROUP_AREA_AURA || Effect[i] == SPELL_EFFECT_APPLY_RAID_AREA_AURA || Effect[i] == SPELL_EFFECT_APPLY_PET_AREA_AURA || Effect[i] == SPELL_EFFECT_APPLY_FRIEND_AREA_AURA || Effect[i] == SPELL_EFFECT_APPLY_ENEMY_AREA_AURA || Effect[i] == SPELL_EFFECT_APPLY_OWNER_AREA_AURA) && EffectApplyAuraName[i] == aura) return true; } return false; } uint32 SpellInfo::GetAreaAuraEffectId() { for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) { if (Effect[i] == SPELL_EFFECT_APPLY_GROUP_AREA_AURA || Effect[i] == SPELL_EFFECT_APPLY_RAID_AREA_AURA || Effect[i] == SPELL_EFFECT_APPLY_PET_AREA_AURA || Effect[i] == SPELL_EFFECT_APPLY_FRIEND_AREA_AURA || Effect[i] == SPELL_EFFECT_APPLY_ENEMY_AREA_AURA || Effect[i] == SPELL_EFFECT_APPLY_OWNER_AREA_AURA) return Effect[i]; } return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2009-2017 The Regents of the University of Michigan // This file is part of the HOOMD-blue project, released under the BSD 3-Clause License. // Maintainer: joaander /*! \file NeighborListBinned.cc \brief Defines NeighborListBinned */ #include "NeighborListBinned.h" #ifdef ENABLE_MPI #include "hoomd/Communicator.h" #endif using namespace std; namespace py = pybind11; NeighborListBinned::NeighborListBinned(std::shared_ptr<SystemDefinition> sysdef, Scalar r_cut, Scalar r_buff, std::shared_ptr<CellList> cl) : NeighborList(sysdef, r_cut, r_buff), m_cl(cl) { m_exec_conf->msg->notice(5) << "Constructing NeighborListBinned" << endl; // create a default cell list if one was not specified if (!m_cl) m_cl = std::shared_ptr<CellList>(new CellList(sysdef)); m_cl->setRadius(1); m_cl->setComputeTDB(false); m_cl->setFlagIndex(); // call this class's special setRCut setRCut(r_cut, r_buff); } NeighborListBinned::~NeighborListBinned() { m_exec_conf->msg->notice(5) << "Destroying NeighborListBinned" << endl; } void NeighborListBinned::setRCut(Scalar r_cut, Scalar r_buff) { NeighborList::setRCut(r_cut, r_buff); Scalar rmax = getMaxRCut() + m_r_buff; if (m_diameter_shift) rmax += m_d_max - Scalar(1.0); m_cl->setNominalWidth(rmax); } void NeighborListBinned::setRCutPair(unsigned int typ1, unsigned int typ2, Scalar r_cut) { NeighborList::setRCutPair(typ1,typ2,r_cut); Scalar rmax = getMaxRCut() + m_r_buff; if (m_diameter_shift) rmax += m_d_max - Scalar(1.0); m_cl->setNominalWidth(rmax); } void NeighborListBinned::setMaximumDiameter(Scalar d_max) { NeighborList::setMaximumDiameter(d_max); // need to update the cell list settings appropriately Scalar rmax = getMaxRCut() + m_r_buff; if (m_diameter_shift) rmax += m_d_max - Scalar(1.0); m_cl->setNominalWidth(rmax); } void NeighborListBinned::buildNlist(unsigned int timestep) { m_cl->compute(timestep); uint3 dim = m_cl->getDim(); Scalar3 ghost_width = m_cl->getGhostWidth(); if (m_prof) m_prof->push(m_exec_conf, "compute"); // acquire the particle data and box dimension ArrayHandle<Scalar4> h_pos(m_pdata->getPositions(), access_location::host, access_mode::read); ArrayHandle<unsigned int> h_body(m_pdata->getBodies(), access_location::host, access_mode::read); ArrayHandle<Scalar> h_diameter(m_pdata->getDiameters(), access_location::host, access_mode::read); ArrayHandle<int3> h_image(m_pdata->getImages(), access_location::host, access_mode::read); const BoxDim& box = m_pdata->getBox(); Scalar3 nearest_plane_distance = box.getNearestPlaneDistance(); // validate that the cutoff fits inside the box Scalar rmax = getMaxRCut() + m_r_buff; if (m_diameter_shift) rmax += m_d_max - Scalar(1.0); if (m_filter_body) { // add the maximum diameter of all composite particles Scalar max_d_comp = m_pdata->getMaxCompositeParticleDiameter(); rmax += 0.5*max_d_comp; } if ((box.getPeriodic().x && nearest_plane_distance.x <= rmax * 2.0) || (box.getPeriodic().y && nearest_plane_distance.y <= rmax * 2.0) || (this->m_sysdef->getNDimensions() == 3 && box.getPeriodic().z && nearest_plane_distance.z <= rmax * 2.0)) { m_exec_conf->msg->error() << "nlist: Simulation box is too small! Particles would be interacting with themselves." << endl; throw runtime_error("Error updating neighborlist bins"); } // access the rlist data ArrayHandle<Scalar> h_r_cut(m_r_cut, access_location::host, access_mode::read); ArrayHandle<Scalar> h_r_listsq(m_r_listsq, access_location::host, access_mode::read); // access the cell list data arrays ArrayHandle<unsigned int> h_cell_size(m_cl->getCellSizeArray(), access_location::host, access_mode::read); ArrayHandle<Scalar4> h_cell_xyzf(m_cl->getXYZFArray(), access_location::host, access_mode::read); ArrayHandle<unsigned int> h_cell_adj(m_cl->getCellAdjArray(), access_location::host, access_mode::read); // access the neighbor list data ArrayHandle<unsigned int> h_head_list(m_head_list, access_location::host, access_mode::read); ArrayHandle<unsigned int> h_Nmax(m_Nmax, access_location::host, access_mode::read); ArrayHandle<unsigned int> h_conditions(m_conditions, access_location::host, access_mode::readwrite); ArrayHandle<unsigned int> h_nlist(m_nlist, access_location::host, access_mode::overwrite); ArrayHandle<unsigned int> h_n_neigh(m_n_neigh, access_location::host, access_mode::overwrite); // access indexers Index3D ci = m_cl->getCellIndexer(); Index2D cli = m_cl->getCellListIndexer(); Index2D cadji = m_cl->getCellAdjIndexer(); // get periodic flags uchar3 periodic = box.getPeriodic(); // for each local particle unsigned int nparticles = m_pdata->getN(); for (int i = 0; i < (int)nparticles; i++) { unsigned int cur_n_neigh = 0; const Scalar3 my_pos = make_scalar3(h_pos.data[i].x, h_pos.data[i].y, h_pos.data[i].z); const unsigned int type_i = __scalar_as_int(h_pos.data[i].w); const unsigned int body_i = h_body.data[i]; const Scalar diam_i = h_diameter.data[i]; const unsigned int Nmax_i = h_Nmax.data[type_i]; const unsigned int head_idx_i = h_head_list.data[i]; // find the bin each particle belongs in Scalar3 f = box.makeFraction(my_pos,ghost_width); int ib = (unsigned int)(f.x * dim.x); int jb = (unsigned int)(f.y * dim.y); int kb = (unsigned int)(f.z * dim.z); // need to handle the case where the particle is exactly at the box hi if (ib == (int)dim.x && periodic.x) ib = 0; if (jb == (int)dim.y && periodic.y) jb = 0; if (kb == (int)dim.z && periodic.z) kb = 0; // identify the bin unsigned int my_cell = ci(ib,jb,kb); // loop through all neighboring bins for (unsigned int cur_adj = 0; cur_adj < cadji.getW(); cur_adj++) { unsigned int neigh_cell = h_cell_adj.data[cadji(cur_adj, my_cell)]; // check against all the particles in that neighboring bin to see if it is a neighbor unsigned int size = h_cell_size.data[neigh_cell]; for (unsigned int cur_offset = 0; cur_offset < size; cur_offset++) { Scalar4& cur_xyzf = h_cell_xyzf.data[cli(cur_offset, neigh_cell)]; unsigned int cur_neigh = __scalar_as_int(cur_xyzf.w); // get the current neighbor type from the position data (will use tdb on the GPU) unsigned int cur_neigh_type = __scalar_as_int(h_pos.data[cur_neigh].w); Scalar r_cut = h_r_cut.data[m_typpair_idx(type_i,cur_neigh_type)]; // automatically exclude particles without a distance check when: // (1) they are the same particle, or // (2) the r_cut(i,j) indicates to skip, or // (3) they are in the same body bool excluded = ((i == (int)cur_neigh) || (r_cut <= Scalar(0.0))); Scalar3 neigh_pos = make_scalar3(cur_xyzf.x, cur_xyzf.y, cur_xyzf.z); Scalar3 dx = my_pos - neigh_pos; dx = box.minImage(dx); if (m_filter_body && body_i != NO_BODY && body_i == h_body.data[cur_neigh]) { Scalar3 rtest = my_pos - dx; int3 test_img = h_image.data[i]; int3 img_j = h_image.data[cur_neigh]; box.wrap(rtest, test_img); // if the images match, then it is the particle in the same image of the body // so it should be excluded excluded |= (test_img == img_j); } if (excluded) continue; Scalar r_list = r_cut + m_r_buff; Scalar sqshift = Scalar(0.0); if (m_diameter_shift) { const Scalar delta = (diam_i + h_diameter.data[cur_neigh]) * Scalar(0.5) - Scalar(1.0); // r^2 < (r_list + delta)^2 // r^2 < r_listsq + delta^2 + 2*r_list*delta sqshift = (delta + Scalar(2.0) * r_list) * delta; } Scalar dr_sq = dot(dx,dx); // move the squared rlist by the diameter shift if necessary Scalar r_listsq = h_r_listsq.data[m_typpair_idx(type_i,cur_neigh_type)]; if (dr_sq <= (r_listsq + sqshift) && !excluded) { if (m_storage_mode == full || i < (int)cur_neigh) { // local neighbor if (cur_n_neigh < Nmax_i) { h_nlist.data[head_idx_i + cur_n_neigh] = cur_neigh; } else h_conditions.data[type_i] = max(h_conditions.data[type_i], cur_n_neigh+1); cur_n_neigh++; } } } } h_n_neigh.data[i] = cur_n_neigh; } if (m_prof) m_prof->pop(m_exec_conf); } void export_NeighborListBinned(py::module& m) { py::class_<NeighborListBinned, std::shared_ptr<NeighborListBinned> >(m, "NeighborListBinned", py::base<NeighborList>()) .def(py::init< std::shared_ptr<SystemDefinition>, Scalar, Scalar, std::shared_ptr<CellList> >()) ; } <commit_msg>Revert "implement self interaction check in NeighborListBinned base class"<commit_after>// Copyright (c) 2009-2017 The Regents of the University of Michigan // This file is part of the HOOMD-blue project, released under the BSD 3-Clause License. // Maintainer: joaander /*! \file NeighborListBinned.cc \brief Defines NeighborListBinned */ #include "NeighborListBinned.h" #ifdef ENABLE_MPI #include "hoomd/Communicator.h" #endif using namespace std; namespace py = pybind11; NeighborListBinned::NeighborListBinned(std::shared_ptr<SystemDefinition> sysdef, Scalar r_cut, Scalar r_buff, std::shared_ptr<CellList> cl) : NeighborList(sysdef, r_cut, r_buff), m_cl(cl) { m_exec_conf->msg->notice(5) << "Constructing NeighborListBinned" << endl; // create a default cell list if one was not specified if (!m_cl) m_cl = std::shared_ptr<CellList>(new CellList(sysdef)); m_cl->setRadius(1); m_cl->setComputeTDB(false); m_cl->setFlagIndex(); // call this class's special setRCut setRCut(r_cut, r_buff); } NeighborListBinned::~NeighborListBinned() { m_exec_conf->msg->notice(5) << "Destroying NeighborListBinned" << endl; } void NeighborListBinned::setRCut(Scalar r_cut, Scalar r_buff) { NeighborList::setRCut(r_cut, r_buff); Scalar rmax = getMaxRCut() + m_r_buff; if (m_diameter_shift) rmax += m_d_max - Scalar(1.0); m_cl->setNominalWidth(rmax); } void NeighborListBinned::setRCutPair(unsigned int typ1, unsigned int typ2, Scalar r_cut) { NeighborList::setRCutPair(typ1,typ2,r_cut); Scalar rmax = getMaxRCut() + m_r_buff; if (m_diameter_shift) rmax += m_d_max - Scalar(1.0); m_cl->setNominalWidth(rmax); } void NeighborListBinned::setMaximumDiameter(Scalar d_max) { NeighborList::setMaximumDiameter(d_max); // need to update the cell list settings appropriately Scalar rmax = getMaxRCut() + m_r_buff; if (m_diameter_shift) rmax += m_d_max - Scalar(1.0); m_cl->setNominalWidth(rmax); } void NeighborListBinned::buildNlist(unsigned int timestep) { m_cl->compute(timestep); uint3 dim = m_cl->getDim(); Scalar3 ghost_width = m_cl->getGhostWidth(); if (m_prof) m_prof->push(m_exec_conf, "compute"); // acquire the particle data and box dimension ArrayHandle<Scalar4> h_pos(m_pdata->getPositions(), access_location::host, access_mode::read); ArrayHandle<unsigned int> h_body(m_pdata->getBodies(), access_location::host, access_mode::read); ArrayHandle<Scalar> h_diameter(m_pdata->getDiameters(), access_location::host, access_mode::read); const BoxDim& box = m_pdata->getBox(); Scalar3 nearest_plane_distance = box.getNearestPlaneDistance(); // validate that the cutoff fits inside the box Scalar rmax = getMaxRCut() + m_r_buff; if (m_diameter_shift) rmax += m_d_max - Scalar(1.0); if (m_filter_body) { // add the maximum diameter of all composite particles Scalar max_d_comp = m_pdata->getMaxCompositeParticleDiameter(); rmax += 0.5*max_d_comp; } if ((box.getPeriodic().x && nearest_plane_distance.x <= rmax * 2.0) || (box.getPeriodic().y && nearest_plane_distance.y <= rmax * 2.0) || (this->m_sysdef->getNDimensions() == 3 && box.getPeriodic().z && nearest_plane_distance.z <= rmax * 2.0)) { m_exec_conf->msg->error() << "nlist: Simulation box is too small! Particles would be interacting with themselves." << endl; throw runtime_error("Error updating neighborlist bins"); } // access the rlist data ArrayHandle<Scalar> h_r_cut(m_r_cut, access_location::host, access_mode::read); ArrayHandle<Scalar> h_r_listsq(m_r_listsq, access_location::host, access_mode::read); // access the cell list data arrays ArrayHandle<unsigned int> h_cell_size(m_cl->getCellSizeArray(), access_location::host, access_mode::read); ArrayHandle<Scalar4> h_cell_xyzf(m_cl->getXYZFArray(), access_location::host, access_mode::read); ArrayHandle<unsigned int> h_cell_adj(m_cl->getCellAdjArray(), access_location::host, access_mode::read); // access the neighbor list data ArrayHandle<unsigned int> h_head_list(m_head_list, access_location::host, access_mode::read); ArrayHandle<unsigned int> h_Nmax(m_Nmax, access_location::host, access_mode::read); ArrayHandle<unsigned int> h_conditions(m_conditions, access_location::host, access_mode::readwrite); ArrayHandle<unsigned int> h_nlist(m_nlist, access_location::host, access_mode::overwrite); ArrayHandle<unsigned int> h_n_neigh(m_n_neigh, access_location::host, access_mode::overwrite); // access indexers Index3D ci = m_cl->getCellIndexer(); Index2D cli = m_cl->getCellListIndexer(); Index2D cadji = m_cl->getCellAdjIndexer(); // get periodic flags uchar3 periodic = box.getPeriodic(); // for each local particle unsigned int nparticles = m_pdata->getN(); for (int i = 0; i < (int)nparticles; i++) { unsigned int cur_n_neigh = 0; const Scalar3 my_pos = make_scalar3(h_pos.data[i].x, h_pos.data[i].y, h_pos.data[i].z); const unsigned int type_i = __scalar_as_int(h_pos.data[i].w); const unsigned int body_i = h_body.data[i]; const Scalar diam_i = h_diameter.data[i]; const unsigned int Nmax_i = h_Nmax.data[type_i]; const unsigned int head_idx_i = h_head_list.data[i]; // find the bin each particle belongs in Scalar3 f = box.makeFraction(my_pos,ghost_width); int ib = (unsigned int)(f.x * dim.x); int jb = (unsigned int)(f.y * dim.y); int kb = (unsigned int)(f.z * dim.z); // need to handle the case where the particle is exactly at the box hi if (ib == (int)dim.x && periodic.x) ib = 0; if (jb == (int)dim.y && periodic.y) jb = 0; if (kb == (int)dim.z && periodic.z) kb = 0; // identify the bin unsigned int my_cell = ci(ib,jb,kb); // loop through all neighboring bins for (unsigned int cur_adj = 0; cur_adj < cadji.getW(); cur_adj++) { unsigned int neigh_cell = h_cell_adj.data[cadji(cur_adj, my_cell)]; // check against all the particles in that neighboring bin to see if it is a neighbor unsigned int size = h_cell_size.data[neigh_cell]; for (unsigned int cur_offset = 0; cur_offset < size; cur_offset++) { Scalar4& cur_xyzf = h_cell_xyzf.data[cli(cur_offset, neigh_cell)]; unsigned int cur_neigh = __scalar_as_int(cur_xyzf.w); // get the current neighbor type from the position data (will use tdb on the GPU) unsigned int cur_neigh_type = __scalar_as_int(h_pos.data[cur_neigh].w); Scalar r_cut = h_r_cut.data[m_typpair_idx(type_i,cur_neigh_type)]; // automatically exclude particles without a distance check when: // (1) they are the same particle, or // (2) the r_cut(i,j) indicates to skip, or // (3) they are in the same body bool excluded = ((i == (int)cur_neigh) || (r_cut <= Scalar(0.0))); if (m_filter_body && body_i != NO_BODY) excluded = excluded | (body_i == h_body.data[cur_neigh]); if (excluded) continue; Scalar3 neigh_pos = make_scalar3(cur_xyzf.x, cur_xyzf.y, cur_xyzf.z); Scalar3 dx = my_pos - neigh_pos; dx = box.minImage(dx); Scalar r_list = r_cut + m_r_buff; Scalar sqshift = Scalar(0.0); if (m_diameter_shift) { const Scalar delta = (diam_i + h_diameter.data[cur_neigh]) * Scalar(0.5) - Scalar(1.0); // r^2 < (r_list + delta)^2 // r^2 < r_listsq + delta^2 + 2*r_list*delta sqshift = (delta + Scalar(2.0) * r_list) * delta; } Scalar dr_sq = dot(dx,dx); // move the squared rlist by the diameter shift if necessary Scalar r_listsq = h_r_listsq.data[m_typpair_idx(type_i,cur_neigh_type)]; if (dr_sq <= (r_listsq + sqshift) && !excluded) { if (m_storage_mode == full || i < (int)cur_neigh) { // local neighbor if (cur_n_neigh < Nmax_i) { h_nlist.data[head_idx_i + cur_n_neigh] = cur_neigh; } else h_conditions.data[type_i] = max(h_conditions.data[type_i], cur_n_neigh+1); cur_n_neigh++; } } } } h_n_neigh.data[i] = cur_n_neigh; } if (m_prof) m_prof->pop(m_exec_conf); } void export_NeighborListBinned(py::module& m) { py::class_<NeighborListBinned, std::shared_ptr<NeighborListBinned> >(m, "NeighborListBinned", py::base<NeighborList>()) .def(py::init< std::shared_ptr<SystemDefinition>, Scalar, Scalar, std::shared_ptr<CellList> >()) ; } <|endoftext|>
<commit_before>/* _____ * /\ _ \ __ * \ \ \_\ \ __ __ __ /\_\ * \ \ __ \ /'_ `\ /\ \/\ \\/\ \ * \ \ \/\ \ /\ \_\ \\ \ \_\ \\ \ \ * \ \_\ \_\\ \____ \\ \____/ \ \_\ * \/_/\/_/ \/____\ \\/___/ \/_/ * /\____/ * \_/__/ * * Copyright (c) 2011 Joshua Larouche * * * License: (BSD) * 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 Agui 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 "Agui/Widgets/ToolTip/ToolTip.hpp" namespace agui { ToolTip::ToolTip() : align(ALIGN_TOP_LEFT), invoker(NULL) { resizableText.setSingleLine(false); setVisibility(false); setFocusable(false); setTabable(false); setPreferredOffset(Point(10,10)); } void ToolTip::mouseClick( MouseEvent &mouseEvent ) { if(mouseEvent.getButton() == MOUSE_BUTTON_LEFT) dispatchActionEvent(ActionEvent(this)); } void ToolTip::showToolTip( const std::string& text, int width, int x, int y, Widget* invoker ) { this->invoker = invoker; setLocation(x,y); int w = width <= 0 ? 1000 : width; resizableText.makeTextLines(getFont(),text,wrappedText,w); int newHeight = wrappedText.size() * getFont()->getLineHeight(); int newWidth = w; int widestLine = -1; for(size_t i = 0; i < wrappedText.size(); ++i) { int curWidth = getFont()->getTextWidth(wrappedText[i]); if(curWidth > widestLine) { widestLine = curWidth; } } if(widestLine < width) newWidth = widestLine; newWidth += (getMargin(SIDE_LEFT) + getMargin(SIDE_RIGHT)); newHeight += (getMargin(SIDE_TOP) + getMargin(SIDE_BOTTOM)); setSize(newWidth,newHeight); setVisibility(true); } const std::vector<std::string>& ToolTip::getAreaText() const { return wrappedText; } void ToolTip::paintBackground( const PaintEvent &paintEvent ) { paintEvent.graphics()->drawFilledRectangle( getSizeRectangle(),getBackColor()); } void ToolTip::paintComponent( const PaintEvent &paintEvent ) { resizableText.drawTextArea( paintEvent.graphics(),getFont(),getInnerRectangle(), getFontColor(),getAreaText(),align); } void ToolTip::setTextAlignment( AreaAlignmentEnum alignment ) { align = alignment; } agui::AreaAlignmentEnum ToolTip::getTextAlignment() const { return align; } void ToolTip::hideToolTip() { setVisibility(false); invoker = NULL; } void ToolTip::setPreferredOffset( Point offset ) { preferredOffset = offset; } Point ToolTip::getPreferredOffset() const { return preferredOffset; } Widget* ToolTip::getInvoker() const { return invoker; } } <commit_msg>Added border around the tooltip widget, it looks better this way.<commit_after>/* _____ * /\ _ \ __ * \ \ \_\ \ __ __ __ /\_\ * \ \ __ \ /'_ `\ /\ \/\ \\/\ \ * \ \ \/\ \ /\ \_\ \\ \ \_\ \\ \ \ * \ \_\ \_\\ \____ \\ \____/ \ \_\ * \/_/\/_/ \/____\ \\/___/ \/_/ * /\____/ * \_/__/ * * Copyright (c) 2011 Joshua Larouche * * * License: (BSD) * 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 Agui 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 "Agui/Widgets/ToolTip/ToolTip.hpp" namespace agui { ToolTip::ToolTip() : align(ALIGN_TOP_LEFT), invoker(NULL) { resizableText.setSingleLine(false); setVisibility(false); setFocusable(false); setTabable(false); setPreferredOffset(Point(10,10)); } void ToolTip::mouseClick( MouseEvent &mouseEvent ) { if(mouseEvent.getButton() == MOUSE_BUTTON_LEFT) dispatchActionEvent(ActionEvent(this)); } void ToolTip::showToolTip( const std::string& text, int width, int x, int y, Widget* invoker ) { this->invoker = invoker; setLocation(x,y); int w = width <= 0 ? 1000 : width; resizableText.makeTextLines(getFont(),text,wrappedText,w); int newHeight = wrappedText.size() * getFont()->getLineHeight(); int newWidth = w; int widestLine = -1; for(size_t i = 0; i < wrappedText.size(); ++i) { int curWidth = getFont()->getTextWidth(wrappedText[i]); if(curWidth > widestLine) { widestLine = curWidth; } } if(widestLine < width) newWidth = widestLine; newWidth += (getMargin(SIDE_LEFT) + getMargin(SIDE_RIGHT)); newHeight += (getMargin(SIDE_TOP) + getMargin(SIDE_BOTTOM)); setSize(newWidth,newHeight); setVisibility(true); } const std::vector<std::string>& ToolTip::getAreaText() const { return wrappedText; } void ToolTip::paintBackground( const PaintEvent &paintEvent ) { paintEvent.graphics()->drawFilledRectangle( getSizeRectangle(),getBackColor()); paintEvent.graphics()->drawRectangle(getSizeRectangle(), getFontColor()); } void ToolTip::paintComponent( const PaintEvent &paintEvent ) { resizableText.drawTextArea( paintEvent.graphics(),getFont(),getInnerRectangle(), getFontColor(),getAreaText(),align); } void ToolTip::setTextAlignment( AreaAlignmentEnum alignment ) { align = alignment; } agui::AreaAlignmentEnum ToolTip::getTextAlignment() const { return align; } void ToolTip::hideToolTip() { setVisibility(false); invoker = NULL; } void ToolTip::setPreferredOffset( Point offset ) { preferredOffset = offset; } Point ToolTip::getPreferredOffset() const { return preferredOffset; } Widget* ToolTip::getInvoker() const { return invoker; } } <|endoftext|>
<commit_before>/* * Copyright (C) 2009 Marc Boris Duerner, Tommi Maekitalo * * 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. * * As a special exception, you may use this file as part of a free * software library without restriction. Specifically, if other files * instantiate templates or use macros or inline functions from this * file, or you compile this file and link it with other files to * produce an executable, this file does not by itself cause the * resulting executable to be covered by the GNU General Public * License. This exception does not however invalidate any other * reasons why the executable file might be covered by the GNU Library * General Public License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "config.h" #ifdef HAVE_ACCEPT4 #include <sys/types.h> #include <sys/socket.h> #endif #include "tcpsocketimpl.h" #include "tcpserverimpl.h" #include "cxxtools/net/tcpserver.h" #include "cxxtools/net/tcpsocket.h" #include "cxxtools/systemerror.h" #include "cxxtools/ioerror.h" #include "cxxtools/log.h" #include "config.h" #include "error.h" #include <cerrno> #include <cstring> #include <cassert> #include <fcntl.h> #include <string.h> #include <netinet/in.h> #include <arpa/inet.h> log_define("cxxtools.net.tcpsocket.impl") namespace cxxtools { namespace net { void formatIp(const sockaddr_in& sa, std::string& str) { #ifdef HAVE_INET_NTOP char strbuf[INET6_ADDRSTRLEN + 1]; const char* p = inet_ntop(sa.sin_family, &sa.sin_addr, strbuf, sizeof(strbuf)); str = (p == 0 ? "-" : strbuf); #else static cxxtools::Mutex monitor; cxxtools::MutexLock lock(monitor); const char* p = inet_ntoa(sa.sin_addr); if (p) str = p; else str.clear(); #endif } std::string getSockAddr(int fd) { union { struct sockaddr_storage storage; struct sockaddr sa; struct sockaddr_in sa_in; struct sockaddr_in6 sa_in6; struct in_addr addr; } addr; socklen_t slen = sizeof(addr); if (::getsockname(fd, &addr.sa, &slen) < 0) throw SystemError("getsockname"); std::string ret; formatIp(addr.sa_in, ret); return ret; } TcpSocketImpl::TcpSocketImpl(TcpSocket& socket) : IODeviceImpl(socket) , _socket(socket) , _isConnected(false) { } TcpSocketImpl::~TcpSocketImpl() { assert(_pfd == 0); } void TcpSocketImpl::close() { log_debug("close socket " << _fd); IODeviceImpl::close(); _isConnected = false; } std::string TcpSocketImpl::getSockAddr() const { return net::getSockAddr(fd()); } std::string TcpSocketImpl::getPeerAddr() const { union { struct sockaddr_storage storage; struct sockaddr sa; struct sockaddr_in sa_in; struct sockaddr_in6 sa_in6; struct in_addr addr; } addr; addr.storage = _peeraddr; std::string ret; formatIp(addr.sa_in, ret); return ret; } void TcpSocketImpl::connect(const AddrInfo& addrInfo) { log_debug("connect"); this->beginConnect(addrInfo); this->endConnect(); } int TcpSocketImpl::checkConnect() { log_trace("checkConnect"); int sockerr; socklen_t optlen = sizeof(sockerr); // check for socket error if( ::getsockopt(this->fd(), SOL_SOCKET, SO_ERROR, &sockerr, &optlen) != 0 ) { // getsockopt failed int e = errno; close(); throw SystemError(e, "getsockopt"); } if (sockerr == 0) { log_debug("connected successfully to " << getPeerAddr()); _isConnected = true; } return sockerr; } void TcpSocketImpl::checkPendingError() { if (_connectResult.second) { std::pair<int, const char*> p = _connectResult; _connectResult = std::pair<int, const char*>(0, 0); if (p.first) { throw IOError(getErrnoString(p.first, p.second).c_str()); } else { throw IOError("invalid address information"); } } } std::pair<int, const char*> TcpSocketImpl::tryConnect() { log_trace("tryConnect"); assert(_fd == -1); if (_addrInfoPtr == _addrInfo.impl()->end()) { log_debug("no more address informations"); return std::pair<int, const char*>(0, "invalid address information"); } while (true) { int fd; while (true) { log_debug("create socket"); fd = ::socket(_addrInfoPtr->ai_family, SOCK_STREAM, 0); if (fd >= 0) break; if (++_addrInfoPtr == _addrInfo.impl()->end()) return std::pair<int, const char*>(errno, "socket"); } IODeviceImpl::open(fd, true, false); std::memmove(&_peeraddr, _addrInfoPtr->ai_addr, _addrInfoPtr->ai_addrlen); log_debug("created socket " << _fd << " max: " << FD_SETSIZE); if( ::connect(this->fd(), _addrInfoPtr->ai_addr, _addrInfoPtr->ai_addrlen) == 0 ) { _isConnected = true; log_debug("connected successfully to " << getPeerAddr()); break; } if (errno == EINPROGRESS) { log_debug("connect in progress"); break; } close(); if (++_addrInfoPtr == _addrInfo.impl()->end()) return std::pair<int, const char*>(errno, "connect"); } return std::pair<int, const char*>(0, 0); } bool TcpSocketImpl::beginConnect(const AddrInfo& addrInfo) { log_trace("begin connect"); assert(!_isConnected); _addrInfo = addrInfo; _addrInfoPtr = _addrInfo.impl()->begin(); _connectResult = tryConnect(); checkPendingError(); return _isConnected; } void TcpSocketImpl::endConnect() { log_trace("ending connect"); if(_pfd && ! _socket.wbuf()) { _pfd->events &= ~POLLOUT; } checkPendingError(); if( _isConnected ) return; try { while (true) { pollfd pfd; pfd.fd = this->fd(); pfd.revents = 0; pfd.events = POLLOUT; log_debug("wait " << timeout() << " ms"); bool avail = this->wait(this->timeout(), pfd); if (avail) { // something has happened int sockerr = checkConnect(); if (_isConnected) return; if (++_addrInfoPtr == _addrInfo.impl()->end()) { // no more addrInfo - propagate error throw IOError(getErrnoString(sockerr, "connect").c_str()); } } else if (++_addrInfoPtr == _addrInfo.impl()->end()) { log_debug("timeout"); throw IOTimeout(); } close(); _connectResult = tryConnect(); if (_isConnected) return; checkPendingError(); } } catch(...) { close(); throw; } } void TcpSocketImpl::accept(const TcpServer& server, unsigned flags) { socklen_t peeraddr_len = sizeof(_peeraddr); _fd = server.impl().accept(flags, reinterpret_cast <struct sockaddr*>(&_peeraddr), peeraddr_len); if( _fd < 0 ) throw SystemError("accept"); #ifdef HAVE_ACCEPT4 IODeviceImpl::open(_fd, false, false); #else bool inherit = (flags & TcpSocket::INHERIT) != 0; IODeviceImpl::open(_fd, true, inherit); #endif //TODO ECONNABORTED EINTR EPERM _isConnected = true; log_debug( "accepted from " << getPeerAddr()); } void TcpSocketImpl::initWait(pollfd& pfd) { IODeviceImpl::initWait(pfd); if( ! _isConnected ) { log_debug("not connected, setting POLLOUT "); pfd.events = POLLOUT; } } bool TcpSocketImpl::checkPollEvent(pollfd& pfd) { log_debug("checkPollEvent " << pfd.revents); if( _isConnected ) { if ( pfd.revents & POLLERR ) { _device.close(); _socket.closed(_socket); return true; } return IODeviceImpl::checkPollEvent(pfd); } if ( pfd.revents & POLLERR ) { AddrInfoImpl::const_iterator ptr = _addrInfoPtr; if (++ptr == _addrInfo.impl()->end()) { // not really connected but error // end of addrinfo list means that no working addrinfo was found log_debug("no more addrinfos found"); _socket.connected(_socket); return true; } else { _addrInfoPtr = ptr; close(); _connectResult = tryConnect(); if (_isConnected || _connectResult.second) { // immediate success or error log_debug("connected successfully"); _socket.connected(_socket); } else { // by closing the previous file handle _pfd is set to 0. // creating a new socket in tryConnect may also change the value of fd. initializePoll(&pfd, 1); } return _isConnected; } } else if( pfd.revents & POLLOUT ) { int sockerr = checkConnect(); if (_isConnected) { _socket.connected(_socket); return true; } // something went wrong - look for next addrInfo log_debug("sockerr is " << sockerr << " try next"); if (++_addrInfoPtr == _addrInfo.impl()->end()) { // no more addrInfo - propagate error _connectResult = std::pair<int, const char*>(sockerr, "connect"); _socket.connected(_socket); return true; } _connectResult = tryConnect(); if (_isConnected) { _socket.connected(_socket); return true; } } return false; } } // namespace net } // namespace cxxtools <commit_msg>fix handling of closed sockets<commit_after>/* * Copyright (C) 2009 Marc Boris Duerner, Tommi Maekitalo * * 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. * * As a special exception, you may use this file as part of a free * software library without restriction. Specifically, if other files * instantiate templates or use macros or inline functions from this * file, or you compile this file and link it with other files to * produce an executable, this file does not by itself cause the * resulting executable to be covered by the GNU General Public * License. This exception does not however invalidate any other * reasons why the executable file might be covered by the GNU Library * General Public License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "config.h" #ifdef HAVE_ACCEPT4 #include <sys/types.h> #include <sys/socket.h> #endif #include "tcpsocketimpl.h" #include "tcpserverimpl.h" #include "cxxtools/net/tcpserver.h" #include "cxxtools/net/tcpsocket.h" #include "cxxtools/systemerror.h" #include "cxxtools/ioerror.h" #include "cxxtools/log.h" #include "config.h" #include "error.h" #include <cerrno> #include <cstring> #include <cassert> #include <fcntl.h> #include <string.h> #include <netinet/in.h> #include <arpa/inet.h> log_define("cxxtools.net.tcpsocket.impl") namespace cxxtools { namespace net { void formatIp(const sockaddr_in& sa, std::string& str) { #ifdef HAVE_INET_NTOP char strbuf[INET6_ADDRSTRLEN + 1]; const char* p = inet_ntop(sa.sin_family, &sa.sin_addr, strbuf, sizeof(strbuf)); str = (p == 0 ? "-" : strbuf); #else static cxxtools::Mutex monitor; cxxtools::MutexLock lock(monitor); const char* p = inet_ntoa(sa.sin_addr); if (p) str = p; else str.clear(); #endif } std::string getSockAddr(int fd) { union { struct sockaddr_storage storage; struct sockaddr sa; struct sockaddr_in sa_in; struct sockaddr_in6 sa_in6; struct in_addr addr; } addr; socklen_t slen = sizeof(addr); if (::getsockname(fd, &addr.sa, &slen) < 0) throw SystemError("getsockname"); std::string ret; formatIp(addr.sa_in, ret); return ret; } TcpSocketImpl::TcpSocketImpl(TcpSocket& socket) : IODeviceImpl(socket) , _socket(socket) , _isConnected(false) { } TcpSocketImpl::~TcpSocketImpl() { assert(_pfd == 0); } void TcpSocketImpl::close() { log_debug("close socket " << _fd); IODeviceImpl::close(); _isConnected = false; } std::string TcpSocketImpl::getSockAddr() const { return net::getSockAddr(fd()); } std::string TcpSocketImpl::getPeerAddr() const { union { struct sockaddr_storage storage; struct sockaddr sa; struct sockaddr_in sa_in; struct sockaddr_in6 sa_in6; struct in_addr addr; } addr; addr.storage = _peeraddr; std::string ret; formatIp(addr.sa_in, ret); return ret; } void TcpSocketImpl::connect(const AddrInfo& addrInfo) { log_debug("connect"); this->beginConnect(addrInfo); this->endConnect(); } int TcpSocketImpl::checkConnect() { log_trace("checkConnect"); int sockerr; socklen_t optlen = sizeof(sockerr); // check for socket error if( ::getsockopt(this->fd(), SOL_SOCKET, SO_ERROR, &sockerr, &optlen) != 0 ) { // getsockopt failed int e = errno; close(); throw SystemError(e, "getsockopt"); } if (sockerr == 0) { log_debug("connected successfully to " << getPeerAddr()); _isConnected = true; } return sockerr; } void TcpSocketImpl::checkPendingError() { if (_connectResult.second) { std::pair<int, const char*> p = _connectResult; _connectResult = std::pair<int, const char*>(0, 0); if (p.first) { throw IOError(getErrnoString(p.first, p.second).c_str()); } else { throw IOError("invalid address information"); } } } std::pair<int, const char*> TcpSocketImpl::tryConnect() { log_trace("tryConnect"); assert(_fd == -1); if (_addrInfoPtr == _addrInfo.impl()->end()) { log_debug("no more address informations"); return std::pair<int, const char*>(0, "invalid address information"); } while (true) { int fd; while (true) { log_debug("create socket"); fd = ::socket(_addrInfoPtr->ai_family, SOCK_STREAM, 0); if (fd >= 0) break; if (++_addrInfoPtr == _addrInfo.impl()->end()) return std::pair<int, const char*>(errno, "socket"); } IODeviceImpl::open(fd, true, false); std::memmove(&_peeraddr, _addrInfoPtr->ai_addr, _addrInfoPtr->ai_addrlen); log_debug("created socket " << _fd << " max: " << FD_SETSIZE); if( ::connect(this->fd(), _addrInfoPtr->ai_addr, _addrInfoPtr->ai_addrlen) == 0 ) { _isConnected = true; log_debug("connected successfully to " << getPeerAddr()); break; } if (errno == EINPROGRESS) { log_debug("connect in progress"); break; } close(); if (++_addrInfoPtr == _addrInfo.impl()->end()) return std::pair<int, const char*>(errno, "connect"); } return std::pair<int, const char*>(0, 0); } bool TcpSocketImpl::beginConnect(const AddrInfo& addrInfo) { log_trace("begin connect"); assert(!_isConnected); _addrInfo = addrInfo; _addrInfoPtr = _addrInfo.impl()->begin(); _connectResult = tryConnect(); checkPendingError(); return _isConnected; } void TcpSocketImpl::endConnect() { log_trace("ending connect"); if(_pfd && ! _socket.wbuf()) { _pfd->events &= ~POLLOUT; } checkPendingError(); if( _isConnected ) return; try { while (true) { pollfd pfd; pfd.fd = this->fd(); pfd.revents = 0; pfd.events = POLLOUT; log_debug("wait " << timeout() << " ms"); bool avail = this->wait(this->timeout(), pfd); if (avail) { // something has happened int sockerr = checkConnect(); if (_isConnected) return; if (++_addrInfoPtr == _addrInfo.impl()->end()) { // no more addrInfo - propagate error throw IOError(getErrnoString(sockerr, "connect").c_str()); } } else if (++_addrInfoPtr == _addrInfo.impl()->end()) { log_debug("timeout"); throw IOTimeout(); } close(); _connectResult = tryConnect(); if (_isConnected) return; checkPendingError(); } } catch(...) { close(); throw; } } void TcpSocketImpl::accept(const TcpServer& server, unsigned flags) { socklen_t peeraddr_len = sizeof(_peeraddr); _fd = server.impl().accept(flags, reinterpret_cast <struct sockaddr*>(&_peeraddr), peeraddr_len); if( _fd < 0 ) throw SystemError("accept"); #ifdef HAVE_ACCEPT4 IODeviceImpl::open(_fd, false, false); #else bool inherit = (flags & TcpSocket::INHERIT) != 0; IODeviceImpl::open(_fd, true, inherit); #endif //TODO ECONNABORTED EINTR EPERM _isConnected = true; log_debug( "accepted from " << getPeerAddr()); } void TcpSocketImpl::initWait(pollfd& pfd) { IODeviceImpl::initWait(pfd); if( ! _isConnected ) { log_debug("not connected, setting POLLOUT "); pfd.events = POLLOUT; } } bool TcpSocketImpl::checkPollEvent(pollfd& pfd) { log_debug("checkPollEvent " << pfd.revents); if( _isConnected ) { // check for error while neither reading nor writing // // if reading or writing, IODeviceImpl::checkPollEvent will emit // inputReady or outputReady signal and the user gets an exception in // endRead or endWrite. if ( !_device.reading() && !_device.writing() && (pfd.revents & POLLERR) ) { _device.close(); _socket.closed(_socket); return true; } return IODeviceImpl::checkPollEvent(pfd); } if ( pfd.revents & POLLERR ) { AddrInfoImpl::const_iterator ptr = _addrInfoPtr; if (++ptr == _addrInfo.impl()->end()) { // not really connected but error // end of addrinfo list means that no working addrinfo was found log_debug("no more addrinfos found"); _socket.connected(_socket); return true; } else { _addrInfoPtr = ptr; close(); _connectResult = tryConnect(); if (_isConnected || _connectResult.second) { // immediate success or error log_debug("connected successfully"); _socket.connected(_socket); } else { // by closing the previous file handle _pfd is set to 0. // creating a new socket in tryConnect may also change the value of fd. initializePoll(&pfd, 1); } return _isConnected; } } else if( pfd.revents & POLLOUT ) { int sockerr = checkConnect(); if (_isConnected) { _socket.connected(_socket); return true; } // something went wrong - look for next addrInfo log_debug("sockerr is " << sockerr << " try next"); if (++_addrInfoPtr == _addrInfo.impl()->end()) { // no more addrInfo - propagate error _connectResult = std::pair<int, const char*>(sockerr, "connect"); _socket.connected(_socket); return true; } _connectResult = tryConnect(); if (_isConnected) { _socket.connected(_socket); return true; } } return false; } } // namespace net } // namespace cxxtools <|endoftext|>
<commit_before>/* * Copyright (c) 2008-2009 * * School of Computing, University of Utah, * Salt Lake City, UT 84112, USA * * and the Gauss Group * http://www.cs.utah.edu/formal_verification * * See LICENSE for licensing information */ /* * ISP: MPI Dynamic Verification Tool * * File: TransitionList.hpp * Description: Implements lists of transitions from an interleaving * Contact: isp-dev@cs.utah.edu */ #ifndef _TRANSITIONLIST_HPP #define _TRANSITIONLIST_HPP #include <vector> #include <list> #include <algorithm> #include <sstream> #include <memory> #include <boost/iterator/indirect_iterator.hpp> #include "Envelope.hpp" #include "Transition.hpp" using std::unique_ptr; using std::vector; using boost::indirect_iterator; using boost::make_indirect_iterator; /* * This implements a TransitionList and updates "Intra-Completes-Before" */ class TransitionList { public: inline int getId() const { return id; } inline unsigned int size() const { return tlist.size(); } inline const Transition & get(int index) const { return *tlist[index]; } bool addTransition (unique_ptr<Transition> t); inline indirect_iterator<vector<unique_ptr<Transition> >::iterator> begin () { return make_indirect_iterator(tlist.begin()); } inline indirect_iterator<vector<unique_ptr<Transition> >::iterator> end () { return make_indirect_iterator(tlist.end()); } inline indirect_iterator<vector<unique_ptr<Transition> >::reverse_iterator> rbegin () { return make_indirect_iterator(tlist.rbegin()); } inline indirect_iterator<vector<unique_ptr<Transition> >::reverse_iterator> rend () { return make_indirect_iterator(tlist.rend()); } private: std::vector<std::unique_ptr<Transition> > tlist; std::list<int> ulist; int id; inline bool intraCB (const Transition &f, const Transition &s) const { const auto &env_f = f.getEnvelope(); const auto &env_s = s.getEnvelope(); /* * Find Intra-Completes-Before : * 1) Blocking rule */ if (env_f.isBlockingType ()) { return true; } /* * 2) Send order rule */ if (env_f.isSendType () && env_s.isSendType () && env_f.dest == env_s.dest && env_f.comm == env_s.comm && env_f.stag == env_s.stag) { return true; } /* * 3) Recv order rule */ if (env_f.isRecvType () && env_s.isRecvType () && (env_f.src == env_s.src || env_f.src == WILDCARD) && env_f.comm == env_s.comm && (env_f.rtag == env_s.rtag || env_f.rtag == WILDCARD)) { return true; } /* * 4) iRecv -> Wait order rule */ if (env_f.func_id == IRECV && ((env_s.func_id == WAIT) || (env_s.func_id == TEST)) && env_f.count == env_s.count) { return true; } if (env_f.func_id == ISEND && ((env_s.func_id == WAIT) || (env_s.func_id == TEST)) && env_f.count == env_s.count) { return true; } if (((env_s.func_id == WAITALL) || (env_s.func_id == WAITANY) || (env_s.func_id == TESTANY) || (env_s.func_id == TESTALL) ) && (env_f.func_id == IRECV || env_f.func_id == ISEND)) { for (int i = 0 ; i < env_s.count ; i++) { if (env_s.req_procs[i] == env_f.index) { return true; } } } if (env_s.func_id == FINALIZE) { return true; } return false; } }; #endif <commit_msg>Removed const as it is too strong.<commit_after>/* * Copyright (c) 2008-2009 * * School of Computing, University of Utah, * Salt Lake City, UT 84112, USA * * and the Gauss Group * http://www.cs.utah.edu/formal_verification * * See LICENSE for licensing information */ /* * ISP: MPI Dynamic Verification Tool * * File: TransitionList.hpp * Description: Implements lists of transitions from an interleaving * Contact: isp-dev@cs.utah.edu */ #ifndef _TRANSITIONLIST_HPP #define _TRANSITIONLIST_HPP #include <vector> #include <list> #include <algorithm> #include <sstream> #include <memory> #include <boost/iterator/indirect_iterator.hpp> #include "Envelope.hpp" #include "Transition.hpp" using std::unique_ptr; using std::vector; using boost::indirect_iterator; using boost::make_indirect_iterator; /* * This implements a TransitionList and updates "Intra-Completes-Before" */ class TransitionList { public: inline int getId() const { return id; } inline unsigned int size() const { return tlist.size(); } inline Transition & get(int index) const { return *tlist[index]; } bool addTransition (unique_ptr<Transition> t); inline indirect_iterator<vector<unique_ptr<Transition> >::iterator> begin () { return make_indirect_iterator(tlist.begin()); } inline indirect_iterator<vector<unique_ptr<Transition> >::iterator> end () { return make_indirect_iterator(tlist.end()); } inline indirect_iterator<vector<unique_ptr<Transition> >::reverse_iterator> rbegin () { return make_indirect_iterator(tlist.rbegin()); } inline indirect_iterator<vector<unique_ptr<Transition> >::reverse_iterator> rend () { return make_indirect_iterator(tlist.rend()); } private: std::vector<std::unique_ptr<Transition> > tlist; std::list<int> ulist; int id; inline bool intraCB (const Transition &f, const Transition &s) const { const auto &env_f = f.getEnvelope(); const auto &env_s = s.getEnvelope(); /* * Find Intra-Completes-Before : * 1) Blocking rule */ if (env_f.isBlockingType ()) { return true; } /* * 2) Send order rule */ if (env_f.isSendType () && env_s.isSendType () && env_f.dest == env_s.dest && env_f.comm == env_s.comm && env_f.stag == env_s.stag) { return true; } /* * 3) Recv order rule */ if (env_f.isRecvType () && env_s.isRecvType () && (env_f.src == env_s.src || env_f.src == WILDCARD) && env_f.comm == env_s.comm && (env_f.rtag == env_s.rtag || env_f.rtag == WILDCARD)) { return true; } /* * 4) iRecv -> Wait order rule */ if (env_f.func_id == IRECV && ((env_s.func_id == WAIT) || (env_s.func_id == TEST)) && env_f.count == env_s.count) { return true; } if (env_f.func_id == ISEND && ((env_s.func_id == WAIT) || (env_s.func_id == TEST)) && env_f.count == env_s.count) { return true; } if (((env_s.func_id == WAITALL) || (env_s.func_id == WAITANY) || (env_s.func_id == TESTANY) || (env_s.func_id == TESTALL) ) && (env_f.func_id == IRECV || env_f.func_id == ISEND)) { for (int i = 0 ; i < env_s.count ; i++) { if (env_s.req_procs[i] == env_f.index) { return true; } } } if (env_s.func_id == FINALIZE) { return true; } return false; } }; #endif <|endoftext|>
<commit_before>/** ****************************************************************************** * Xenia : Xbox 360 Emulator Research Project * ****************************************************************************** * Copyright 2013 Ben Vanik. All rights reserved. * * Released under the BSD license - see LICENSE in the root for more details. * ****************************************************************************** */ #include <xenia/hid/input_system.h> #include <xenia/emulator.h> #include <xenia/cpu/processor.h> #include <xenia/hid/input_driver.h> using namespace xe; using namespace xe::hid; InputSystem::InputSystem(Emulator* emulator) : emulator_(emulator) { memory_ = xe_memory_retain(emulator->memory()); } InputSystem::~InputSystem() { for (std::vector<InputDriver*>::iterator it = drivers_.begin(); it != drivers_.end(); ++it) { InputDriver* driver = *it; delete driver; } xe_memory_release(memory_); } X_STATUS InputSystem::Setup() { processor_ = emulator_->processor(); return X_STATUS_SUCCESS; } void InputSystem::AddDriver(InputDriver* driver) { drivers_.push_back(driver); } X_RESULT InputSystem::GetCapabilities( uint32_t user_index, uint32_t flags, X_INPUT_CAPABILITIES& out_caps) { for (std::vector<InputDriver*>::iterator it = drivers_.begin(); it != drivers_.end(); ++it) { InputDriver* driver = *it; if (XSUCCEEDED(driver->GetCapabilities(user_index, flags, out_caps))) { return X_ERROR_SUCCESS; } } return X_ERROR_DEVICE_NOT_CONNECTED; } X_RESULT InputSystem::GetState(uint32_t user_index, X_INPUT_STATE& out_state) { for (std::vector<InputDriver*>::iterator it = drivers_.begin(); it != drivers_.end(); ++it) { InputDriver* driver = *it; if (XSUCCEEDED(driver->GetState(user_index, out_state))) { return X_ERROR_SUCCESS; } } return X_ERROR_DEVICE_NOT_CONNECTED; } X_RESULT InputSystem::SetState( uint32_t user_index, X_INPUT_VIBRATION& vibration) { for (std::vector<InputDriver*>::iterator it = drivers_.begin(); it != drivers_.end(); ++it) { InputDriver* driver = *it; if (XSUCCEEDED(driver->SetState(user_index, vibration))) { return X_ERROR_SUCCESS; } } return X_ERROR_DEVICE_NOT_CONNECTED; } <commit_msg>Fix input error return.<commit_after>/** ****************************************************************************** * Xenia : Xbox 360 Emulator Research Project * ****************************************************************************** * Copyright 2013 Ben Vanik. All rights reserved. * * Released under the BSD license - see LICENSE in the root for more details. * ****************************************************************************** */ #include <xenia/hid/input_system.h> #include <xenia/emulator.h> #include <xenia/cpu/processor.h> #include <xenia/hid/input_driver.h> using namespace xe; using namespace xe::hid; InputSystem::InputSystem(Emulator* emulator) : emulator_(emulator) { memory_ = xe_memory_retain(emulator->memory()); } InputSystem::~InputSystem() { for (std::vector<InputDriver*>::iterator it = drivers_.begin(); it != drivers_.end(); ++it) { InputDriver* driver = *it; delete driver; } xe_memory_release(memory_); } X_STATUS InputSystem::Setup() { processor_ = emulator_->processor(); return X_STATUS_SUCCESS; } void InputSystem::AddDriver(InputDriver* driver) { drivers_.push_back(driver); } X_RESULT InputSystem::GetCapabilities( uint32_t user_index, uint32_t flags, X_INPUT_CAPABILITIES& out_caps) { for (std::vector<InputDriver*>::iterator it = drivers_.begin(); it != drivers_.end(); ++it) { InputDriver* driver = *it; if (XSUCCEEDED(driver->GetCapabilities(user_index, flags, out_caps))) { return X_ERROR_SUCCESS; } } return X_ERROR_DEVICE_NOT_CONNECTED; } X_RESULT InputSystem::GetState(uint32_t user_index, X_INPUT_STATE& out_state) { for (std::vector<InputDriver*>::iterator it = drivers_.begin(); it != drivers_.end(); ++it) { InputDriver* driver = *it; if (driver->GetState(user_index, out_state) == X_ERROR_SUCCESS) { return X_ERROR_SUCCESS; } } return X_ERROR_DEVICE_NOT_CONNECTED; } X_RESULT InputSystem::SetState( uint32_t user_index, X_INPUT_VIBRATION& vibration) { for (std::vector<InputDriver*>::iterator it = drivers_.begin(); it != drivers_.end(); ++it) { InputDriver* driver = *it; if (XSUCCEEDED(driver->SetState(user_index, vibration))) { return X_ERROR_SUCCESS; } } return X_ERROR_DEVICE_NOT_CONNECTED; } <|endoftext|>
<commit_before>// // This file is part of the Marble Virtual Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2009 Andrew Manson <g.real.ate@gmail.com> // #include "GeoLineStringGraphicsItem.h" #include "GeoDataLineString.h" #include "GeoDataLineStyle.h" #include "GeoPainter.h" #include "ViewportParams.h" #include "GeoDataStyle.h" namespace Marble { GeoLineStringGraphicsItem::GeoLineStringGraphicsItem( const GeoDataLineString* lineString ) : GeoGraphicsItem(), m_lineString( lineString ) { } void GeoLineStringGraphicsItem::setLineString( const GeoDataLineString* lineString ) { m_lineString = lineString; } GeoDataCoordinates GeoLineStringGraphicsItem::coordinate() const { return m_lineString->latLonAltBox().center(); } void GeoLineStringGraphicsItem::coordinate( qreal &longitude, qreal &latitude, qreal &altitude ) const { GeoDataCoordinates coords = m_lineString->latLonAltBox().center(); longitude = coords.longitude(); latitude = coords.latitude(); altitude = coords.altitude(); } GeoDataLatLonAltBox GeoLineStringGraphicsItem::latLonAltBox() const { return m_lineString->latLonAltBox(); } void GeoLineStringGraphicsItem::paint( GeoPainter* painter, ViewportParams* viewport, const QString& renderPos, GeoSceneLayer* layer ) { Q_UNUSED( renderPos ); Q_UNUSED( layer ); if ( !style() ) { painter->save(); painter->setPen( QPen() ); painter->drawPolyline( *m_lineString ); painter->restore(); return; } if(style()->lineStyle().color() == Qt::transparent) return; painter->save(); QPen currentPen = painter->pen(); if ( currentPen.color() != style()->lineStyle().color() ) currentPen.setColor( style()->lineStyle().color() ); if ( currentPen.widthF() != style()->lineStyle().width() || style()->lineStyle().physicalWidth() != 0.0 ) { if ( float( viewport->radius() ) / EARTH_RADIUS * style()->lineStyle().physicalWidth() < style()->lineStyle().width() ) currentPen.setWidthF( style()->lineStyle().width() ); else currentPen.setWidthF( float( viewport->radius() ) / EARTH_RADIUS * style()->lineStyle().physicalWidth() ); } if ( currentPen.capStyle() != style()->lineStyle().capStyle() ) currentPen.setCapStyle( style()->lineStyle().capStyle() ); if ( currentPen.style() != style()->lineStyle().penStyle() ) currentPen.setStyle( style()->lineStyle().penStyle() ); if ( style()->lineStyle().penStyle() == Qt::CustomDashLine ) currentPen.setDashPattern( style()->lineStyle().dashPattern() ); if ( painter->mapQuality() != Marble::HighQuality && painter->mapQuality() != Marble::PrintQuality ) { QColor penColor = currentPen.color(); penColor.setAlpha( 255 ); currentPen.setColor( penColor ); } if ( painter->pen() != currentPen ) painter->setPen( currentPen ); if ( style()->lineStyle().background() ) { painter->save(); QPen bgPen( painter->pen() ); bgPen.setColor( style()->polyStyle().color() ); bgPen.setStyle( Qt::SolidLine ); bgPen.setCapStyle( Qt::RoundCap ); painter->setPen( bgPen ); painter->drawPolyline( *m_lineString ); painter->restore(); } painter->drawPolyline( *m_lineString ); painter->restore(); } } <commit_msg>faster background painting for GeoLineStringGraphicsItems<commit_after>// // This file is part of the Marble Virtual Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2009 Andrew Manson <g.real.ate@gmail.com> // #include "GeoLineStringGraphicsItem.h" #include "GeoDataLineString.h" #include "GeoDataLineStyle.h" #include "GeoPainter.h" #include "ViewportParams.h" #include "GeoDataStyle.h" namespace Marble { GeoLineStringGraphicsItem::GeoLineStringGraphicsItem( const GeoDataLineString* lineString ) : GeoGraphicsItem(), m_lineString( lineString ) { } void GeoLineStringGraphicsItem::setLineString( const GeoDataLineString* lineString ) { m_lineString = lineString; } GeoDataCoordinates GeoLineStringGraphicsItem::coordinate() const { return m_lineString->latLonAltBox().center(); } void GeoLineStringGraphicsItem::coordinate( qreal &longitude, qreal &latitude, qreal &altitude ) const { GeoDataCoordinates coords = m_lineString->latLonAltBox().center(); longitude = coords.longitude(); latitude = coords.latitude(); altitude = coords.altitude(); } GeoDataLatLonAltBox GeoLineStringGraphicsItem::latLonAltBox() const { return m_lineString->latLonAltBox(); } void GeoLineStringGraphicsItem::paint( GeoPainter* painter, ViewportParams* viewport, const QString& renderPos, GeoSceneLayer* layer ) { Q_UNUSED( renderPos ); Q_UNUSED( layer ); if ( !style() ) { painter->save(); painter->setPen( QPen() ); painter->drawPolyline( *m_lineString ); painter->restore(); return; } if(style()->lineStyle().color() == Qt::transparent) return; painter->save(); QPen currentPen = painter->pen(); if ( currentPen.color() != style()->lineStyle().color() ) currentPen.setColor( style()->lineStyle().color() ); if ( currentPen.widthF() != style()->lineStyle().width() || style()->lineStyle().physicalWidth() != 0.0 ) { if ( float( viewport->radius() ) / EARTH_RADIUS * style()->lineStyle().physicalWidth() < style()->lineStyle().width() ) currentPen.setWidthF( style()->lineStyle().width() ); else currentPen.setWidthF( float( viewport->radius() ) / EARTH_RADIUS * style()->lineStyle().physicalWidth() ); } if ( currentPen.capStyle() != style()->lineStyle().capStyle() ) currentPen.setCapStyle( style()->lineStyle().capStyle() ); if ( currentPen.style() != style()->lineStyle().penStyle() ) currentPen.setStyle( style()->lineStyle().penStyle() ); if ( style()->lineStyle().penStyle() == Qt::CustomDashLine ) currentPen.setDashPattern( style()->lineStyle().dashPattern() ); if ( painter->mapQuality() != Marble::HighQuality && painter->mapQuality() != Marble::PrintQuality ) { QColor penColor = currentPen.color(); penColor.setAlpha( 255 ); currentPen.setColor( penColor ); } if ( painter->pen() != currentPen ) painter->setPen( currentPen ); if ( style()->lineStyle().background() ) { QBrush brush = painter->background(); brush.setColor( style()->polyStyle().color() ); painter->setBackground( brush ); painter->setBackgroundMode( Qt::OpaqueMode ); } painter->drawPolyline( *m_lineString ); painter->restore(); } } <|endoftext|>
<commit_before>#include "HTTPSession.h" #include "Application/HTTP/UrlParam.h" #include "Application/HTTP/HTTPRequest.h" #include "Application/HTTP/HTTPConnection.h" #include "Application/HTTP/HTTPConsts.h" #include "Application/HTTP/Mime.h" #define MSG_FAIL "Unable to process your request at this time" #define CONTENT_TYPE_PLAIN HTTP_HEADER_CONTENT_TYPE ": " MIME_TYPE_TEXT_PLAIN HTTP_CS_CRLF #define CONTENT_TYPE_HTML HTTP_HEADER_CONTENT_TYPE ": " MIME_TYPE_TEXT_HTML HTTP_CS_CRLF HTTPSession::HTTPSession() { headerSent = false; conn = NULL; type = PLAIN; } void HTTPSession::SetConnection(HTTPConnection* conn_) { conn = conn_; if (conn != NULL) json.Init(conn); } bool HTTPSession::ParseRequest(HTTPRequest& request, ReadBuffer& cmd, UrlParam& params) { char* qmark; ReadBuffer rb; ReadBuffer jsonCallback; ReadBuffer mimeType; ReadBuffer origin; // TODO: when adding keep-alive HTTP sessions, move this to an Init() function isFlushed = false; uri = request.line.uri; rb = request.line.uri; if (rb.GetCharAt(0) == '/') rb.Advance(1); mimeType.Reset(); ParseType(rb); cmd = rb; qmark = NULL; if (rb.GetLength() > 0) qmark = FindInBuffer(rb.GetBuffer(), rb.GetLength() - 1, '?'); if (qmark) { rb.Advance((unsigned) (qmark - rb.GetBuffer() + 1)); params.Init(rb.GetBuffer(), rb.GetLength(), '&'); cmd.SetLength((unsigned) (qmark - cmd.GetBuffer())); if (type == JSON) { HTTP_GET_OPT_PARAM(params, "callback", jsonCallback); json.SetCallbackPrefix(jsonCallback); } // mime type is overridable HTTP_GET_OPT_PARAM(params, "mimetype", mimeType); if (mimeType.GetLength() != 0) conn->SetContentType(mimeType); // CORS support // http://www.w3.org/TR/cors/ HTTP_GET_OPT_PARAM(params, "origin", origin); } return true; } void HTTPSession::ParseType(ReadBuffer& rb) { const char JSON_PREFIX[] = "json/"; const char HTML_PREFIX[] = "html/"; if (HTTP_MATCH_PREFIX(rb, JSON_PREFIX)) { SetType(JSON); rb.Advance(sizeof(JSON_PREFIX) - 1); } else if (HTTP_MATCH_PREFIX(rb, HTML_PREFIX)) { SetType(HTML); rb.Advance(sizeof(HTML_PREFIX) - 1); } else SetType(PLAIN); } void HTTPSession::ResponseFail() { ASSERT(headerSent == false); if (!conn) return; if (type == JSON) json.PrintStatus("error", MSG_FAIL); else conn->Response(HTTP_STATUS_CODE_OK, MSG_FAIL, sizeof(MSG_FAIL) - 1); } void HTTPSession::Redirect(const ReadBuffer& location) { Buffer extraHeader; ASSERT(headerSent == false); if (!conn) return; extraHeader.Writef(HTTP_HEADER_LOCATION ": %R" HTTP_CS_CRLF, &location); extraHeader.NullTerminate(); conn->ResponseHeader(HTTP_STATUS_CODE_TEMPORARY_REDIRECT, true, extraHeader.GetBuffer()); } void HTTPSession::Print(const ReadBuffer& line) { Buffer header; ReadBuffer tmp; if (!conn) return; if (!headerSent) { if (type == JSON) json.Start(); else conn->WriteHeader(HTTP_STATUS_CODE_OK); headerSent = true; } if (type == JSON) { tmp = "response"; json.PrintString(tmp); json.PrintColon(); json.PrintString(line); } else { conn->Write(line.GetBuffer(), line.GetLength()); conn->Print("\n"); } } void HTTPSession::PrintPair(const ReadBuffer& key, const ReadBuffer& value) { if (!conn) return; if (!headerSent) { if (type == JSON) json.Start(); else conn->WriteHeader(HTTP_STATUS_CODE_OK); headerSent = true; } if (type == JSON) json.PrintPair(key.GetBuffer(), key.GetLength(), value.GetBuffer(), value.GetLength()); else { conn->Write(key.GetBuffer(), key.GetLength()); conn->Print(": "); conn->Write(value.GetBuffer(), value.GetLength()); conn->Print("\n"); } } void HTTPSession::PrintPair(const char* key, const char* value) { PrintPair(ReadBuffer(key), ReadBuffer(value)); } void HTTPSession::Flush() { if (!conn) return; if (type == JSON) json.End(); conn->Flush(true); isFlushed = true; } void HTTPSession::SetType(Type type_) { const char* mime; ReadBuffer mimeType; type = type_; switch (type) { case PLAIN: mime = MIME_TYPE_TEXT_PLAIN; break; case HTML: mime = MIME_TYPE_TEXT_HTML; break; case JSON: mime = MIME_TYPE_APPLICATION_JSON; break; default: mime = MIME_TYPE_TEXT_PLAIN; break; } if (mimeType.GetLength() == 0) mimeType.Wrap(mime); conn->SetContentType(mimeType); } bool HTTPSession::IsFlushed() { return isFlushed; } bool HTTPSession::RedirectLocalhost(HTTPConnection *conn, HTTPRequest &request) { #ifdef PLATFORM_WINDOWS ReadBuffer host; // fix Windows 7 IPv6 localhost name resolution issue host = request.header.GetField(HTTP_HEADER_HOST); if (host.BeginsWith("localhost")) { Buffer newHost; Buffer ha; unsigned i; newHost.Write("127.0.0.1"); for (i = 0; i < host.GetLength(); i++) { if (host.GetCharAt(i) == ':') { host.Advance(i); newHost.Append(host); break; } } ha.Writef(HTTP_HEADER_LOCATION ": http://%B%R" HTTP_CS_CRLF, &newHost, &request.line.uri); ha.NullTerminate(); conn->ResponseHeader(HTTP_STATUS_CODE_TEMPORARY_REDIRECT, true, ha.GetBuffer()); conn->Flush(true); return true; } #endif return false; } <commit_msg>Undo localhost redirection policy.<commit_after>#include "HTTPSession.h" #include "Application/HTTP/UrlParam.h" #include "Application/HTTP/HTTPRequest.h" #include "Application/HTTP/HTTPConnection.h" #include "Application/HTTP/HTTPConsts.h" #include "Application/HTTP/Mime.h" #define MSG_FAIL "Unable to process your request at this time" #define CONTENT_TYPE_PLAIN HTTP_HEADER_CONTENT_TYPE ": " MIME_TYPE_TEXT_PLAIN HTTP_CS_CRLF #define CONTENT_TYPE_HTML HTTP_HEADER_CONTENT_TYPE ": " MIME_TYPE_TEXT_HTML HTTP_CS_CRLF HTTPSession::HTTPSession() { headerSent = false; conn = NULL; type = PLAIN; } void HTTPSession::SetConnection(HTTPConnection* conn_) { conn = conn_; if (conn != NULL) json.Init(conn); } bool HTTPSession::ParseRequest(HTTPRequest& request, ReadBuffer& cmd, UrlParam& params) { char* qmark; ReadBuffer rb; ReadBuffer jsonCallback; ReadBuffer mimeType; ReadBuffer origin; // TODO: when adding keep-alive HTTP sessions, move this to an Init() function isFlushed = false; uri = request.line.uri; rb = request.line.uri; if (rb.GetCharAt(0) == '/') rb.Advance(1); mimeType.Reset(); ParseType(rb); cmd = rb; qmark = NULL; if (rb.GetLength() > 0) qmark = FindInBuffer(rb.GetBuffer(), rb.GetLength() - 1, '?'); if (qmark) { rb.Advance((unsigned) (qmark - rb.GetBuffer() + 1)); params.Init(rb.GetBuffer(), rb.GetLength(), '&'); cmd.SetLength((unsigned) (qmark - cmd.GetBuffer())); if (type == JSON) { HTTP_GET_OPT_PARAM(params, "callback", jsonCallback); json.SetCallbackPrefix(jsonCallback); } // mime type is overridable HTTP_GET_OPT_PARAM(params, "mimetype", mimeType); if (mimeType.GetLength() != 0) conn->SetContentType(mimeType); // CORS support // http://www.w3.org/TR/cors/ HTTP_GET_OPT_PARAM(params, "origin", origin); } return true; } void HTTPSession::ParseType(ReadBuffer& rb) { const char JSON_PREFIX[] = "json/"; const char HTML_PREFIX[] = "html/"; if (HTTP_MATCH_PREFIX(rb, JSON_PREFIX)) { SetType(JSON); rb.Advance(sizeof(JSON_PREFIX) - 1); } else if (HTTP_MATCH_PREFIX(rb, HTML_PREFIX)) { SetType(HTML); rb.Advance(sizeof(HTML_PREFIX) - 1); } else SetType(PLAIN); } void HTTPSession::ResponseFail() { ASSERT(headerSent == false); if (!conn) return; if (type == JSON) json.PrintStatus("error", MSG_FAIL); else conn->Response(HTTP_STATUS_CODE_OK, MSG_FAIL, sizeof(MSG_FAIL) - 1); } void HTTPSession::Redirect(const ReadBuffer& location) { Buffer extraHeader; ASSERT(headerSent == false); if (!conn) return; extraHeader.Writef(HTTP_HEADER_LOCATION ": %R" HTTP_CS_CRLF, &location); extraHeader.NullTerminate(); conn->ResponseHeader(HTTP_STATUS_CODE_TEMPORARY_REDIRECT, true, extraHeader.GetBuffer()); } void HTTPSession::Print(const ReadBuffer& line) { Buffer header; ReadBuffer tmp; if (!conn) return; if (!headerSent) { if (type == JSON) json.Start(); else conn->WriteHeader(HTTP_STATUS_CODE_OK); headerSent = true; } if (type == JSON) { tmp = "response"; json.PrintString(tmp); json.PrintColon(); json.PrintString(line); } else { conn->Write(line.GetBuffer(), line.GetLength()); conn->Print("\n"); } } void HTTPSession::PrintPair(const ReadBuffer& key, const ReadBuffer& value) { if (!conn) return; if (!headerSent) { if (type == JSON) json.Start(); else conn->WriteHeader(HTTP_STATUS_CODE_OK); headerSent = true; } if (type == JSON) json.PrintPair(key.GetBuffer(), key.GetLength(), value.GetBuffer(), value.GetLength()); else { conn->Write(key.GetBuffer(), key.GetLength()); conn->Print(": "); conn->Write(value.GetBuffer(), value.GetLength()); conn->Print("\n"); } } void HTTPSession::PrintPair(const char* key, const char* value) { PrintPair(ReadBuffer(key), ReadBuffer(value)); } void HTTPSession::Flush() { if (!conn) return; if (type == JSON) json.End(); conn->Flush(true); isFlushed = true; } void HTTPSession::SetType(Type type_) { const char* mime; ReadBuffer mimeType; type = type_; switch (type) { case PLAIN: mime = MIME_TYPE_TEXT_PLAIN; break; case HTML: mime = MIME_TYPE_TEXT_HTML; break; case JSON: mime = MIME_TYPE_APPLICATION_JSON; break; default: mime = MIME_TYPE_TEXT_PLAIN; break; } if (mimeType.GetLength() == 0) mimeType.Wrap(mime); conn->SetContentType(mimeType); } bool HTTPSession::IsFlushed() { return isFlushed; } bool HTTPSession::RedirectLocalhost(HTTPConnection *conn, HTTPRequest &request) { ReadBuffer host; // fix Windows 7 IPv6 localhost name resolution issue host = request.header.GetField(HTTP_HEADER_HOST); if (host.BeginsWith("localhost")) { Buffer newHost; Buffer ha; unsigned i; newHost.Write("127.0.0.1"); for (i = 0; i < host.GetLength(); i++) { if (host.GetCharAt(i) == ':') { host.Advance(i); newHost.Append(host); break; } } ha.Writef(HTTP_HEADER_LOCATION ": http://%B%R" HTTP_CS_CRLF, &newHost, &request.line.uri); ha.NullTerminate(); conn->ResponseHeader(HTTP_STATUS_CODE_TEMPORARY_REDIRECT, true, ha.GetBuffer()); conn->Flush(true); return true; } return false; } <|endoftext|>
<commit_before>/* Twofold-ChaiScript * (C) Copyright 2015 HicknHack Software GmbH * * The original code can be found at: * https://github.com/arBmind/Twofold-ChaiScript * * 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 "Engine.h" #include "Twofold/intern/ChaiScriptTargetBuilderApi.h" #include "Twofold/intern/QStringHelper.h" #include "Twofold/intern/find_last.h" #include <chaiscript/chaiscript.hpp> #include <chaiscript/utility/utility.hpp> #include <QVector> #include <vector> namespace Twofold { namespace intern { chaiscript::ModulePtr chaiscript_stdlib(); } // namespace intern using namespace intern; namespace { FileLineColumnPositionList generateExceptionCallerStack(const PreparedTemplate &preparedTemplate, const QStringList &backtrace) { FileLineColumnPositionList callerStack; for (const auto& traceLine : backtrace) { // traceline format: "<function>() at <line>" auto begin = traceLine.begin(); const auto end = traceLine.end(); begin = find_last(begin, end, QChar(' ')); QString lineString = toQString(begin, end); bool convertSuccesful = false; const int line = lineString.toInt(&convertSuccesful); const int column = 1; if (convertSuccesful) { const auto position = SourceMap::getOriginalPositionFromGenerated(preparedTemplate.sourceMap, {line, column}); callerStack.push_back(position); } } return callerStack; } } // namespace class Engine::Private { public: Private(MessageHandlerPtr messageHandler, TextLoaderPtr textLoader) : m_messageHandler(messageHandler) , m_textLoader(textLoader) , m_chai(chaiscript_stdlib()) { defineQVariantCasts(); } Target execPrepared(const PreparedTemplate &preparedTemplate, const Engine::Context &inputs) { ChaiScriptTargetBuilderApi scriptTargetBuilder(preparedTemplate.originPositions); auto old_state = m_chai.get_state(); defineInputs(inputs); defineTemplateApi(scriptTargetBuilder); try { auto resultValue = m_chai.eval(preparedTemplate.script.toStdString(), chaiscript::exception_specification<const std::exception &>()); } catch (const chaiscript::exception::eval_error &error) { const int line = error.start_position.line; const int column = error.start_position.column; FileLineColumnPositionList position {{ SourceMap::getOriginalPositionFromGenerated(preparedTemplate.sourceMap, {line, column}) }}; const QString text = "Eval Error: " + QString::fromLatin1(error.what()); m_messageHandler->scriptMessage(MessageType::Error, position, text); } catch (const chaiscript::exception::bad_boxed_cast &e) { const QString text = "Bad Boxed Cast: " + QString::fromLatin1(e.what()); m_messageHandler->message(MessageType::Error, text); } catch (const std::exception &e) { const QString text = "Exception: " + QString::fromLatin1(e.what()); m_messageHandler->message(MessageType::Error, text); } m_chai.set_state(old_state); const auto sourceMapText = scriptTargetBuilder.build(); return { sourceMapText.sourceMap, sourceMapText.text }; } // void showSyntaxError(QScriptSyntaxCheckResult checkResult, const PreparedTemplate &preparedTemplate) // { // const int line = checkResult.errorLineNumber(); // const int column = checkResult.errorColumnNumber(); // FileLineColumnPositionList position {{ SourceMap::getOriginalPositionFromGenerated(preparedTemplate.sourceMap, {line, column}) }}; // const QString text = "Syntax Error: " + checkResult.errorMessage(); // m_messageHandler->scriptMessage(MessageType::Error, position, text); // } PreparedTemplateBuilder createPreparedBuilder() { return { m_messageHandler, m_textLoader }; } private: // void showException(QScriptValue resultValue, const PreparedTemplate &preparedTemplate) // { // const QStringList backtrace = m_chai.uncaughtExceptionBacktrace(); // auto positionStack = generateExceptionCallerStack(preparedTemplate, backtrace); // const int line = m_chai.uncaughtExceptionLineNumber(); // const int column = 1; // TODO: use agent and stack! // positionStack.insert(positionStack.begin(), SourceMap::getOriginalPositionFromGenerated(preparedTemplate.sourceMap, {line, column})); // const QString text = "Uncaught Exception: " + resultValue.toString(); // m_messageHandler->scriptMessage(MessageType::Error, positionStack, text); // } void defineQVariantCasts() { m_chai.eval(R"CHAISCRIPT( def for_each_with_index(container, func) { for (var i = 0; i < container.size(); ++i) { func(container[i], i); } } def to_string(void) { "" } )CHAISCRIPT" , chaiscript::Exception_Handler(), "twofold prelude"); m_chai.add(chaiscript::user_type<QVariant>(), "QVariant"); m_chai.add(chaiscript::type_conversion<QVariant, int>([](const QVariant& v){return v.toInt();})); m_chai.add(chaiscript::type_conversion<QVariant, float>([](const QVariant& v){return v.toFloat();})); m_chai.add(chaiscript::type_conversion<QVariant, bool>([](const QVariant& v){return v.toBool();})); m_chai.add(chaiscript::type_conversion<QVariant, std::vector<QVariant> >([](const QVariant& v){ std::vector<QVariant> r; const auto seq = v.value<QSequentialIterable>(); r.reserve(1 + seq.size()); for (const auto &e : seq) r.push_back(e); return r; })); m_chai.add(chaiscript::fun([](const QVariant* v){ return v->toString().toStdString(); }), "to_string"); // m_chai.add(chaiscript::fun< std::string (void) >([](void){ // return ""; // }), "to_string"); m_chai.add(chaiscript::fun([](const QVariant* v, bool x){ return v->toBool() == x; }), "=="); m_chai.add(chaiscript::fun([](const QVariant* v, const std::string &x){ return v->toString().toStdString() == x; }), "=="); m_chai.add(chaiscript::fun([](const QVariant* v, const std::string& k){ if (v->canConvert(QMetaType::QObjectStar)) { const auto* o = v->value<QObject*>(); return o->property( k.c_str() ); } else if (v->canConvert(QMetaType::QVariantHash)) { const auto& a = v->value<QAssociativeIterable>(); return a.value(QString::fromStdString(k)); } throw std::range_error("unknown type"); }), "method_missing"); m_chai.add(chaiscript::fun([](const QVariant* v, int index)->QVariant{ if (v->canConvert(QMetaType::QVariantList)) { const auto& s = v->value<QSequentialIterable>(); if (index >= s.size()) throw std::range_error("index out of range"); return s.at(index); } throw std::range_error("unknown type"); }), "[]"); m_chai.add(chaiscript::user_type<QObject>(), "QObject"); m_chai.add(chaiscript::fun([](const QObject* o, const std::string& k){ return o->property( k.c_str() ); }), "method_missing"); m_chai.add(chaiscript::user_type<QString>(), "QString"); m_chai.add(chaiscript::type_conversion<std::string, QString>([](const std::string& v){return QString::fromStdString(v);})); } void defineTemplateApi(ChaiScriptTargetBuilderApi &templateApi) { auto module = std::make_shared<chaiscript::Module>(); chaiscript::utility::add_class<ChaiScriptTargetBuilderApi>(*module, "TwofoldTemplate", {}, { { chaiscript::fun(&ChaiScriptTargetBuilderApi::append), "append" }, { chaiscript::fun(&ChaiScriptTargetBuilderApi::newLine), "newLine" }, { chaiscript::fun(&ChaiScriptTargetBuilderApi::pushIndentation), "pushIndentation" }, { chaiscript::fun(&ChaiScriptTargetBuilderApi::popIndentation), "popIndentation" }, { chaiscript::fun(&ChaiScriptTargetBuilderApi::indentPart), "indentPart" }, { chaiscript::fun(&ChaiScriptTargetBuilderApi::pushPartIndent), "pushPartIndent" }, { chaiscript::fun(&ChaiScriptTargetBuilderApi::popPartIndent), "popPartIndent" }, } ); m_chai.add(module); m_chai.add_global(chaiscript::var(&templateApi), "_template"); } void defineInputs(const Engine::Context &inputs) { for (const auto &v : inputs) { m_chai.add_global(v.second, v.first); } } MessageHandlerPtr m_messageHandler; TextLoaderPtr m_textLoader; chaiscript::ChaiScript m_chai; }; Engine::Engine(MessageHandlerPtr messageHandler, TextLoaderPtr textLoader) : m_private(new Private(messageHandler, textLoader)) { } Engine::Engine(TextLoaderPtr textLoader, MessageHandlerPtr messageHandler) : Engine(messageHandler, textLoader) { } void Engine::showTemplateSyntaxErrors(const PreparedTemplate &) const { // auto checkResult = QScriptEngine::checkSyntax(preparedTemplate.script); // if (checkResult.state() == QScriptSyntaxCheckResult::Error) // m_private->showSyntaxError(checkResult, preparedTemplate); } Target Engine::exec(const PreparedTemplate &preparedTemplate, const Context &inputs) { return m_private->execPrepared(preparedTemplate, inputs); } PreparedTemplate Engine::prepare(const QString &templateName) const { auto prepared = m_private->createPreparedBuilder().build(templateName); this->showTemplateSyntaxErrors(prepared); return prepared; } Target Engine::execTemplateName(const QString &templateName, const Context &inputs) { auto prepared = this->prepare(templateName); return this->exec(prepared, inputs); } void Engine::PrivateDeleter::operator()(Engine::Private *p) const { delete p; } } // namespace Twofold <commit_msg>* commented out unused function<commit_after>/* Twofold-ChaiScript * (C) Copyright 2015 HicknHack Software GmbH * * The original code can be found at: * https://github.com/arBmind/Twofold-ChaiScript * * 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 "Engine.h" #include "Twofold/intern/ChaiScriptTargetBuilderApi.h" #include "Twofold/intern/QStringHelper.h" #include "Twofold/intern/find_last.h" #include <chaiscript/chaiscript.hpp> #include <chaiscript/utility/utility.hpp> #include <QVector> #include <vector> namespace Twofold { namespace intern { chaiscript::ModulePtr chaiscript_stdlib(); } // namespace intern using namespace intern; namespace { //FileLineColumnPositionList generateExceptionCallerStack(const PreparedTemplate &preparedTemplate, const QStringList &backtrace) //{ // FileLineColumnPositionList callerStack; // for (const auto& traceLine : backtrace) { // // traceline format: "<function>() at <line>" // auto begin = traceLine.begin(); // const auto end = traceLine.end(); // begin = find_last(begin, end, QChar(' ')); // QString lineString = toQString(begin, end); // bool convertSuccesful = false; // const int line = lineString.toInt(&convertSuccesful); // const int column = 1; // if (convertSuccesful) { // const auto position = SourceMap::getOriginalPositionFromGenerated(preparedTemplate.sourceMap, {line, column}); // callerStack.push_back(position); // } // } // return callerStack; //} } // namespace class Engine::Private { public: Private(MessageHandlerPtr messageHandler, TextLoaderPtr textLoader) : m_messageHandler(messageHandler) , m_textLoader(textLoader) , m_chai(chaiscript_stdlib()) { defineQVariantCasts(); } Target execPrepared(const PreparedTemplate &preparedTemplate, const Engine::Context &inputs) { ChaiScriptTargetBuilderApi scriptTargetBuilder(preparedTemplate.originPositions); auto old_state = m_chai.get_state(); defineInputs(inputs); defineTemplateApi(scriptTargetBuilder); try { auto resultValue = m_chai.eval(preparedTemplate.script.toStdString(), chaiscript::exception_specification<const std::exception &>()); } catch (const chaiscript::exception::eval_error &error) { const int line = error.start_position.line; const int column = error.start_position.column; FileLineColumnPositionList position {{ SourceMap::getOriginalPositionFromGenerated(preparedTemplate.sourceMap, {line, column}) }}; const QString text = "Eval Error: " + QString::fromLatin1(error.what()); m_messageHandler->scriptMessage(MessageType::Error, position, text); } catch (const chaiscript::exception::bad_boxed_cast &e) { const QString text = "Bad Boxed Cast: " + QString::fromLatin1(e.what()); m_messageHandler->message(MessageType::Error, text); } catch (const std::exception &e) { const QString text = "Exception: " + QString::fromLatin1(e.what()); m_messageHandler->message(MessageType::Error, text); } m_chai.set_state(old_state); const auto sourceMapText = scriptTargetBuilder.build(); return { sourceMapText.sourceMap, sourceMapText.text }; } // void showSyntaxError(QScriptSyntaxCheckResult checkResult, const PreparedTemplate &preparedTemplate) // { // const int line = checkResult.errorLineNumber(); // const int column = checkResult.errorColumnNumber(); // FileLineColumnPositionList position {{ SourceMap::getOriginalPositionFromGenerated(preparedTemplate.sourceMap, {line, column}) }}; // const QString text = "Syntax Error: " + checkResult.errorMessage(); // m_messageHandler->scriptMessage(MessageType::Error, position, text); // } PreparedTemplateBuilder createPreparedBuilder() { return { m_messageHandler, m_textLoader }; } private: // void showException(QScriptValue resultValue, const PreparedTemplate &preparedTemplate) // { // const QStringList backtrace = m_chai.uncaughtExceptionBacktrace(); // auto positionStack = generateExceptionCallerStack(preparedTemplate, backtrace); // const int line = m_chai.uncaughtExceptionLineNumber(); // const int column = 1; // TODO: use agent and stack! // positionStack.insert(positionStack.begin(), SourceMap::getOriginalPositionFromGenerated(preparedTemplate.sourceMap, {line, column})); // const QString text = "Uncaught Exception: " + resultValue.toString(); // m_messageHandler->scriptMessage(MessageType::Error, positionStack, text); // } void defineQVariantCasts() { m_chai.eval(R"CHAISCRIPT( def for_each_with_index(container, func) { for (var i = 0; i < container.size(); ++i) { func(container[i], i); } } def to_string(void) { "" } )CHAISCRIPT" , chaiscript::Exception_Handler(), "twofold prelude"); m_chai.add(chaiscript::user_type<QVariant>(), "QVariant"); m_chai.add(chaiscript::type_conversion<QVariant, int>([](const QVariant& v){return v.toInt();})); m_chai.add(chaiscript::type_conversion<QVariant, float>([](const QVariant& v){return v.toFloat();})); m_chai.add(chaiscript::type_conversion<QVariant, bool>([](const QVariant& v){return v.toBool();})); m_chai.add(chaiscript::type_conversion<QVariant, std::vector<QVariant> >([](const QVariant& v){ std::vector<QVariant> r; const auto seq = v.value<QSequentialIterable>(); r.reserve(1 + seq.size()); for (const auto &e : seq) r.push_back(e); return r; })); m_chai.add(chaiscript::fun([](const QVariant* v){ return v->toString().toStdString(); }), "to_string"); // m_chai.add(chaiscript::fun< std::string (void) >([](void){ // return ""; // }), "to_string"); m_chai.add(chaiscript::fun([](const QVariant* v, bool x){ return v->toBool() == x; }), "=="); m_chai.add(chaiscript::fun([](const QVariant* v, const std::string &x){ return v->toString().toStdString() == x; }), "=="); m_chai.add(chaiscript::fun([](const QVariant* v, const std::string& k){ if (v->canConvert(QMetaType::QObjectStar)) { const auto* o = v->value<QObject*>(); return o->property( k.c_str() ); } else if (v->canConvert(QMetaType::QVariantHash)) { const auto& a = v->value<QAssociativeIterable>(); return a.value(QString::fromStdString(k)); } throw std::range_error("unknown type"); }), "method_missing"); m_chai.add(chaiscript::fun([](const QVariant* v, int index)->QVariant{ if (v->canConvert(QMetaType::QVariantList)) { const auto& s = v->value<QSequentialIterable>(); if (index >= s.size()) throw std::range_error("index out of range"); return s.at(index); } throw std::range_error("unknown type"); }), "[]"); m_chai.add(chaiscript::user_type<QObject>(), "QObject"); m_chai.add(chaiscript::fun([](const QObject* o, const std::string& k){ return o->property( k.c_str() ); }), "method_missing"); m_chai.add(chaiscript::user_type<QString>(), "QString"); m_chai.add(chaiscript::type_conversion<std::string, QString>([](const std::string& v){return QString::fromStdString(v);})); } void defineTemplateApi(ChaiScriptTargetBuilderApi &templateApi) { auto module = std::make_shared<chaiscript::Module>(); chaiscript::utility::add_class<ChaiScriptTargetBuilderApi>(*module, "TwofoldTemplate", {}, { { chaiscript::fun(&ChaiScriptTargetBuilderApi::append), "append" }, { chaiscript::fun(&ChaiScriptTargetBuilderApi::newLine), "newLine" }, { chaiscript::fun(&ChaiScriptTargetBuilderApi::pushIndentation), "pushIndentation" }, { chaiscript::fun(&ChaiScriptTargetBuilderApi::popIndentation), "popIndentation" }, { chaiscript::fun(&ChaiScriptTargetBuilderApi::indentPart), "indentPart" }, { chaiscript::fun(&ChaiScriptTargetBuilderApi::pushPartIndent), "pushPartIndent" }, { chaiscript::fun(&ChaiScriptTargetBuilderApi::popPartIndent), "popPartIndent" }, } ); m_chai.add(module); m_chai.add_global(chaiscript::var(&templateApi), "_template"); } void defineInputs(const Engine::Context &inputs) { for (const auto &v : inputs) { m_chai.add_global(v.second, v.first); } } MessageHandlerPtr m_messageHandler; TextLoaderPtr m_textLoader; chaiscript::ChaiScript m_chai; }; Engine::Engine(MessageHandlerPtr messageHandler, TextLoaderPtr textLoader) : m_private(new Private(messageHandler, textLoader)) { } Engine::Engine(TextLoaderPtr textLoader, MessageHandlerPtr messageHandler) : Engine(messageHandler, textLoader) { } void Engine::showTemplateSyntaxErrors(const PreparedTemplate &) const { // auto checkResult = QScriptEngine::checkSyntax(preparedTemplate.script); // if (checkResult.state() == QScriptSyntaxCheckResult::Error) // m_private->showSyntaxError(checkResult, preparedTemplate); } Target Engine::exec(const PreparedTemplate &preparedTemplate, const Context &inputs) { return m_private->execPrepared(preparedTemplate, inputs); } PreparedTemplate Engine::prepare(const QString &templateName) const { auto prepared = m_private->createPreparedBuilder().build(templateName); this->showTemplateSyntaxErrors(prepared); return prepared; } Target Engine::execTemplateName(const QString &templateName, const Context &inputs) { auto prepared = this->prepare(templateName); return this->exec(prepared, inputs); } void Engine::PrivateDeleter::operator()(Engine::Private *p) const { delete p; } } // namespace Twofold <|endoftext|>
<commit_before>#include "TextInputWidget.hpp" #include <iostream> gsf::TextInputWidget::Ptr gsf::TextInputWidget::create(sf::Font &font) { Ptr widget{ std::make_unique<TextInputWidget>(font) }; return widget; } gsf::TextInputWidget::Ptr gsf::TextInputWidget::create(float width, float height, sf::Font &font) { Ptr widget{ std::make_unique<TextInputWidget>(width, height, font) }; return widget; } gsf::TextInputWidget::TextInputWidget(sf::Font &font) : Widget{ } //, m_text{ "", font, 12, sf::Color::Black } , m_text{ nullptr } , m_font{ font } , m_charSize{ 12 } , m_isEditable{ true } , m_cursor{ "|", font, m_charSize } , m_cursorColor{ sf::Color::Black } , m_scrollable{ nullptr } , m_acceptNewLines{ true } , m_isFocused{ false } , m_cursorPos{ 0 } , m_lBreaksBefCur{ 0 } , m_isCursorShown{ true } , m_blinkFreq{ 0.8f } , m_lastBlinkTime{ 0.f } , m_whiteListChars{ L"" } , m_blackListChars{ L"" } , m_minBreakCharCnt{ 0 } { init(); } gsf::TextInputWidget::TextInputWidget(float width, float height, sf::Font &font) : Widget{ width, height } //, m_text{ "", font, 12, sf::Color::Black } , m_text{ nullptr } , m_font{ font } , m_charSize{ 12 } , m_isEditable{ true } , m_cursor{ "|", font, m_charSize } , m_cursorColor{ sf::Color::Black } , m_scrollable{ nullptr } , m_acceptNewLines{ true } , m_isFocused{ false } , m_cursorPos{ 0 } , m_lBreaksBefCur{ 0 } , m_isCursorShown{ true } , m_blinkFreq{ 0.8f } , m_lastBlinkTime{ 0.f } , m_whiteListChars{ L"" } , m_blackListChars{ L"" } , m_minBreakCharCnt{ 0 } { init(); } void gsf::TextInputWidget::init() { std::unique_ptr<TextWidget> text{ std::make_unique<TextWidget>("", m_font, m_charSize, sf::Color::Black) }; std::unique_ptr<ScrollableWidget> scrollable{ std::make_unique<ScrollableWidget>( getWidth(), getHeight()) }; m_scrollable = scrollable.get(); m_text = text.get(); scrollable->setBackgroundColor(sf::Color::Transparent); scrollable->attachChild(std::move(text)); // Change content area so that the scrollbar fits in the TextInputWidget when // necassary. scrollable->setOnVerticalScrollNeededChangedListener( [](Widget* widget, bool isNeeded) { // Vertical Scrollbar is needed so we reduce the width of the content // area, so that the scrollbar fits in the TextInputWidget if (isNeeded) { widget->setWidth(widget->getWidth() - ScrollableWidget::SCROLLBAR_THICKNESS); } // Vertical Scrollbar is no longer so we can make the // reductoion undone else { widget->setWidth(widget->getWidth() + ScrollableWidget::SCROLLBAR_THICKNESS); } }); attachChild(std::move(scrollable)); m_cursor.setFillColor(m_cursorColor); setOutlineThickness(4.f); } void gsf::TextInputWidget::setCursorColor(sf::Color color) { m_cursorColor = color; m_cursor.setFillColor(color); } sf::Color gsf::TextInputWidget::getCursorColor() const { return m_cursorColor; } void gsf::TextInputWidget::setIsEditable(bool isEditable) { m_isEditable = isEditable; } bool gsf::TextInputWidget::isEditable() const { return m_isEditable; } void gsf::TextInputWidget::setText(const std::wstring &text) { m_currentText = text; m_text->setText(m_currentText); // Move cursor to end of text m_cursorPos = m_currentText.size(); // Adjust text so that it fits the scrollbar when horizontal scrolling is disabled adjustShownText(); m_scrollable->recalculateScroll(); m_scrollable->scrollToBottom(); m_scrollable->scrollToLeft(); } std::wstring gsf::TextInputWidget::getText() const { //return m_text->getText().toWideString(); return m_currentText; } void gsf::TextInputWidget::setCharacterSize(const unsigned int size) { m_text->setCharacterSize(size); m_charSize = size; m_cursor.setCharacterSize(size); } unsigned int gsf::TextInputWidget::getCharacterSize() const { return m_charSize; } void gsf::TextInputWidget::setTextColor(const sf::Color color) { m_text->setTextColor(color); } sf::Color gsf::TextInputWidget::getTextColor() const { return m_text->getTextColor(); } void gsf::TextInputWidget::setIsNewLineAccepted(bool isAccepted) { m_acceptNewLines = isAccepted; } bool gsf::TextInputWidget::getIsNewLineAccepted() const { return m_acceptNewLines; } bool gsf::TextInputWidget::isFocused() const { return m_isFocused; } void gsf::TextInputWidget::setIsVerticalScrollEnabled(bool isEnabled) { m_scrollable->setIsVerticalScrollEnabled(isEnabled); } bool gsf::TextInputWidget::isVerticalScrollEnabled() const { return m_scrollable->isVerticalScrollEnabled(); } void gsf::TextInputWidget::setIsHorizontalScrollEnabled(bool isEnabled) { m_scrollable->setIsHorizontalScrollEnabled(isEnabled); } bool gsf::TextInputWidget::isHorizontalScrollEnabled() const { return m_scrollable->isHorizontalScrollEnabled(); } void gsf::TextInputWidget::setIsVerticalScrollbarDrawn(bool isDrawn) { m_scrollable->setIsVerticalScrollbarDrawn(isDrawn); } void gsf::TextInputWidget::setIsHorizontalScrollbarDrawn(bool isDrawn) { m_scrollable->setIsHorizontalScrollbarDrawn(isDrawn); } std::wstring gsf::TextInputWidget::getBlackListChars() const { return m_blackListChars; } void gsf::TextInputWidget::setBlackListChars(std::wstring chars) { m_blackListChars = chars; } std::wstring gsf::TextInputWidget::getWhiteListChars() const { return m_whiteListChars; } void gsf::TextInputWidget::setWhiteListChars(std::wstring chars) { m_whiteListChars = chars; } void gsf::TextInputWidget::adjustShownText() { if (!m_scrollable->isHorizontalScrollEnabled() && m_currentText.size() > 0) { m_lBreaksBefCur = 0; m_lBreakIndexes.clear(); std::wstring shownString{ L"" }; // The chars which are in the actual line unsigned int charCntLine{ 0 }; // The total width of all chars in the current line float lineWidth{ 0.f }; for (unsigned int i{ 0 }; i < m_currentText.size(); i++) { wchar_t c{ m_currentText[i] }; // If we have a new line as char we can set the lineWidth and charCntLine // to 0 because there is no need to handle the chars in this line // (It is already handled by user width the new line char) if (c == '\n') { lineWidth = 0.f; charCntLine = 0; shownString += c; continue; } // Width of the current char float cWidth{ m_text->getWidthAndHeightOfChar(c).x }; lineWidth += cWidth; // When Text is out of scrollable widget, we have to add a new line if (lineWidth > m_scrollable->getWidth()) { if (i < m_cursorPos) { // We have to increase the "line breaks befor cursor" counter // so we add the cursor later on the right position m_lBreaksBefCur++; } //shownString += m_currentText.substr(i - charCntLine, charCntLine); // Add new line shownString += L"\n"; // Store the position (of the shown text) // where the new line was added m_lBreakIndexes.push_back(i + 1); // add the char with which the line was to wide in the new line shownString += c; // We have added the char c in the new line, // so we have now 1 char in the current line charCntLine = 1; lineWidth = cWidth; } else { charCntLine++; shownString += c; } } m_shownText = shownString; m_text->setText(m_shownText); } } void gsf::TextInputWidget::resetCursorStatus() { m_lastBlinkTime = 0.f; m_isCursorShown = true; } unsigned int gsf::TextInputWidget::getAddedLineBreaksUpToIndex (unsigned int index) const { unsigned int cnt{ 0 }; for (unsigned int lBreakIndex : m_lBreakIndexes) { if (lBreakIndex < index) { cnt++; } else { return cnt; } } return cnt; } bool gsf::TextInputWidget::handleEventCurrentAfterChildren(sf::Event &event, const sf::RenderTarget &target) { bool handled{ Widget::handleEventCurrentAfterChildren(event, target) }; if (!m_isEditable) { // Nothing to do return handled; } //bool handled{ ChildWidget::handleEvent(event) };/*|| // m_scrollable->handleEventWidget(event) };*/ // Check if actual Widget is focused if (event.type == sf::Event::MouseButtonPressed) { sf::Vector2f mousePos{ target.mapPixelToCoords({ event.mouseButton.x, event.mouseButton.y }) }; sf::Vector2f localPos{ convertToLocalPoint(mousePos) }; bool isMouseInShownArea{ getShownArea().contains(mousePos) }; bool intersecting{ isIntersecting(mousePos) }; if (isMouseInShownArea && intersecting) { m_isFocused = true; handled = true; // Put cursor to clicked postion // Get the index of the char where the mouse has clicked int clickedCharIndex{ m_text->findIndexOfCharOnPos(localPos) }; // Clicked on a char? if (clickedCharIndex > -1) { // The index is the index of m_shownText, but we need the index of // the char in m_currentText, so we have to remove the automatic // added line breaks. unsigned int autoAddedLineBreaks{ getAddedLineBreaksUpToIndex(clickedCharIndex) }; m_cursorPos = clickedCharIndex - autoAddedLineBreaks; m_lBreaksBefCur = autoAddedLineBreaks; } } else { m_isFocused = false; } } if (event.type == sf::Event::KeyPressed && m_isFocused) { switch (event.key.code) { case sf::Keyboard::Left: if (m_cursorPos > 0) { m_cursorPos--; } // when cursor is moved it should be drawn so we reset its status resetCursorStatus(); adjustShownText(); //m_cursor.setPosition( // m_text->findCharacterPos(m_cursorPos + m_lBreaksBefCur)); return true; case sf::Keyboard::Right: if (m_cursorPos < m_currentText.length()) { m_cursorPos++; } resetCursorStatus(); adjustShownText(); //m_cursor.setPosition // (m_text->findCharacterPos(m_cursorPos + m_lBreaksBefCur)); return true; default: break; } } // If Widget is focused and Text entered, handle entered text if (m_isFocused && event.type == sf::Event::TextEntered) { // To handle umlauts and other 'exotic' chars we use widestring // and wide char //std::wstring actualTxt{ m_text.getString().toWideString() }; wchar_t c{ static_cast<wchar_t>(event.text.unicode) }; std::cout << "Entered: " << c << std::endl; switch (c) { // Backspace case 8: if (m_currentText.length() > 0) { // Remove chars right of cursor when there are chars if (m_cursorPos > 0 && m_cursorPos < m_currentText.length()) { m_currentText.erase(m_cursorPos - 1, 1); m_cursorPos--; } // When cursos is at the end of the text, p // place cursor behind char which we want to delete, else if (m_cursorPos == m_currentText.length()) { // Delete last char m_currentText.pop_back(); m_cursorPos--; } } break; // Delete Pressed case 127: if (m_currentText.length() > 0 && m_cursorPos < m_currentText.length()) { m_currentText.erase(m_cursorPos, 1); } break; // Enter key case 13: // Dont add new line, when new lines are not accepted if (!m_acceptNewLines) { return false; } m_currentText.insert(m_cursorPos, L"\n"); m_cursorPos++; break; // Add char to text default: // If there are white listed chars specified, check if char is in it. // If not return if (m_whiteListChars.length() > 0 && m_whiteListChars.find(c) == std::wstring::npos) { return false; } // Check if char is black listed, if so return if(m_blackListChars.find(c) != std::wstring::npos) { return false; } m_currentText.insert(m_cursorPos, std::wstring() + c); m_cursorPos++; } resetCursorStatus(); m_shownText = m_currentText; m_text->setText(m_shownText); adjustShownText(); //m_cursor.setPosition //(m_text->findCharacterPos(m_cursorPos + m_lBreaksBefCur)); m_scrollable->recalculateScroll(); m_scrollable->scrollToRight(); m_scrollable->scrollToBottom(); return true; } return handled; } void gsf::TextInputWidget::updateCurrentAfterChildren(float dt) { if (!m_isEditable) { // Nothing to do return; } // Update cursor stuff m_lastBlinkTime += dt; if (m_lastBlinkTime >= m_blinkFreq) { m_isCursorShown = !m_isCursorShown; m_lastBlinkTime = 0.f; } m_cursor.setPosition( m_text->findGlobalCharacterPos(m_cursorPos + m_lBreaksBefCur)); //std::wstring text{ m_currentText }; //std::wstring text{ m_shownText }; //m_text->setText(text); } void gsf::TextInputWidget::drawCurrentAfterChildren(sf::RenderTarget &target, sf::RenderStates states, sf::View defaultView) const { // Draw cursor after children, so that children are not drawn over cursor if (m_isCursorShown && m_isEditable) { target.draw(m_cursor, states); } } <commit_msg>Move cursor in TextInputWidget to end f a click was not on a char<commit_after>#include "TextInputWidget.hpp" #include <iostream> gsf::TextInputWidget::Ptr gsf::TextInputWidget::create(sf::Font &font) { Ptr widget{ std::make_unique<TextInputWidget>(font) }; return widget; } gsf::TextInputWidget::Ptr gsf::TextInputWidget::create(float width, float height, sf::Font &font) { Ptr widget{ std::make_unique<TextInputWidget>(width, height, font) }; return widget; } gsf::TextInputWidget::TextInputWidget(sf::Font &font) : Widget{ } //, m_text{ "", font, 12, sf::Color::Black } , m_text{ nullptr } , m_font{ font } , m_charSize{ 12 } , m_isEditable{ true } , m_cursor{ "|", font, m_charSize } , m_cursorColor{ sf::Color::Black } , m_scrollable{ nullptr } , m_acceptNewLines{ true } , m_isFocused{ false } , m_cursorPos{ 0 } , m_lBreaksBefCur{ 0 } , m_isCursorShown{ true } , m_blinkFreq{ 0.8f } , m_lastBlinkTime{ 0.f } , m_whiteListChars{ L"" } , m_blackListChars{ L"" } , m_minBreakCharCnt{ 0 } { init(); } gsf::TextInputWidget::TextInputWidget(float width, float height, sf::Font &font) : Widget{ width, height } //, m_text{ "", font, 12, sf::Color::Black } , m_text{ nullptr } , m_font{ font } , m_charSize{ 12 } , m_isEditable{ true } , m_cursor{ "|", font, m_charSize } , m_cursorColor{ sf::Color::Black } , m_scrollable{ nullptr } , m_acceptNewLines{ true } , m_isFocused{ false } , m_cursorPos{ 0 } , m_lBreaksBefCur{ 0 } , m_isCursorShown{ true } , m_blinkFreq{ 0.8f } , m_lastBlinkTime{ 0.f } , m_whiteListChars{ L"" } , m_blackListChars{ L"" } , m_minBreakCharCnt{ 0 } { init(); } void gsf::TextInputWidget::init() { std::unique_ptr<TextWidget> text{ std::make_unique<TextWidget>("", m_font, m_charSize, sf::Color::Black) }; std::unique_ptr<ScrollableWidget> scrollable{ std::make_unique<ScrollableWidget>( getWidth(), getHeight()) }; m_scrollable = scrollable.get(); m_text = text.get(); scrollable->setBackgroundColor(sf::Color::Transparent); scrollable->attachChild(std::move(text)); // Change content area so that the scrollbar fits in the TextInputWidget when // necassary. scrollable->setOnVerticalScrollNeededChangedListener( [](Widget* widget, bool isNeeded) { // Vertical Scrollbar is needed so we reduce the width of the content // area, so that the scrollbar fits in the TextInputWidget if (isNeeded) { widget->setWidth(widget->getWidth() - ScrollableWidget::SCROLLBAR_THICKNESS); } // Vertical Scrollbar is no longer so we can make the // reductoion undone else { widget->setWidth(widget->getWidth() + ScrollableWidget::SCROLLBAR_THICKNESS); } }); attachChild(std::move(scrollable)); m_cursor.setFillColor(m_cursorColor); setOutlineThickness(4.f); } void gsf::TextInputWidget::setCursorColor(sf::Color color) { m_cursorColor = color; m_cursor.setFillColor(color); } sf::Color gsf::TextInputWidget::getCursorColor() const { return m_cursorColor; } void gsf::TextInputWidget::setIsEditable(bool isEditable) { m_isEditable = isEditable; } bool gsf::TextInputWidget::isEditable() const { return m_isEditable; } void gsf::TextInputWidget::setText(const std::wstring &text) { m_currentText = text; m_text->setText(m_currentText); // Move cursor to end of text m_cursorPos = m_currentText.size(); // Adjust text so that it fits the scrollbar when horizontal scrolling is disabled adjustShownText(); m_scrollable->recalculateScroll(); m_scrollable->scrollToBottom(); m_scrollable->scrollToLeft(); } std::wstring gsf::TextInputWidget::getText() const { //return m_text->getText().toWideString(); return m_currentText; } void gsf::TextInputWidget::setCharacterSize(const unsigned int size) { m_text->setCharacterSize(size); m_charSize = size; m_cursor.setCharacterSize(size); } unsigned int gsf::TextInputWidget::getCharacterSize() const { return m_charSize; } void gsf::TextInputWidget::setTextColor(const sf::Color color) { m_text->setTextColor(color); } sf::Color gsf::TextInputWidget::getTextColor() const { return m_text->getTextColor(); } void gsf::TextInputWidget::setIsNewLineAccepted(bool isAccepted) { m_acceptNewLines = isAccepted; } bool gsf::TextInputWidget::getIsNewLineAccepted() const { return m_acceptNewLines; } bool gsf::TextInputWidget::isFocused() const { return m_isFocused; } void gsf::TextInputWidget::setIsVerticalScrollEnabled(bool isEnabled) { m_scrollable->setIsVerticalScrollEnabled(isEnabled); } bool gsf::TextInputWidget::isVerticalScrollEnabled() const { return m_scrollable->isVerticalScrollEnabled(); } void gsf::TextInputWidget::setIsHorizontalScrollEnabled(bool isEnabled) { m_scrollable->setIsHorizontalScrollEnabled(isEnabled); } bool gsf::TextInputWidget::isHorizontalScrollEnabled() const { return m_scrollable->isHorizontalScrollEnabled(); } void gsf::TextInputWidget::setIsVerticalScrollbarDrawn(bool isDrawn) { m_scrollable->setIsVerticalScrollbarDrawn(isDrawn); } void gsf::TextInputWidget::setIsHorizontalScrollbarDrawn(bool isDrawn) { m_scrollable->setIsHorizontalScrollbarDrawn(isDrawn); } std::wstring gsf::TextInputWidget::getBlackListChars() const { return m_blackListChars; } void gsf::TextInputWidget::setBlackListChars(std::wstring chars) { m_blackListChars = chars; } std::wstring gsf::TextInputWidget::getWhiteListChars() const { return m_whiteListChars; } void gsf::TextInputWidget::setWhiteListChars(std::wstring chars) { m_whiteListChars = chars; } void gsf::TextInputWidget::adjustShownText() { if (!m_scrollable->isHorizontalScrollEnabled() && m_currentText.size() > 0) { m_lBreaksBefCur = 0; m_lBreakIndexes.clear(); std::wstring shownString{ L"" }; // The chars which are in the actual line unsigned int charCntLine{ 0 }; // The total width of all chars in the current line float lineWidth{ 0.f }; for (unsigned int i{ 0 }; i < m_currentText.size(); i++) { wchar_t c{ m_currentText[i] }; // If we have a new line as char we can set the lineWidth and charCntLine // to 0 because there is no need to handle the chars in this line // (It is already handled by user width the new line char) if (c == '\n') { lineWidth = 0.f; charCntLine = 0; shownString += c; continue; } // Width of the current char float cWidth{ m_text->getWidthAndHeightOfChar(c).x }; lineWidth += cWidth; // When Text is out of scrollable widget, we have to add a new line if (lineWidth > m_scrollable->getWidth()) { if (i < m_cursorPos) { // We have to increase the "line breaks befor cursor" counter // so we add the cursor later on the right position m_lBreaksBefCur++; } //shownString += m_currentText.substr(i - charCntLine, charCntLine); // Add new line shownString += L"\n"; // Store the position (of the shown text) // where the new line was added m_lBreakIndexes.push_back(i + 1); // add the char with which the line was to wide in the new line shownString += c; // We have added the char c in the new line, // so we have now 1 char in the current line charCntLine = 1; lineWidth = cWidth; } else { charCntLine++; shownString += c; } } m_shownText = shownString; m_text->setText(m_shownText); } } void gsf::TextInputWidget::resetCursorStatus() { m_lastBlinkTime = 0.f; m_isCursorShown = true; } unsigned int gsf::TextInputWidget::getAddedLineBreaksUpToIndex (unsigned int index) const { unsigned int cnt{ 0 }; for (unsigned int lBreakIndex : m_lBreakIndexes) { if (lBreakIndex < index) { cnt++; } else { return cnt; } } return cnt; } bool gsf::TextInputWidget::handleEventCurrentAfterChildren(sf::Event &event, const sf::RenderTarget &target) { bool handled{ Widget::handleEventCurrentAfterChildren(event, target) }; if (!m_isEditable) { // Nothing to do return handled; } //bool handled{ ChildWidget::handleEvent(event) };/*|| // m_scrollable->handleEventWidget(event) };*/ // Check if actual Widget is focused if (event.type == sf::Event::MouseButtonPressed) { sf::Vector2f mousePos{ target.mapPixelToCoords({ event.mouseButton.x, event.mouseButton.y }) }; sf::Vector2f localPos{ convertToLocalPoint(mousePos) }; bool isMouseInShownArea{ getShownArea().contains(mousePos) }; bool intersecting{ isIntersecting(mousePos) }; if (isMouseInShownArea && intersecting) { m_isFocused = true; handled = true; // Put cursor to clicked postion // Get the index of the char where the mouse has clicked int clickedCharIndex{ m_text->findIndexOfCharOnPos(localPos) }; // Clicked on a char? if (clickedCharIndex > -1) { // The index is the index of m_shownText, but we need the index of // the char in m_currentText, so we have to remove the automatic // added line breaks. unsigned int autoAddedLineBreaks{ getAddedLineBreaksUpToIndex(clickedCharIndex) }; m_cursorPos = clickedCharIndex - autoAddedLineBreaks; m_lBreaksBefCur = autoAddedLineBreaks; } // If there was no click on a char, move cursor to end else { m_cursorPos = m_shownText.length(); } } else { m_isFocused = false; } } if (event.type == sf::Event::KeyPressed && m_isFocused) { switch (event.key.code) { case sf::Keyboard::Left: if (m_cursorPos > 0) { m_cursorPos--; } // when cursor is moved it should be drawn so we reset its status resetCursorStatus(); adjustShownText(); //m_cursor.setPosition( // m_text->findCharacterPos(m_cursorPos + m_lBreaksBefCur)); return true; case sf::Keyboard::Right: if (m_cursorPos < m_currentText.length()) { m_cursorPos++; } resetCursorStatus(); adjustShownText(); //m_cursor.setPosition // (m_text->findCharacterPos(m_cursorPos + m_lBreaksBefCur)); return true; default: break; } } // If Widget is focused and Text entered, handle entered text if (m_isFocused && event.type == sf::Event::TextEntered) { // To handle umlauts and other 'exotic' chars we use widestring // and wide char //std::wstring actualTxt{ m_text.getString().toWideString() }; wchar_t c{ static_cast<wchar_t>(event.text.unicode) }; std::cout << "Entered: " << c << std::endl; switch (c) { // Backspace case 8: if (m_currentText.length() > 0) { // Remove chars right of cursor when there are chars if (m_cursorPos > 0 && m_cursorPos < m_currentText.length()) { m_currentText.erase(m_cursorPos - 1, 1); m_cursorPos--; } // When cursos is at the end of the text, p // place cursor behind char which we want to delete, else if (m_cursorPos == m_currentText.length()) { // Delete last char m_currentText.pop_back(); m_cursorPos--; } } break; // Delete Pressed case 127: if (m_currentText.length() > 0 && m_cursorPos < m_currentText.length()) { m_currentText.erase(m_cursorPos, 1); } break; // Enter key case 13: // Dont add new line, when new lines are not accepted if (!m_acceptNewLines) { return false; } m_currentText.insert(m_cursorPos, L"\n"); m_cursorPos++; break; // Add char to text default: // If there are white listed chars specified, check if char is in it. // If not return if (m_whiteListChars.length() > 0 && m_whiteListChars.find(c) == std::wstring::npos) { return false; } // Check if char is black listed, if so return if(m_blackListChars.find(c) != std::wstring::npos) { return false; } m_currentText.insert(m_cursorPos, std::wstring() + c); m_cursorPos++; } resetCursorStatus(); m_shownText = m_currentText; m_text->setText(m_shownText); adjustShownText(); //m_cursor.setPosition //(m_text->findCharacterPos(m_cursorPos + m_lBreaksBefCur)); m_scrollable->recalculateScroll(); m_scrollable->scrollToRight(); m_scrollable->scrollToBottom(); return true; } return handled; } void gsf::TextInputWidget::updateCurrentAfterChildren(float dt) { if (!m_isEditable) { // Nothing to do return; } // Update cursor stuff m_lastBlinkTime += dt; if (m_lastBlinkTime >= m_blinkFreq) { m_isCursorShown = !m_isCursorShown; m_lastBlinkTime = 0.f; } m_cursor.setPosition( m_text->findGlobalCharacterPos(m_cursorPos + m_lBreaksBefCur)); //std::wstring text{ m_currentText }; //std::wstring text{ m_shownText }; //m_text->setText(text); } void gsf::TextInputWidget::drawCurrentAfterChildren(sf::RenderTarget &target, sf::RenderStates states, sf::View defaultView) const { // Draw cursor after children, so that children are not drawn over cursor if (m_isCursorShown && m_isEditable) { target.draw(m_cursor, states); } } <|endoftext|>
<commit_before>/****************************************************************/ /* DO NOT MODIFY THIS HEADER */ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* */ /* (c) 2010 Battelle Energy Alliance, LLC */ /* ALL RIGHTS RESERVED */ /* */ /* Prepared by Battelle Energy Alliance, LLC */ /* Under Contract No. DE-AC07-05ID14517 */ /* With the U. S. Department of Energy */ /* */ /* See COPYRIGHT for full restrictions */ /****************************************************************/ #include "ComputeUserObjectsThread.h" #include "Problem.h" #include "SystemBase.h" #include "ElementUserObject.h" #include "ShapeElementUserObject.h" #include "SideUserObject.h" #include "ShapeSideUserObject.h" #include "InternalSideUserObject.h" #include "NodalUserObject.h" #include "SwapBackSentinel.h" #include "libmesh/numeric_vector.h" ComputeUserObjectsThread::ComputeUserObjectsThread(FEProblemBase & problem, SystemBase & sys, const MooseObjectWarehouse<ElementUserObject> & elemental_user_objects, const MooseObjectWarehouse<SideUserObject> & side_user_objects, const MooseObjectWarehouse<InternalSideUserObject> & internal_side_user_objects) : ThreadedElementLoop<ConstElemRange>(problem), _soln(*sys.currentSolution()), _elemental_user_objects(elemental_user_objects), _side_user_objects(side_user_objects), _internal_side_user_objects(internal_side_user_objects) { } // Splitting Constructor ComputeUserObjectsThread::ComputeUserObjectsThread(ComputeUserObjectsThread & x, Threads::split) : ThreadedElementLoop<ConstElemRange>(x._fe_problem), _soln(x._soln), _elemental_user_objects(x._elemental_user_objects), _side_user_objects(x._side_user_objects), _internal_side_user_objects(x._internal_side_user_objects) { } ComputeUserObjectsThread::~ComputeUserObjectsThread() { } void ComputeUserObjectsThread::subdomainChanged() { std::set<MooseVariable *> needed_moose_vars; _elemental_user_objects.updateBlockVariableDependency(_subdomain, needed_moose_vars, _tid); _side_user_objects.updateBoundaryVariableDependency(needed_moose_vars, _tid); _internal_side_user_objects.updateBlockVariableDependency(_subdomain, needed_moose_vars, _tid); std::set<unsigned int> needed_mat_props; _elemental_user_objects.updateBlockMatPropDependency(_subdomain, needed_mat_props, _tid); _side_user_objects.updateBoundaryMatPropDependency(needed_mat_props, _tid); _internal_side_user_objects.updateBlockMatPropDependency(_subdomain, needed_mat_props, _tid); _elemental_user_objects.subdomainSetup(_subdomain, _tid); _side_user_objects.subdomainSetup(_tid); _internal_side_user_objects.subdomainSetup(_subdomain, _tid); _fe_problem.setActiveElementalMooseVariables(needed_moose_vars, _tid); _fe_problem.setActiveMaterialProperties(needed_mat_props, _tid); _fe_problem.prepareMaterials(_subdomain, _tid); } void ComputeUserObjectsThread::onElement(const Elem * elem) { _fe_problem.prepare(elem, _tid); _fe_problem.reinitElem(elem, _tid); // Set up Sentinel class so that, even if reinitMaterials() throws, we // still remember to swap back during stack unwinding. SwapBackSentinel sentinel(_fe_problem, &FEProblem::swapBackMaterials, _tid); _fe_problem.reinitMaterials(_subdomain, _tid); if (_elemental_user_objects.hasActiveBlockObjects(_subdomain, _tid)) { const auto & objects = _elemental_user_objects.getActiveBlockObjects(_subdomain, _tid); for (const auto & uo : objects) uo->execute(); } // UserObject Jacobians if (_fe_problem.currentlyComputingJacobian()) if (_elemental_user_objects.hasActiveBlockObjects(_subdomain, _tid)) { // Prepare shape functions for ShapeElementUserObjects std::vector<MooseVariable *> jacobian_moose_vars = _fe_problem.getUserObjectJacobianVariables(_tid); for (auto & jvar : jacobian_moose_vars) { unsigned int jvar_id = jvar->number(); std::vector<dof_id_type> & dof_indices = jvar->dofIndices(); _fe_problem.prepareShapes(jvar_id, _tid); const auto & e_objects = _elemental_user_objects.getActiveBlockObjects(_subdomain, _tid); for (const auto & uo : e_objects) { std::shared_ptr<ShapeElementUserObject> shape_element_uo = std::dynamic_pointer_cast<ShapeElementUserObject>(uo); if (shape_element_uo) shape_element_uo->executeJacobianWrapper(jvar_id, dof_indices); } } } } void ComputeUserObjectsThread::onBoundary(const Elem *elem, unsigned int side, BoundaryID bnd_id) { if (_side_user_objects.hasActiveBoundaryObjects(bnd_id, _tid)) { _fe_problem.reinitElemFace(elem, side, bnd_id, _tid); // Set up Sentinel class so that, even if reinitMaterialsFace() throws, we // still remember to swap back during stack unwinding. SwapBackSentinel sentinel(_fe_problem, &FEProblem::swapBackMaterialsFace, _tid); _fe_problem.reinitMaterialsFace(_subdomain, _tid); _fe_problem.reinitMaterialsBoundary(bnd_id, _tid); _fe_problem.setCurrentBoundaryID(bnd_id); const auto & objects = _side_user_objects.getActiveBoundaryObjects(bnd_id, _tid); for (const auto & uo : objects) uo->execute(); // UserObject Jacobians if (_fe_problem.currentlyComputingJacobian()) { // Prepare shape functions for ShapeSideUserObjects std::vector<MooseVariable *> jacobian_moose_vars = _fe_problem.getUserObjectJacobianVariables(_tid); for (auto & jvar : jacobian_moose_vars) { unsigned int jvar_id = jvar->number(); std::vector<dof_id_type> & dof_indices = jvar->dofIndices(); _fe_problem.prepareFaceShapes(jvar_id, _tid); for (const auto & uo : objects) { std::shared_ptr<ShapeSideUserObject> shape_side_uo = std::dynamic_pointer_cast<ShapeSideUserObject>(uo); if (shape_side_uo) shape_side_uo->executeJacobianWrapper(jvar_id, dof_indices); } } } _fe_problem.setCurrentBoundaryID(Moose::INVALID_BOUNDARY_ID); } } void ComputeUserObjectsThread::onInternalSide(const Elem *elem, unsigned int side) { // Pointer to the neighbor we are currently working on. const Elem * neighbor = elem->neighbor(side); // Get the global id of the element and the neighbor const dof_id_type elem_id = elem->id(), neighbor_id = neighbor->id(); if (_internal_side_user_objects.hasActiveBlockObjects(_subdomain, _tid)) { if ((neighbor->active() && (neighbor->level() == elem->level()) && (elem_id < neighbor_id)) || (neighbor->level() < elem->level())) { _fe_problem.prepareFace(elem, _tid); _fe_problem.reinitNeighbor(elem, side, _tid); // Set up Sentinels so that, even if one of the reinitMaterialsXXX() calls throws, we // still remember to swap back during stack unwinding. SwapBackSentinel face_sentinel(_fe_problem, &FEProblem::swapBackMaterialsFace, _tid); _fe_problem.reinitMaterialsFace(elem->subdomain_id(), _tid); SwapBackSentinel neighbor_sentinel(_fe_problem, &FEProblem::swapBackMaterialsNeighbor, _tid); _fe_problem.reinitMaterialsNeighbor(neighbor->subdomain_id(), _tid); const auto & objects = _internal_side_user_objects.getActiveBlockObjects(_subdomain, _tid); for (const auto & uo : objects) { if (!uo->blockRestricted()) uo->execute(); else if (uo->hasBlocks(neighbor->subdomain_id())) uo->execute(); } } } } void ComputeUserObjectsThread::post() { _fe_problem.clearActiveElementalMooseVariables(_tid); _fe_problem.clearActiveMaterialProperties(_tid); } void ComputeUserObjectsThread::join(const ComputeUserObjectsThread & /*y*/) { } <commit_msg>compute thread housekeeping<commit_after>/****************************************************************/ /* DO NOT MODIFY THIS HEADER */ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* */ /* (c) 2010 Battelle Energy Alliance, LLC */ /* ALL RIGHTS RESERVED */ /* */ /* Prepared by Battelle Energy Alliance, LLC */ /* Under Contract No. DE-AC07-05ID14517 */ /* With the U. S. Department of Energy */ /* */ /* See COPYRIGHT for full restrictions */ /****************************************************************/ #include "ComputeUserObjectsThread.h" #include "Problem.h" #include "SystemBase.h" #include "ElementUserObject.h" #include "ShapeElementUserObject.h" #include "SideUserObject.h" #include "ShapeSideUserObject.h" #include "InternalSideUserObject.h" #include "NodalUserObject.h" #include "SwapBackSentinel.h" #include "libmesh/numeric_vector.h" ComputeUserObjectsThread::ComputeUserObjectsThread( FEProblemBase & problem, SystemBase & sys, const MooseObjectWarehouse<ElementUserObject> & elemental_user_objects, const MooseObjectWarehouse<SideUserObject> & side_user_objects, const MooseObjectWarehouse<InternalSideUserObject> & internal_side_user_objects) : ThreadedElementLoop<ConstElemRange>(problem), _soln(*sys.currentSolution()), _elemental_user_objects(elemental_user_objects), _side_user_objects(side_user_objects), _internal_side_user_objects(internal_side_user_objects) { } // Splitting Constructor ComputeUserObjectsThread::ComputeUserObjectsThread(ComputeUserObjectsThread & x, Threads::split) : ThreadedElementLoop<ConstElemRange>(x._fe_problem), _soln(x._soln), _elemental_user_objects(x._elemental_user_objects), _side_user_objects(x._side_user_objects), _internal_side_user_objects(x._internal_side_user_objects) { } ComputeUserObjectsThread::~ComputeUserObjectsThread() {} void ComputeUserObjectsThread::subdomainChanged() { std::set<MooseVariable *> needed_moose_vars; _elemental_user_objects.updateBlockVariableDependency(_subdomain, needed_moose_vars, _tid); _side_user_objects.updateBoundaryVariableDependency(needed_moose_vars, _tid); _internal_side_user_objects.updateBlockVariableDependency(_subdomain, needed_moose_vars, _tid); std::set<unsigned int> needed_mat_props; _elemental_user_objects.updateBlockMatPropDependency(_subdomain, needed_mat_props, _tid); _side_user_objects.updateBoundaryMatPropDependency(needed_mat_props, _tid); _internal_side_user_objects.updateBlockMatPropDependency(_subdomain, needed_mat_props, _tid); _elemental_user_objects.subdomainSetup(_subdomain, _tid); _side_user_objects.subdomainSetup(_tid); _internal_side_user_objects.subdomainSetup(_subdomain, _tid); _fe_problem.setActiveElementalMooseVariables(needed_moose_vars, _tid); _fe_problem.setActiveMaterialProperties(needed_mat_props, _tid); _fe_problem.prepareMaterials(_subdomain, _tid); } void ComputeUserObjectsThread::onElement(const Elem * elem) { _fe_problem.prepare(elem, _tid); _fe_problem.reinitElem(elem, _tid); // Set up Sentinel class so that, even if reinitMaterials() throws, we // still remember to swap back during stack unwinding. SwapBackSentinel sentinel(_fe_problem, &FEProblem::swapBackMaterials, _tid); _fe_problem.reinitMaterials(_subdomain, _tid); if (_elemental_user_objects.hasActiveBlockObjects(_subdomain, _tid)) { const auto & objects = _elemental_user_objects.getActiveBlockObjects(_subdomain, _tid); for (const auto & uo : objects) uo->execute(); } // UserObject Jacobians if (_fe_problem.currentlyComputingJacobian() && _elemental_user_objects.hasActiveBlockObjects(_subdomain, _tid)) { // Prepare shape functions for ShapeElementUserObjects std::vector<MooseVariable *> jacobian_moose_vars = _fe_problem.getUserObjectJacobianVariables(_tid); for (auto & jvar : jacobian_moose_vars) { unsigned int jvar_id = jvar->number(); std::vector<dof_id_type> & dof_indices = jvar->dofIndices(); _fe_problem.prepareShapes(jvar_id, _tid); const auto & e_objects = _elemental_user_objects.getActiveBlockObjects(_subdomain, _tid); for (const auto & uo : e_objects) { auto shape_element_uo = std::dynamic_pointer_cast<ShapeElementUserObject>(uo); if (shape_element_uo) shape_element_uo->executeJacobianWrapper(jvar_id, dof_indices); } } } } void ComputeUserObjectsThread::onBoundary(const Elem * elem, unsigned int side, BoundaryID bnd_id) { if (!_side_user_objects.hasActiveBoundaryObjects(bnd_id, _tid)) return; _fe_problem.reinitElemFace(elem, side, bnd_id, _tid); // Set up Sentinel class so that, even if reinitMaterialsFace() throws, we // still remember to swap back during stack unwinding. SwapBackSentinel sentinel(_fe_problem, &FEProblem::swapBackMaterialsFace, _tid); _fe_problem.reinitMaterialsFace(_subdomain, _tid); _fe_problem.reinitMaterialsBoundary(bnd_id, _tid); _fe_problem.setCurrentBoundaryID(bnd_id); const auto & objects = _side_user_objects.getActiveBoundaryObjects(bnd_id, _tid); for (const auto & uo : objects) uo->execute(); // UserObject Jacobians if (_fe_problem.currentlyComputingJacobian()) { // Prepare shape functions for ShapeSideUserObjects std::vector<MooseVariable *> jacobian_moose_vars = _fe_problem.getUserObjectJacobianVariables(_tid); for (auto & jvar : jacobian_moose_vars) { unsigned int jvar_id = jvar->number(); std::vector<dof_id_type> & dof_indices = jvar->dofIndices(); _fe_problem.prepareFaceShapes(jvar_id, _tid); for (const auto & uo : objects) { auto shape_side_uo = std::dynamic_pointer_cast<ShapeSideUserObject>(uo); if (shape_side_uo) shape_side_uo->executeJacobianWrapper(jvar_id, dof_indices); } } } _fe_problem.setCurrentBoundaryID(Moose::INVALID_BOUNDARY_ID); } void ComputeUserObjectsThread::onInternalSide(const Elem * elem, unsigned int side) { // Pointer to the neighbor we are currently working on. const Elem * neighbor = elem->neighbor(side); // Get the global id of the element and the neighbor const dof_id_type elem_id = elem->id(), neighbor_id = neighbor->id(); if (!_internal_side_user_objects.hasActiveBlockObjects(_subdomain, _tid)) return; if (!((neighbor->active() && (neighbor->level() == elem->level()) && (elem_id < neighbor_id)) || (neighbor->level() < elem->level()))) return; _fe_problem.prepareFace(elem, _tid); _fe_problem.reinitNeighbor(elem, side, _tid); // Set up Sentinels so that, even if one of the reinitMaterialsXXX() calls throws, we // still remember to swap back during stack unwinding. SwapBackSentinel face_sentinel(_fe_problem, &FEProblem::swapBackMaterialsFace, _tid); _fe_problem.reinitMaterialsFace(elem->subdomain_id(), _tid); SwapBackSentinel neighbor_sentinel(_fe_problem, &FEProblem::swapBackMaterialsNeighbor, _tid); _fe_problem.reinitMaterialsNeighbor(neighbor->subdomain_id(), _tid); const auto & objects = _internal_side_user_objects.getActiveBlockObjects(_subdomain, _tid); for (const auto & uo : objects) { if (!uo->blockRestricted()) uo->execute(); else if (uo->hasBlocks(neighbor->subdomain_id())) uo->execute(); } } void ComputeUserObjectsThread::post() { _fe_problem.clearActiveElementalMooseVariables(_tid); _fe_problem.clearActiveMaterialProperties(_tid); } void ComputeUserObjectsThread::join(const ComputeUserObjectsThread & /*y*/) { } <|endoftext|>
<commit_before>// Xerus - A General Purpose Tensor Library // Copyright (C) 2014-2015 Benjamin Huber and Sebastian Wolf. // // Xerus 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. // // Xerus 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 Xerus. If not, see <http://www.gnu.org/licenses/>. // // For further information on Xerus visit https://libXerus.org // or contact us at contact@libXerus.org. /** * @file * @brief Implementation of the PerformanceData class. */ #include <string> #include <fstream> #include <xerus/performanceData.h> #include <xerus/misc/missingFunctions.h> namespace xerus { PerformanceData::Histogram::Histogram(const std::vector< xerus::PerformanceData::DataPoint >& _data, const xerus::value_t _base) : base(_base), totalTime(0) { for (size_t i = 1; i<_data.size(); ++i) { if (_data[i].residual >= _data[i-1].residual) { continue; } // assume x_2 = x_1 * 2^(-alpha * delta-t) value_t relativeChange = _data[i].residual/_data[i-1].residual; value_t exponent = log(relativeChange) / log(2); size_t delta_t = _data[i].elapsedTime - _data[i-1].elapsedTime; value_t rate = - exponent / value_t(delta_t); int logRate = int(log(rate)/log(base)); buckets[logRate] += delta_t; totalTime += delta_t; } } PerformanceData::Histogram::Histogram(const xerus::value_t _base) : base(_base), totalTime(0) {} PerformanceData::Histogram PerformanceData::Histogram::operator+=(const Histogram &_other) { REQUIRE(misc::approx_equal(_other.base, base), "only histograms of identical base can be added"); for (const auto &h : _other.buckets) { buckets[h.first] += h.second; } totalTime += _other.totalTime; return *this; } PerformanceData::Histogram PerformanceData::Histogram::read_from_file(const std::string &_fileName) { std::ifstream in(_fileName); Histogram result(0.0); std::string line; std::getline(in, line); REQUIRE(line == "# raw data:", "unknown histogram file format " << _fileName); //TODO this should throw an exception char c; in >> c; REQUIRE(c == '#', "missing information in histogram file " << _fileName); in >> result.base >> result.totalTime; std::getline(in, line); // read in rest of this line std::getline(in, line); // line now contains all buckets std::stringstream bucketData(line); bucketData >> c; REQUIRE(c == '#', "missing information in histogram file " << _fileName); int bucketIndex; while (bucketData >> bucketIndex) { size_t count; if (!(bucketData >> count)) { LOG(fatal, "missing bucket count in histogram file " << _fileName); } result.buckets[bucketIndex] = count; } return result; } void PerformanceData::Histogram::dump_to_file(const std::string &_fileName) const { std::ofstream out(_fileName); out << "# raw data:\n"; out << "# " << base << ' ' << totalTime << '\n'; out << '#'; for (auto &h : buckets) { out << ' ' << h.first << ' ' << h.second; } out << "\n# plotable data:\n"; for (auto &h : buckets) { out << pow(base, h.first) << " " << double(h.second)/double(totalTime) << '\n'; } out.close(); } void PerformanceData::add(const size_t _itrCount, const xerus::value_t _residual, const std::vector<size_t> _ranks, const size_t _flags) { if (active) { if (startTime == ~0ul) { start(); } data.emplace_back(_itrCount, get_runtime(), _residual, _ranks, _flags); if(printProgress) { LOG(PerformanceData, "Iteration " << std::setw(4) << std::setfill(' ') << _itrCount << " Time: " << std::setw(6) << std::setfill(' ') << std::fixed << double(data.back().elapsedTime)*1e-6 << "s Residual: " << std::setw(11) << std::setfill(' ') << std::scientific << _residual << " Flags: " << _flags << " Ranks: " << _ranks); } } } void PerformanceData::add(const xerus::value_t _residual, const TensorNetwork::RankTuple _ranks, const size_t _flags) { if (active) { if (data.empty()) { add(0, _residual, _ranks, _flags); } else { add(data.back().iterationCount+1, _residual, _ranks, _flags); } } } void PerformanceData::dump_to_file(const std::string &_fileName) const { std::string header; header += "# "; header += additionalInformation; misc::replace(header, "\n", "\n# "); header += "\n# \n#itr \ttime[us] \tresidual \tflags \tranks...\n"; std::ofstream out(_fileName); out << header; for (const DataPoint &d : data) { out << d.iterationCount << '\t' << d.elapsedTime << '\t' << d.residual << '\t' << d.flags; for (size_t r : d.ranks) { out << '\t' << r; } out << '\n'; } out.close(); } PerformanceData::Histogram PerformanceData::get_histogram(const xerus::value_t _base) const { return Histogram(data, _base); } PerformanceData NoPerfData(false); } <commit_msg>consistency check for Histogram::read_from_file<commit_after>// Xerus - A General Purpose Tensor Library // Copyright (C) 2014-2015 Benjamin Huber and Sebastian Wolf. // // Xerus 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. // // Xerus 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 Xerus. If not, see <http://www.gnu.org/licenses/>. // // For further information on Xerus visit https://libXerus.org // or contact us at contact@libXerus.org. /** * @file * @brief Implementation of the PerformanceData class. */ #include <string> #include <fstream> #include <xerus/performanceData.h> #include <xerus/misc/missingFunctions.h> namespace xerus { PerformanceData::Histogram::Histogram(const std::vector< xerus::PerformanceData::DataPoint >& _data, const xerus::value_t _base) : base(_base), totalTime(0) { for (size_t i = 1; i<_data.size(); ++i) { if (_data[i].residual >= _data[i-1].residual) { continue; } // assume x_2 = x_1 * 2^(-alpha * delta-t) value_t relativeChange = _data[i].residual/_data[i-1].residual; value_t exponent = log(relativeChange) / log(2); size_t delta_t = _data[i].elapsedTime - _data[i-1].elapsedTime; value_t rate = - exponent / value_t(delta_t); int logRate = int(log(rate)/log(base)); buckets[logRate] += delta_t; totalTime += delta_t; } } PerformanceData::Histogram::Histogram(const xerus::value_t _base) : base(_base), totalTime(0) {} PerformanceData::Histogram PerformanceData::Histogram::operator+=(const Histogram &_other) { REQUIRE(misc::approx_equal(_other.base, base), "only histograms of identical base can be added"); for (const auto &h : _other.buckets) { buckets[h.first] += h.second; } totalTime += _other.totalTime; return *this; } PerformanceData::Histogram PerformanceData::Histogram::read_from_file(const std::string &_fileName) { std::ifstream in(_fileName); Histogram result(0.0); std::string line; std::getline(in, line); REQUIRE(line == "# raw data:", "unknown histogram file format " << _fileName); //TODO this should throw an exception char c; in >> c; REQUIRE(c == '#', "missing information in histogram file " << _fileName); in >> result.base >> result.totalTime; std::getline(in, line); // read in rest of this line std::getline(in, line); // line now contains all buckets std::stringstream bucketData(line); bucketData >> c; REQUIRE(c == '#', "missing information in histogram file " << _fileName); int bucketIndex; while (bucketData >> bucketIndex) { size_t count; if (!(bucketData >> count)) { LOG(fatal, "missing bucket count in histogram file " << _fileName); } result.buckets[bucketIndex] = count; } size_t accountedTime=0; for (auto &h : result.buckets) { accountedTime += h.second; } REQUIRE(accountedTime == result.totalTime, "histogram data inconsistent in file " << _fileName); return result; } void PerformanceData::Histogram::dump_to_file(const std::string &_fileName) const { std::ofstream out(_fileName); out << "# raw data:\n"; out << "# " << base << ' ' << totalTime << '\n'; out << '#'; for (auto &h : buckets) { out << ' ' << h.first << ' ' << h.second; } out << "\n# plotable data:\n"; for (auto &h : buckets) { out << pow(base, h.first) << " " << double(h.second)/double(totalTime) << '\n'; } out.close(); } void PerformanceData::add(const size_t _itrCount, const xerus::value_t _residual, const std::vector<size_t> _ranks, const size_t _flags) { if (active) { if (startTime == ~0ul) { start(); } data.emplace_back(_itrCount, get_runtime(), _residual, _ranks, _flags); if(printProgress) { LOG(PerformanceData, "Iteration " << std::setw(4) << std::setfill(' ') << _itrCount << " Time: " << std::setw(6) << std::setfill(' ') << std::fixed << double(data.back().elapsedTime)*1e-6 << "s Residual: " << std::setw(11) << std::setfill(' ') << std::scientific << _residual << " Flags: " << _flags << " Ranks: " << _ranks); } } } void PerformanceData::add(const xerus::value_t _residual, const TensorNetwork::RankTuple _ranks, const size_t _flags) { if (active) { if (data.empty()) { add(0, _residual, _ranks, _flags); } else { add(data.back().iterationCount+1, _residual, _ranks, _flags); } } } void PerformanceData::dump_to_file(const std::string &_fileName) const { std::string header; header += "# "; header += additionalInformation; misc::replace(header, "\n", "\n# "); header += "\n# \n#itr \ttime[us] \tresidual \tflags \tranks...\n"; std::ofstream out(_fileName); out << header; for (const DataPoint &d : data) { out << d.iterationCount << '\t' << d.elapsedTime << '\t' << d.residual << '\t' << d.flags; for (size_t r : d.ranks) { out << '\t' << r; } out << '\n'; } out.close(); } PerformanceData::Histogram PerformanceData::get_histogram(const xerus::value_t _base) const { return Histogram(data, _base); } PerformanceData NoPerfData(false); } <|endoftext|>
<commit_before><commit_msg>DevTools: wire Inspect Element action to DOMAgent-enabled inspector controller. TBR=mnaganov<commit_after><|endoftext|>
<commit_before>//* This file is part of the MOOSE framework //* https://www.mooseframework.org //* //* All rights reserved, see COPYRIGHT for full restrictions //* https://github.com/idaholab/moose/blob/master/COPYRIGHT //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html // MOOSE includes #include "ComputeElemAuxBcsThread.h" #include "AuxiliarySystem.h" #include "FEProblem.h" #include "DisplacedProblem.h" #include "Assembly.h" #include "AuxKernel.h" #include "SwapBackSentinel.h" #include "libmesh/threads.h" template <typename AuxKernelType> ComputeElemAuxBcsThread<AuxKernelType>::ComputeElemAuxBcsThread( FEProblemBase & problem, const MooseObjectWarehouse<AuxKernelType> & storage, const std::vector<std::vector<MooseVariableFEBase *>> & vars, bool need_materials) : _problem(problem), _aux_sys(problem.getAuxiliarySystem()), _storage(storage), _aux_vars(vars), _need_materials(need_materials) { } // Splitting Constructor template <typename AuxKernelType> ComputeElemAuxBcsThread<AuxKernelType>::ComputeElemAuxBcsThread(ComputeElemAuxBcsThread & x, Threads::split /*split*/) : _problem(x._problem), _aux_sys(x._aux_sys), _storage(x._storage), _aux_vars(x._aux_vars), _need_materials(x._need_materials) { } template <typename AuxKernelType> void ComputeElemAuxBcsThread<AuxKernelType>::operator()(const ConstBndElemRange & range) { ParallelUniqueId puid; _tid = puid.id; // Reference to all boundary restricted AuxKernels for the current thread const auto & boundary_kernels = _storage.getActiveBoundaryObjects(_tid); for (const auto & belem : range) { const Elem * elem = belem->_elem; unsigned short int side = belem->_side; BoundaryID boundary_id = belem->_bnd_id; // need to update the boundary ID in assembly _problem.setCurrentBoundaryID(boundary_id, _tid); if (elem->processor_id() == _problem.processor_id()) { // prepare variables for (auto * var : _aux_vars[_tid]) var->prepareAux(); // Locate the AuxKernel objects for the current BoundaryID const auto iter = boundary_kernels.find(boundary_id); if (iter != boundary_kernels.end() && !(iter->second.empty())) { _problem.setCurrentSubdomainID(elem, _tid); _problem.prepare(elem, _tid); _problem.reinitElemFace(elem, side, boundary_id, _tid); if (_need_materials) { std::set<unsigned int> needed_mat_props; for (const auto & aux : iter->second) { const std::set<unsigned int> & mp_deps = aux->getMatPropDependencies(); needed_mat_props.insert(mp_deps.begin(), mp_deps.end()); } _problem.setActiveMaterialProperties(needed_mat_props, _tid); const Elem * neighbor = elem->neighbor_ptr(side); _problem.reinitMaterialsFace(elem->subdomain_id(), _tid); if (neighbor != nullptr) if (neighbor->active()) { SwapBackSentinel neighbor_sentinel( _problem, &FEProblem::swapBackMaterialsNeighbor, _tid); _problem.reinitNeighbor(elem, side, _tid); } _problem.reinitMaterialsBoundary(boundary_id, _tid); _problem.reinitMaterialsInterface(boundary_id, _tid); } for (const auto & aux : iter->second) aux->compute(); if (_need_materials) { _problem.swapBackMaterialsFace(_tid); _problem.clearActiveMaterialProperties(_tid); } } // update the solution vector { Threads::spin_mutex::scoped_lock lock(Threads::spin_mtx); for (auto * var : _aux_vars[_tid]) var->insert(_aux_sys.solution()); } } } } template <typename AuxKernelType> void ComputeElemAuxBcsThread<AuxKernelType>::join(const ComputeElemAuxBcsThread & /*y*/) { } template class ComputeElemAuxBcsThread<AuxKernel>; template class ComputeElemAuxBcsThread<VectorAuxKernel>; <commit_msg>Dont treat InterfaceMaterials as boundary materials<commit_after>//* This file is part of the MOOSE framework //* https://www.mooseframework.org //* //* All rights reserved, see COPYRIGHT for full restrictions //* https://github.com/idaholab/moose/blob/master/COPYRIGHT //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html // MOOSE includes #include "ComputeElemAuxBcsThread.h" #include "AuxiliarySystem.h" #include "FEProblem.h" #include "DisplacedProblem.h" #include "Assembly.h" #include "AuxKernel.h" #include "SwapBackSentinel.h" #include "libmesh/threads.h" template <typename AuxKernelType> ComputeElemAuxBcsThread<AuxKernelType>::ComputeElemAuxBcsThread( FEProblemBase & problem, const MooseObjectWarehouse<AuxKernelType> & storage, const std::vector<std::vector<MooseVariableFEBase *>> & vars, bool need_materials) : _problem(problem), _aux_sys(problem.getAuxiliarySystem()), _storage(storage), _aux_vars(vars), _need_materials(need_materials) { } // Splitting Constructor template <typename AuxKernelType> ComputeElemAuxBcsThread<AuxKernelType>::ComputeElemAuxBcsThread(ComputeElemAuxBcsThread & x, Threads::split /*split*/) : _problem(x._problem), _aux_sys(x._aux_sys), _storage(x._storage), _aux_vars(x._aux_vars), _need_materials(x._need_materials) { } template <typename AuxKernelType> void ComputeElemAuxBcsThread<AuxKernelType>::operator()(const ConstBndElemRange & range) { ParallelUniqueId puid; _tid = puid.id; // Reference to all boundary restricted AuxKernels for the current thread const auto & boundary_kernels = _storage.getActiveBoundaryObjects(_tid); for (const auto & belem : range) { const Elem * elem = belem->_elem; unsigned short int side = belem->_side; BoundaryID boundary_id = belem->_bnd_id; // need to update the boundary ID in assembly _problem.setCurrentBoundaryID(boundary_id, _tid); if (elem->processor_id() == _problem.processor_id()) { // prepare variables for (auto * var : _aux_vars[_tid]) var->prepareAux(); // Locate the AuxKernel objects for the current BoundaryID const auto iter = boundary_kernels.find(boundary_id); if (iter != boundary_kernels.end() && !(iter->second.empty())) { _problem.setCurrentSubdomainID(elem, _tid); _problem.prepare(elem, _tid); _problem.reinitElemFace(elem, side, boundary_id, _tid); if (_need_materials) { std::set<unsigned int> needed_mat_props; for (const auto & aux : iter->second) { const std::set<unsigned int> & mp_deps = aux->getMatPropDependencies(); needed_mat_props.insert(mp_deps.begin(), mp_deps.end()); } _problem.setActiveMaterialProperties(needed_mat_props, _tid); const Elem * neighbor = elem->neighbor_ptr(side); _problem.reinitMaterialsFace(elem->subdomain_id(), _tid); if (neighbor != nullptr) if (neighbor->active()) { SwapBackSentinel neighbor_sentinel( _problem, &FEProblem::swapBackMaterialsNeighbor, _tid); _problem.reinitNeighbor(elem, side, _tid); } _problem.reinitMaterialsBoundary(boundary_id, _tid); // We need to think about whether it makes sense to do interface materials here because in // order for them to function properly we would also need to reinit materials on the // neighboring element face. That just doesn't seem appropriate // _problem.reinitMaterialsInterface(boundary_id, _tid); } for (const auto & aux : iter->second) aux->compute(); if (_need_materials) { _problem.swapBackMaterialsFace(_tid); _problem.clearActiveMaterialProperties(_tid); } } // update the solution vector { Threads::spin_mutex::scoped_lock lock(Threads::spin_mtx); for (auto * var : _aux_vars[_tid]) var->insert(_aux_sys.solution()); } } } } template <typename AuxKernelType> void ComputeElemAuxBcsThread<AuxKernelType>::join(const ComputeElemAuxBcsThread & /*y*/) { } template class ComputeElemAuxBcsThread<AuxKernel>; template class ComputeElemAuxBcsThread<VectorAuxKernel>; <|endoftext|>
<commit_before>/** * \file * * \date 3 Jul 2013 * \author Ben Gray (\@benjamg) */ #ifndef ZMQPP_CONTEXT_OPTIONS_HPP_ #define ZMQPP_CONTEXT_OPTIONS_HPP_ namespace zmqpp { /** \todo Expand the information on the options to make it actually useful. */ /*! * \brief possible Context options in zmq */ enum class context_option { io_threads = ZMQ_IO_THREADS, /*!< I/O thread count */ max_sockets = ZMQ_MAX_SOCKETS, /*!< Maximum supported sockets */ }; } #endif /* ZMQPP_CONTEXT_OPTIONS_HPP_ */ <commit_msg>Added ipv6 flag for cool people<commit_after>/** * \file * * \date 3 Jul 2013 * \author Ben Gray (\@benjamg) */ #ifndef ZMQPP_CONTEXT_OPTIONS_HPP_ #define ZMQPP_CONTEXT_OPTIONS_HPP_ namespace zmqpp { /** \todo Expand the information on the options to make it actually useful. */ /*! * \brief possible Context options in zmq */ enum class context_option { io_threads = ZMQ_IO_THREADS, /*!< I/O thread count */ max_sockets = ZMQ_MAX_SOCKETS, /*!< Maximum supported sockets */ #if (ZMQ_VERSION_MAJOR >= 4) ipv6 = ZMQ_IPV6, /*!< IPv6 support */ #endif }; } #endif /* ZMQPP_CONTEXT_OPTIONS_HPP_ */ <|endoftext|>
<commit_before>// -*- c++ -*- /*! * This file is part of CameraPlus. * * Copyright (C) 2012-2013 Mohammed Sameer <msameer@foolab.org> * * 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 "viewfinder.h" #include "camera.h" #include "cameraconfig.h" #include "qtcamviewfinderrenderer.h" #if defined(QT4) #include <QDeclarativeInfo> #elif defined(QT5) #include <QQmlInfo> #endif #include <QPainter> #include "qtcamdevice.h" #include <QMatrix4x4> #if defined(QT4) Viewfinder::Viewfinder(QDeclarativeItem *parent) : QDeclarativeItem(parent), #elif defined(QT5) Viewfinder::Viewfinder(QQuickItem *parent) : QQuickPaintedItem(parent), #endif m_renderer(0), m_cam(0), m_conf(0), m_dev(0), m_enabled(true) { #if defined(QT4) setFlag(QGraphicsItem::ItemHasNoContents, false); #endif #if defined(QT5) setRenderTarget(QQuickPaintedItem::FramebufferObject); setSmooth(false); setAntialiasing(false); #endif } Viewfinder::~Viewfinder() { } bool Viewfinder::isRenderingEnabled() const { return m_enabled; } void Viewfinder::setRenderingEnabled(bool enabled) { if (m_enabled != enabled) { m_enabled = enabled; emit renderingEnabledChanged(); } } Camera *Viewfinder::camera() const { return m_cam; } void Viewfinder::setCamera(Camera *camera) { if (m_cam == camera) { return; } if (m_cam && m_cam != camera) { qmlInfo(this) << "Cannot reset Camera"; return; } if (!camera) { qmlInfo(this) << "Camera cannot be empty"; return; } if (m_cam) { QObject::disconnect(m_cam, SIGNAL(deviceChanged()), this, SLOT(deviceChanged())); QObject::disconnect(m_cam, SIGNAL(prepareForDeviceChange()), this, SLOT(prepareForDeviceChange())); } m_cam = camera; if (m_cam) { QObject::connect(m_cam, SIGNAL(deviceChanged()), this, SLOT(deviceChanged())); QObject::connect(m_cam, SIGNAL(prepareForDeviceChange()), this, SLOT(prepareForDeviceChange())); } if (isComponentComplete()) { deviceChanged(); } emit cameraChanged(); } CameraConfig *Viewfinder::cameraConfig() const { return m_conf; } void Viewfinder::setCameraConfig(CameraConfig *config) { if (m_conf && m_conf != config) { qmlInfo(this) << "Cannot reset CameraConfig"; return; } if (!config) { qmlInfo(this) << "CameraConfig cannot be empty"; return; } if (m_conf == config) { return; } m_conf = config; if (isComponentComplete()) { deviceChanged(); } emit cameraConfigChanged(); } #if defined(QT4) void Viewfinder::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { Q_UNUSED(widget); Q_UNUSED(option); painter->fillRect(boundingRect(), Qt::black); #elif defined(QT5) void Viewfinder::paint(QPainter *painter) { painter->fillRect(contentsBoundingRect(), Qt::black); #endif if (!m_renderer || !m_enabled) { return; } bool needsNativePainting = m_renderer->needsNativePainting(); if (needsNativePainting) { painter->beginNativePainting(); } m_renderer->paint(QMatrix4x4(painter->combinedTransform()), painter->viewport()); if (needsNativePainting) { painter->endNativePainting(); } } QRectF Viewfinder::renderArea() const { return m_renderer ? m_renderer->renderArea() : QRectF(); } QSizeF Viewfinder::videoResolution() const { return m_renderer ? m_renderer->videoResolution() : QSizeF(); } void Viewfinder::geometryChanged(const QRectF& newGeometry, const QRectF& oldGeometry) { #if defined(QT4) QDeclarativeItem::geometryChanged(newGeometry, oldGeometry); #elif defined(QT5) QQuickPaintedItem::geometryChanged(newGeometry, oldGeometry); #endif if (m_renderer) { m_renderer->resize(newGeometry.size()); } } void Viewfinder::componentComplete() { #if defined(QT4) QDeclarativeItem::componentComplete(); #elif defined(QT5) QQuickPaintedItem::componentComplete(); #endif if (!m_cam) { qmlInfo(this) << "Camera not set"; return; } if (!m_conf) { qmlInfo(this) << "CameraConfig not set"; return; } m_renderer = QtCamViewfinderRenderer::create(m_conf->config(), this); if (!m_renderer) { qmlInfo(this) << "Failed to create viewfinder renderer"; return; } m_renderer->resize(QSizeF(width(), height())); QObject::connect(m_renderer, SIGNAL(updateRequested()), this, SLOT(updateRequested())); QObject::connect(m_renderer, SIGNAL(renderAreaChanged()), this, SIGNAL(renderAreaChanged())); QObject::connect(m_renderer, SIGNAL(videoResolutionChanged()), this, SIGNAL(videoResolutionChanged())); } void Viewfinder::deviceChanged() { if (!m_renderer) { qmlInfo(this) << "No renderer"; return; } if (m_dev) { qmlInfo(this) << "Cannot set a new device without cleaning up the existing one"; abort(); } m_dev = m_cam->device(); if (m_dev) { m_dev->setViewfinder(this); } emit renderAreaChanged(); emit videoResolutionChanged(); } GstElement *Viewfinder::sinkElement() { return m_renderer ? m_renderer->sinkElement() : 0; } void Viewfinder::stop() { if (m_renderer) { m_renderer->reset(); } } void Viewfinder::updateRequested() { if (m_enabled) { update(); } } void Viewfinder::prepareForDeviceChange() { if (m_dev) { m_dev->setViewfinder(0); m_dev = 0; } } <commit_msg>Unset QtCamdevice viewfinder when Viewfinder is being destructed.<commit_after>// -*- c++ -*- /*! * This file is part of CameraPlus. * * Copyright (C) 2012-2013 Mohammed Sameer <msameer@foolab.org> * * 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 "viewfinder.h" #include "camera.h" #include "cameraconfig.h" #include "qtcamviewfinderrenderer.h" #if defined(QT4) #include <QDeclarativeInfo> #elif defined(QT5) #include <QQmlInfo> #endif #include <QPainter> #include "qtcamdevice.h" #include <QMatrix4x4> #if defined(QT4) Viewfinder::Viewfinder(QDeclarativeItem *parent) : QDeclarativeItem(parent), #elif defined(QT5) Viewfinder::Viewfinder(QQuickItem *parent) : QQuickPaintedItem(parent), #endif m_renderer(0), m_cam(0), m_conf(0), m_dev(0), m_enabled(true) { #if defined(QT4) setFlag(QGraphicsItem::ItemHasNoContents, false); #endif #if defined(QT5) setRenderTarget(QQuickPaintedItem::FramebufferObject); setSmooth(false); setAntialiasing(false); #endif } Viewfinder::~Viewfinder() { if (m_cam) { m_cam->stop(true); } if (m_dev) { m_dev->setViewfinder(0); } } bool Viewfinder::isRenderingEnabled() const { return m_enabled; } void Viewfinder::setRenderingEnabled(bool enabled) { if (m_enabled != enabled) { m_enabled = enabled; emit renderingEnabledChanged(); } } Camera *Viewfinder::camera() const { return m_cam; } void Viewfinder::setCamera(Camera *camera) { if (m_cam == camera) { return; } if (m_cam && m_cam != camera) { qmlInfo(this) << "Cannot reset Camera"; return; } if (!camera) { qmlInfo(this) << "Camera cannot be empty"; return; } if (m_cam) { QObject::disconnect(m_cam, SIGNAL(deviceChanged()), this, SLOT(deviceChanged())); QObject::disconnect(m_cam, SIGNAL(prepareForDeviceChange()), this, SLOT(prepareForDeviceChange())); } m_cam = camera; if (m_cam) { QObject::connect(m_cam, SIGNAL(deviceChanged()), this, SLOT(deviceChanged())); QObject::connect(m_cam, SIGNAL(prepareForDeviceChange()), this, SLOT(prepareForDeviceChange())); } if (isComponentComplete()) { deviceChanged(); } emit cameraChanged(); } CameraConfig *Viewfinder::cameraConfig() const { return m_conf; } void Viewfinder::setCameraConfig(CameraConfig *config) { if (m_conf && m_conf != config) { qmlInfo(this) << "Cannot reset CameraConfig"; return; } if (!config) { qmlInfo(this) << "CameraConfig cannot be empty"; return; } if (m_conf == config) { return; } m_conf = config; if (isComponentComplete()) { deviceChanged(); } emit cameraConfigChanged(); } #if defined(QT4) void Viewfinder::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { Q_UNUSED(widget); Q_UNUSED(option); painter->fillRect(boundingRect(), Qt::black); #elif defined(QT5) void Viewfinder::paint(QPainter *painter) { painter->fillRect(contentsBoundingRect(), Qt::black); #endif if (!m_renderer || !m_enabled) { return; } bool needsNativePainting = m_renderer->needsNativePainting(); if (needsNativePainting) { painter->beginNativePainting(); } m_renderer->paint(QMatrix4x4(painter->combinedTransform()), painter->viewport()); if (needsNativePainting) { painter->endNativePainting(); } } QRectF Viewfinder::renderArea() const { return m_renderer ? m_renderer->renderArea() : QRectF(); } QSizeF Viewfinder::videoResolution() const { return m_renderer ? m_renderer->videoResolution() : QSizeF(); } void Viewfinder::geometryChanged(const QRectF& newGeometry, const QRectF& oldGeometry) { #if defined(QT4) QDeclarativeItem::geometryChanged(newGeometry, oldGeometry); #elif defined(QT5) QQuickPaintedItem::geometryChanged(newGeometry, oldGeometry); #endif if (m_renderer) { m_renderer->resize(newGeometry.size()); } } void Viewfinder::componentComplete() { #if defined(QT4) QDeclarativeItem::componentComplete(); #elif defined(QT5) QQuickPaintedItem::componentComplete(); #endif if (!m_cam) { qmlInfo(this) << "Camera not set"; return; } if (!m_conf) { qmlInfo(this) << "CameraConfig not set"; return; } m_renderer = QtCamViewfinderRenderer::create(m_conf->config(), this); if (!m_renderer) { qmlInfo(this) << "Failed to create viewfinder renderer"; return; } m_renderer->resize(QSizeF(width(), height())); QObject::connect(m_renderer, SIGNAL(updateRequested()), this, SLOT(updateRequested())); QObject::connect(m_renderer, SIGNAL(renderAreaChanged()), this, SIGNAL(renderAreaChanged())); QObject::connect(m_renderer, SIGNAL(videoResolutionChanged()), this, SIGNAL(videoResolutionChanged())); } void Viewfinder::deviceChanged() { if (!m_renderer) { qmlInfo(this) << "No renderer"; return; } if (m_dev) { qmlInfo(this) << "Cannot set a new device without cleaning up the existing one"; abort(); } m_dev = m_cam->device(); if (m_dev) { m_dev->setViewfinder(this); } emit renderAreaChanged(); emit videoResolutionChanged(); } GstElement *Viewfinder::sinkElement() { return m_renderer ? m_renderer->sinkElement() : 0; } void Viewfinder::stop() { if (m_renderer) { m_renderer->reset(); } } void Viewfinder::updateRequested() { if (m_enabled) { update(); } } void Viewfinder::prepareForDeviceChange() { if (m_dev) { m_dev->setViewfinder(0); m_dev = 0; } } <|endoftext|>
<commit_before>#ifndef STAN_MATH_PRIM_FUN_LGAMMA_HPP #define STAN_MATH_PRIM_FUN_LGAMMA_HPP /** * The lgamma implementation in stan-math is based on either the * reentrant safe lgamma_r implementation from C or the * boost::math::lgamma implementation. The reentrant safe lgamma_r * implementation is preferred as it is faster when compared to the * boost version. However, the reentrant safe lgamma_r C function is * not available with MinGW compilers used on Windows. Therefore, the * boost version is used on Windows with MinGW compilers as fall * back. For details on the speed evaluations, please refer to * https://github.com/stan-dev/math/pull/1255 . */ #if !__MINGW32__ || !_BOOST_LGAMMA // _REENTRANT must be defined during compilation to ensure that cmath // exports the reentrant safe lgamma_r version. #if !_REENTRANT #error \ "stan-math requires _REENTRANT being defined during compilation" \ "to make lgamma_r available." #endif #include <cmath> #else // MinGW compilers on Windows do not provide the reentrant lgamma_r // such that we fall back to boost whenever we are on MinGW. #include <stan/math/prim/fun/boost_policy.hpp> #include <boost/math/special_functions/gamma.hpp> #include <limits> #endif #include <stan/math/prim/meta.hpp> #include <stan/math/prim/functor/apply_scalar_unary.hpp> namespace stan { namespace math { /** * Return the natural logarithm of the gamma function applied to * the specified argument. * \f[ \mbox{lgamma}(x) = \begin{cases} \textrm{error} & \mbox{if } x\in \{\dots, -3, -2, -1, 0\}\\ \ln\Gamma(x) & \mbox{if } x\not\in \{\dots, -3, -2, -1, 0\}\\[6pt] \textrm{NaN} & \mbox{if } x = \textrm{NaN} \end{cases} \f] \f[ \frac{\partial\, \mbox{lgamma}(x)}{\partial x} = \begin{cases} \textrm{error} & \mbox{if } x\in \{\dots, -3, -2, -1, 0\}\\ \Psi(x) & \mbox{if } x\not\in \{\dots, -3, -2, -1, 0\}\\[6pt] \textrm{NaN} & \mbox{if } x = \textrm{NaN} \end{cases} \f] * * @param x argument * @return natural logarithm of the gamma function applied to * argument */ inline double lgamma(double x) { #if !__MINGW32__ || !_BOOST_LGAMMA int sign = 1; return ::lgamma_r(x, &sign); #else if (unlikely(x == 0.0)) return std::numeric_limits<double>::infinity(); return boost::math::lgamma(x, boost_policy_t<>()); #endif } /** * Return the natural logarithm of the gamma function applied * to the specified argument. * * @param x argument * @return natural logarithm of the gamma function applied to * argument */ inline double lgamma(int x) { #if !__MINGW32__ || !_BOOST_LGAMMA int sign = 1; return ::lgamma_r(x, &sign); #else if (unlikely(x == 0.0)) return std::numeric_limits<double>::infinity(); return boost::math::lgamma(x, boost_policy_t<>()); #endif } /** * Structure to wrap lgamma() so that it can be vectorized. * * @tparam T type of variable * @param x variable * @return Natural log of the gamma function applied to x. * @throw std::domain_error if x is a negative integer or 0. */ struct lgamma_fun { template <typename T> static inline T fun(const T& x) { return lgamma(x); } }; /** * Vectorized version of lgamma(). * * @tparam T type of container * @param x container * @return Natural log of the gamma function * applied to each value in x. * @throw std::domain_error if any value is a negative integer or 0. */ template <typename T, require_not_var_matrix_t<T>* = nullptr, require_not_nonscalar_prim_or_rev_kernel_expression_t<T>* = nullptr> inline auto lgamma(const T& x) { return apply_scalar_unary<lgamma_fun, T>::apply(x); } } // namespace math } // namespace stan #endif <commit_msg>Wrong logic<commit_after>#ifndef STAN_MATH_PRIM_FUN_LGAMMA_HPP #define STAN_MATH_PRIM_FUN_LGAMMA_HPP /** * The lgamma implementation in stan-math is based on either the * reentrant safe lgamma_r implementation from C or the * boost::math::lgamma implementation. The reentrant safe lgamma_r * implementation is preferred as it is faster when compared to the * boost version. However, the reentrant safe lgamma_r C function is * not available with MinGW compilers used on Windows. Therefore, the * boost version is used on Windows with MinGW compilers as fall * back. For details on the speed evaluations, please refer to * https://github.com/stan-dev/math/pull/1255 . */ #if !__MINGW32__ && !_BOOST_LGAMMA // _REENTRANT must be defined during compilation to ensure that cmath // exports the reentrant safe lgamma_r version. #if !_REENTRANT #error \ "stan-math requires _REENTRANT being defined during compilation" \ "to make lgamma_r available." #endif #include <cmath> #else // MinGW compilers on Windows do not provide the reentrant lgamma_r // such that we fall back to boost whenever we are on MinGW. #include <stan/math/prim/fun/boost_policy.hpp> #include <boost/math/special_functions/gamma.hpp> #include <limits> #endif #include <stan/math/prim/meta.hpp> #include <stan/math/prim/functor/apply_scalar_unary.hpp> namespace stan { namespace math { /** * Return the natural logarithm of the gamma function applied to * the specified argument. * \f[ \mbox{lgamma}(x) = \begin{cases} \textrm{error} & \mbox{if } x\in \{\dots, -3, -2, -1, 0\}\\ \ln\Gamma(x) & \mbox{if } x\not\in \{\dots, -3, -2, -1, 0\}\\[6pt] \textrm{NaN} & \mbox{if } x = \textrm{NaN} \end{cases} \f] \f[ \frac{\partial\, \mbox{lgamma}(x)}{\partial x} = \begin{cases} \textrm{error} & \mbox{if } x\in \{\dots, -3, -2, -1, 0\}\\ \Psi(x) & \mbox{if } x\not\in \{\dots, -3, -2, -1, 0\}\\[6pt] \textrm{NaN} & \mbox{if } x = \textrm{NaN} \end{cases} \f] * * @param x argument * @return natural logarithm of the gamma function applied to * argument */ inline double lgamma(double x) { #if !__MINGW32__ && !_BOOST_LGAMMA int sign = 1; return ::lgamma_r(x, &sign); #else if (unlikely(x == 0.0)) return std::numeric_limits<double>::infinity(); return boost::math::lgamma(x, boost_policy_t<>()); #endif } /** * Return the natural logarithm of the gamma function applied * to the specified argument. * * @param x argument * @return natural logarithm of the gamma function applied to * argument */ inline double lgamma(int x) { #if !__MINGW32__ && !_BOOST_LGAMMA int sign = 1; return ::lgamma_r(x, &sign); #else if (unlikely(x == 0.0)) return std::numeric_limits<double>::infinity(); return boost::math::lgamma(x, boost_policy_t<>()); #endif } /** * Structure to wrap lgamma() so that it can be vectorized. * * @tparam T type of variable * @param x variable * @return Natural log of the gamma function applied to x. * @throw std::domain_error if x is a negative integer or 0. */ struct lgamma_fun { template <typename T> static inline T fun(const T& x) { return lgamma(x); } }; /** * Vectorized version of lgamma(). * * @tparam T type of container * @param x container * @return Natural log of the gamma function * applied to each value in x. * @throw std::domain_error if any value is a negative integer or 0. */ template <typename T, require_not_var_matrix_t<T>* = nullptr, require_not_nonscalar_prim_or_rev_kernel_expression_t<T>* = nullptr> inline auto lgamma(const T& x) { return apply_scalar_unary<lgamma_fun, T>::apply(x); } } // namespace math } // namespace stan #endif <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * 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/. */ #include <memory> #include <unotools/mediadescriptor.hxx> #include <unotools/ucbstreamhelper.hxx> #include <document.hxx> #include <mathtype.hxx> #include <unomodel.hxx> using namespace ::com::sun::star; /// Invokes the MathType importer via UNO. class MathTypeFilter : public cppu::WeakImplHelper < document::XFilter, document::XImporter, lang::XServiceInfo > { uno::Reference<uno::XComponentContext> m_xContext; uno::Reference<lang::XComponent> m_xDstDoc; public: MathTypeFilter(const uno::Reference<uno::XComponentContext>& xContext); virtual ~MathTypeFilter(); // XFilter virtual sal_Bool SAL_CALL filter(const uno::Sequence<beans::PropertyValue>& rDescriptor) throw (uno::RuntimeException, std::exception) SAL_OVERRIDE; virtual void SAL_CALL cancel() throw (uno::RuntimeException, std::exception) SAL_OVERRIDE; // XImporter virtual void SAL_CALL setTargetDocument(const uno::Reference<lang::XComponent>& xDoc) throw (lang::IllegalArgumentException, uno::RuntimeException, std::exception) SAL_OVERRIDE; // XServiceInfo virtual OUString SAL_CALL getImplementationName() throw (uno::RuntimeException, std::exception) SAL_OVERRIDE; virtual sal_Bool SAL_CALL supportsService(const OUString& ServiceName) throw (uno::RuntimeException, std::exception) SAL_OVERRIDE; virtual uno::Sequence<OUString> SAL_CALL getSupportedServiceNames() throw (uno::RuntimeException, std::exception) SAL_OVERRIDE; }; MathTypeFilter::MathTypeFilter(const uno::Reference< uno::XComponentContext >& rxContext) : m_xContext(rxContext) { } MathTypeFilter::~MathTypeFilter() { } sal_Bool MathTypeFilter::filter(const uno::Sequence<beans::PropertyValue>& rDescriptor) throw(uno::RuntimeException, std::exception) { bool bSuccess = false; try { utl::MediaDescriptor aMediaDesc(rDescriptor); aMediaDesc.addInputStream(); uno::Reference<io::XInputStream> xInputStream; aMediaDesc[utl::MediaDescriptor::PROP_INPUTSTREAM()] >>= xInputStream; std::unique_ptr<SvStream> pStream(utl::UcbStreamHelper::CreateStream(xInputStream)); if (pStream) { if (SotStorage::IsStorageFile(pStream.get())) { tools::SvRef<SotStorage> aStorage(new SotStorage(pStream.get(), false)); // Is this a MathType Storage? if (aStorage->IsStream(OUString("Equation Native"))) { if (SmModel* pModel = dynamic_cast<SmModel*>(m_xDstDoc.get())) { SmDocShell* pDocShell = static_cast<SmDocShell*>(pModel->GetObjectShell()); OUString aText = pDocShell->GetText(); MathType aEquation(aText); bSuccess = aEquation.Parse(aStorage) == 1; if (bSuccess) { pDocShell->SetText(aText); pDocShell->Parse(); } } } } } } catch (const uno::Exception& rException) { SAL_WARN("starmath", "Exception caught: " << rException.Message); } return bSuccess; } void MathTypeFilter::cancel() throw(uno::RuntimeException, std::exception) { } void MathTypeFilter::setTargetDocument(const uno::Reference< lang::XComponent >& xDoc) throw(lang::IllegalArgumentException, uno::RuntimeException, std::exception) { m_xDstDoc = xDoc; } OUString MathTypeFilter::getImplementationName() throw(uno::RuntimeException, std::exception) { return OUString("com.sun.star.comp.Math.MathTypeFilter"); } sal_Bool MathTypeFilter::supportsService(const OUString& rServiceName) throw(uno::RuntimeException, std::exception) { return cppu::supportsService(this, rServiceName); } uno::Sequence<OUString> MathTypeFilter::getSupportedServiceNames() throw(uno::RuntimeException, std::exception) { uno::Sequence<OUString> aRet = { OUString("com.sun.star.document.ImportFilter") }; return aRet; } extern "C" SAL_DLLPUBLIC_EXPORT uno::XInterface* SAL_CALL com_sun_star_comp_Math_MathTypeFilter_get_implementation(uno::XComponentContext* pComponent, uno::Sequence<uno::Any> const&) { return cppu::acquire(new MathTypeFilter(pComponent)); } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>cppcheck: noExplicitConstructor<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * 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/. */ #include <memory> #include <unotools/mediadescriptor.hxx> #include <unotools/ucbstreamhelper.hxx> #include <document.hxx> #include <mathtype.hxx> #include <unomodel.hxx> using namespace ::com::sun::star; /// Invokes the MathType importer via UNO. class MathTypeFilter : public cppu::WeakImplHelper < document::XFilter, document::XImporter, lang::XServiceInfo > { uno::Reference<uno::XComponentContext> m_xContext; uno::Reference<lang::XComponent> m_xDstDoc; public: explicit MathTypeFilter(const uno::Reference<uno::XComponentContext>& xContext); virtual ~MathTypeFilter(); // XFilter virtual sal_Bool SAL_CALL filter(const uno::Sequence<beans::PropertyValue>& rDescriptor) throw (uno::RuntimeException, std::exception) SAL_OVERRIDE; virtual void SAL_CALL cancel() throw (uno::RuntimeException, std::exception) SAL_OVERRIDE; // XImporter virtual void SAL_CALL setTargetDocument(const uno::Reference<lang::XComponent>& xDoc) throw (lang::IllegalArgumentException, uno::RuntimeException, std::exception) SAL_OVERRIDE; // XServiceInfo virtual OUString SAL_CALL getImplementationName() throw (uno::RuntimeException, std::exception) SAL_OVERRIDE; virtual sal_Bool SAL_CALL supportsService(const OUString& ServiceName) throw (uno::RuntimeException, std::exception) SAL_OVERRIDE; virtual uno::Sequence<OUString> SAL_CALL getSupportedServiceNames() throw (uno::RuntimeException, std::exception) SAL_OVERRIDE; }; MathTypeFilter::MathTypeFilter(const uno::Reference< uno::XComponentContext >& rxContext) : m_xContext(rxContext) { } MathTypeFilter::~MathTypeFilter() { } sal_Bool MathTypeFilter::filter(const uno::Sequence<beans::PropertyValue>& rDescriptor) throw(uno::RuntimeException, std::exception) { bool bSuccess = false; try { utl::MediaDescriptor aMediaDesc(rDescriptor); aMediaDesc.addInputStream(); uno::Reference<io::XInputStream> xInputStream; aMediaDesc[utl::MediaDescriptor::PROP_INPUTSTREAM()] >>= xInputStream; std::unique_ptr<SvStream> pStream(utl::UcbStreamHelper::CreateStream(xInputStream)); if (pStream) { if (SotStorage::IsStorageFile(pStream.get())) { tools::SvRef<SotStorage> aStorage(new SotStorage(pStream.get(), false)); // Is this a MathType Storage? if (aStorage->IsStream(OUString("Equation Native"))) { if (SmModel* pModel = dynamic_cast<SmModel*>(m_xDstDoc.get())) { SmDocShell* pDocShell = static_cast<SmDocShell*>(pModel->GetObjectShell()); OUString aText = pDocShell->GetText(); MathType aEquation(aText); bSuccess = aEquation.Parse(aStorage) == 1; if (bSuccess) { pDocShell->SetText(aText); pDocShell->Parse(); } } } } } } catch (const uno::Exception& rException) { SAL_WARN("starmath", "Exception caught: " << rException.Message); } return bSuccess; } void MathTypeFilter::cancel() throw(uno::RuntimeException, std::exception) { } void MathTypeFilter::setTargetDocument(const uno::Reference< lang::XComponent >& xDoc) throw(lang::IllegalArgumentException, uno::RuntimeException, std::exception) { m_xDstDoc = xDoc; } OUString MathTypeFilter::getImplementationName() throw(uno::RuntimeException, std::exception) { return OUString("com.sun.star.comp.Math.MathTypeFilter"); } sal_Bool MathTypeFilter::supportsService(const OUString& rServiceName) throw(uno::RuntimeException, std::exception) { return cppu::supportsService(this, rServiceName); } uno::Sequence<OUString> MathTypeFilter::getSupportedServiceNames() throw(uno::RuntimeException, std::exception) { uno::Sequence<OUString> aRet = { OUString("com.sun.star.document.ImportFilter") }; return aRet; } extern "C" SAL_DLLPUBLIC_EXPORT uno::XInterface* SAL_CALL com_sun_star_comp_Math_MathTypeFilter_get_implementation(uno::XComponentContext* pComponent, uno::Sequence<uno::Any> const&) { return cppu::acquire(new MathTypeFilter(pComponent)); } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/* Copyright (c) 2014 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /** * @file mc_att_control_base.cpp * * MC Attitude Controller : Control and math code * * @author Tobias Naegeli <naegelit@student.ethz.ch> * @author Lorenz Meier <lm@inf.ethz.ch> * @author Anton Babushkin <anton.babushkin@me.com> * @author Thomas Gubler <thomasgubler@gmail.com> * @author Julian Oes <julian@oes.ch> * @author Roman Bapst <bapstr@ethz.ch> * */ #include "mc_att_control_base.h" #include <geo/geo.h> #include <math.h> #include <lib/mathlib/mathlib.h> #ifdef CONFIG_ARCH_ARM #else #include <cmath> using namespace std; #endif MulticopterAttitudeControlBase::MulticopterAttitudeControlBase() : _v_att_sp_mod(), _v_rates_sp_mod(), _actuators(), _publish_att_sp(false) { _params.att_p.zero(); _params.rate_p.zero(); _params.rate_i.zero(); _params.rate_d.zero(); _params.yaw_ff = 0.0f; _params.yaw_rate_max = 0.0f; _params.man_roll_max = 0.0f; _params.man_pitch_max = 0.0f; _params.man_yaw_max = 0.0f; _params.acro_rate_max.zero(); _rates_prev.zero(); _rates_sp.zero(); _rates_int.zero(); _thrust_sp = 0.0f; _att_control.zero(); _I.identity(); } MulticopterAttitudeControlBase::~MulticopterAttitudeControlBase() { } void MulticopterAttitudeControlBase::control_attitude(float dt) { float yaw_sp_move_rate = 0.0f; _publish_att_sp = false; if (_v_control_mode->data().flag_control_manual_enabled) { /* manual input, set or modify attitude setpoint */ if (_v_control_mode->data().flag_control_velocity_enabled || _v_control_mode->data().flag_control_climb_rate_enabled) { /* in assisted modes poll 'vehicle_attitude_setpoint' topic and modify it */ //XXX get rid of memcpy memcpy(&(_v_att_sp_mod.data()), &_v_att_sp->data(), sizeof(_v_att_sp_mod.data())); } if (!_v_control_mode->data().flag_control_climb_rate_enabled) { /* pass throttle directly if not in altitude stabilized mode */ _v_att_sp_mod.data().thrust = _manual_control_sp->data().z; _publish_att_sp = true; } if (!_armed->data().armed) { /* reset yaw setpoint when disarmed */ _reset_yaw_sp = true; } /* move yaw setpoint in all modes */ if (_v_att_sp_mod.data().thrust < 0.1f) { // TODO //if (_status.condition_landed) { /* reset yaw setpoint if on ground */ // reset_yaw_sp = true; //} } else { /* move yaw setpoint */ yaw_sp_move_rate = _manual_control_sp->data().r * _params.man_yaw_max; _v_att_sp_mod.data().yaw_body = _wrap_pi( _v_att_sp_mod.data().yaw_body + yaw_sp_move_rate * dt); float yaw_offs_max = _params.man_yaw_max / _params.att_p(2); float yaw_offs = _wrap_pi(_v_att_sp_mod.data().yaw_body - _v_att->data().yaw); if (yaw_offs < -yaw_offs_max) { _v_att_sp_mod.data().yaw_body = _wrap_pi(_v_att->data().yaw - yaw_offs_max); } else if (yaw_offs > yaw_offs_max) { _v_att_sp_mod.data().yaw_body = _wrap_pi(_v_att->data().yaw + yaw_offs_max); } _v_att_sp_mod.data().R_valid = false; // _publish_att_sp = true; } /* reset yaw setpoint to current position if needed */ if (_reset_yaw_sp) { _reset_yaw_sp = false; _v_att_sp_mod.data().yaw_body = _v_att->data().yaw; _v_att_sp_mod.data().R_valid = false; // _publish_att_sp = true; } if (!_v_control_mode->data().flag_control_velocity_enabled) { /* update attitude setpoint if not in position control mode */ _v_att_sp_mod.data().roll_body = _manual_control_sp->data().y * _params.man_roll_max; _v_att_sp_mod.data().pitch_body = -_manual_control_sp->data().x * _params.man_pitch_max; _v_att_sp_mod.data().R_valid = false; // _publish_att_sp = true; } } else { /* in non-manual mode use 'vehicle_attitude_setpoint' topic */ //XXX get rid of memcpy memcpy(&(_v_att_sp_mod.data()), &_v_att_sp->data(), sizeof(_v_att_sp_mod.data())); /* reset yaw setpoint after non-manual control mode */ _reset_yaw_sp = true; } _thrust_sp = _v_att_sp_mod.data().thrust; /* construct attitude setpoint rotation matrix */ math::Matrix<3, 3> R_sp; if (_v_att_sp_mod.data().R_valid) { /* rotation matrix in _att_sp is valid, use it */ R_sp.set(&_v_att_sp_mod.data().R_body[0]); } else { /* rotation matrix in _att_sp is not valid, use euler angles instead */ R_sp.from_euler(_v_att_sp_mod.data().roll_body, _v_att_sp_mod.data().pitch_body, _v_att_sp_mod.data().yaw_body); /* copy rotation matrix back to setpoint struct */ memcpy(&_v_att_sp_mod.data().R_body[0], &R_sp.data[0][0], sizeof(_v_att_sp_mod.data().R_body)); _v_att_sp_mod.data().R_valid = true; } /* rotation matrix for current state */ math::Matrix<3, 3> R; R.set(_v_att->data().R); /* all input data is ready, run controller itself */ /* try to move thrust vector shortest way, because yaw response is slower than roll/pitch */ math::Vector < 3 > R_z(R(0, 2), R(1, 2), R(2, 2)); math::Vector < 3 > R_sp_z(R_sp(0, 2), R_sp(1, 2), R_sp(2, 2)); /* axis and sin(angle) of desired rotation */ math::Vector < 3 > e_R = R.transposed() * (R_z % R_sp_z); /* calculate angle error */ float e_R_z_sin = e_R.length(); float e_R_z_cos = R_z * R_sp_z; /* calculate weight for yaw control */ float yaw_w = R_sp(2, 2) * R_sp(2, 2); /* calculate rotation matrix after roll/pitch only rotation */ math::Matrix<3, 3> R_rp; if (e_R_z_sin > 0.0f) { /* get axis-angle representation */ float e_R_z_angle = atan2f(e_R_z_sin, e_R_z_cos); math::Vector < 3 > e_R_z_axis = e_R / e_R_z_sin; e_R = e_R_z_axis * e_R_z_angle; /* cross product matrix for e_R_axis */ math::Matrix<3, 3> e_R_cp; e_R_cp.zero(); e_R_cp(0, 1) = -e_R_z_axis(2); e_R_cp(0, 2) = e_R_z_axis(1); e_R_cp(1, 0) = e_R_z_axis(2); e_R_cp(1, 2) = -e_R_z_axis(0); e_R_cp(2, 0) = -e_R_z_axis(1); e_R_cp(2, 1) = e_R_z_axis(0); /* rotation matrix for roll/pitch only rotation */ R_rp = R * (_I + e_R_cp * e_R_z_sin + e_R_cp * e_R_cp * (1.0f - e_R_z_cos)); } else { /* zero roll/pitch rotation */ R_rp = R; } /* R_rp and R_sp has the same Z axis, calculate yaw error */ math::Vector < 3 > R_sp_x(R_sp(0, 0), R_sp(1, 0), R_sp(2, 0)); math::Vector < 3 > R_rp_x(R_rp(0, 0), R_rp(1, 0), R_rp(2, 0)); e_R(2) = atan2f((R_rp_x % R_sp_x) * R_sp_z, R_rp_x * R_sp_x) * yaw_w; if (e_R_z_cos < 0.0f) { /* for large thrust vector rotations use another rotation method: * calculate angle and axis for R -> R_sp rotation directly */ math::Quaternion q; q.from_dcm(R.transposed() * R_sp); math::Vector < 3 > e_R_d = q.imag(); e_R_d.normalize(); e_R_d *= 2.0f * atan2f(e_R_d.length(), q(0)); /* use fusion of Z axis based rotation and direct rotation */ float direct_w = e_R_z_cos * e_R_z_cos * yaw_w; e_R = e_R * (1.0f - direct_w) + e_R_d * direct_w; } /* calculate angular rates setpoint */ _rates_sp = _params.att_p.emult(e_R); /* limit yaw rate */ _rates_sp(2) = math::constrain(_rates_sp(2), -_params.yaw_rate_max, _params.yaw_rate_max); /* feed forward yaw setpoint rate */ _rates_sp(2) += yaw_sp_move_rate * yaw_w * _params.yaw_ff; } void MulticopterAttitudeControlBase::control_attitude_rates(float dt) { /* reset integral if disarmed */ if (!_armed->data().armed || !_v_status->data().is_rotary_wing) { _rates_int.zero(); } /* current body angular rates */ math::Vector < 3 > rates; rates(0) = _v_att->data().rollspeed; rates(1) = _v_att->data().pitchspeed; rates(2) = _v_att->data().yawspeed; /* angular rates error */ math::Vector < 3 > rates_err = _rates_sp - rates; _att_control = _params.rate_p.emult(rates_err) + _params.rate_d.emult(_rates_prev - rates) / dt + _rates_int; _rates_prev = rates; /* update integral only if not saturated on low limit */ if (_thrust_sp > MIN_TAKEOFF_THRUST) { for (int i = 0; i < 3; i++) { if (fabsf(_att_control(i)) < _thrust_sp) { float rate_i = _rates_int(i) + _params.rate_i(i) * rates_err(i) * dt; if (isfinite( rate_i) && rate_i > -RATES_I_LIMIT && rate_i < RATES_I_LIMIT && _att_control(i) > -RATES_I_LIMIT && _att_control(i) < RATES_I_LIMIT) { _rates_int(i) = rate_i; } } } } } void MulticopterAttitudeControlBase::set_actuator_controls() { _actuators.data().control[0] = (isfinite(_att_control(0))) ? _att_control(0) : 0.0f; _actuators.data().control[1] = (isfinite(_att_control(1))) ? _att_control(1) : 0.0f; _actuators.data().control[2] = (isfinite(_att_control(2))) ? _att_control(2) : 0.0f; _actuators.data().control[3] = (isfinite(_thrust_sp)) ? _thrust_sp : 0.0f; } <commit_msg>multiplat mc att ctrl: move yaw sp only if xy is not controlled<commit_after>/* Copyright (c) 2014 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /** * @file mc_att_control_base.cpp * * MC Attitude Controller : Control and math code * * @author Tobias Naegeli <naegelit@student.ethz.ch> * @author Lorenz Meier <lm@inf.ethz.ch> * @author Anton Babushkin <anton.babushkin@me.com> * @author Thomas Gubler <thomasgubler@gmail.com> * @author Julian Oes <julian@oes.ch> * @author Roman Bapst <bapstr@ethz.ch> * */ #include "mc_att_control_base.h" #include <geo/geo.h> #include <math.h> #include <lib/mathlib/mathlib.h> #ifdef CONFIG_ARCH_ARM #else #include <cmath> using namespace std; #endif MulticopterAttitudeControlBase::MulticopterAttitudeControlBase() : _v_att_sp_mod(), _v_rates_sp_mod(), _actuators(), _publish_att_sp(false) { _params.att_p.zero(); _params.rate_p.zero(); _params.rate_i.zero(); _params.rate_d.zero(); _params.yaw_ff = 0.0f; _params.yaw_rate_max = 0.0f; _params.man_roll_max = 0.0f; _params.man_pitch_max = 0.0f; _params.man_yaw_max = 0.0f; _params.acro_rate_max.zero(); _rates_prev.zero(); _rates_sp.zero(); _rates_int.zero(); _thrust_sp = 0.0f; _att_control.zero(); _I.identity(); } MulticopterAttitudeControlBase::~MulticopterAttitudeControlBase() { } void MulticopterAttitudeControlBase::control_attitude(float dt) { float yaw_sp_move_rate = 0.0f; _publish_att_sp = false; if (_v_control_mode->data().flag_control_manual_enabled) { /* manual input, set or modify attitude setpoint */ if (_v_control_mode->data().flag_control_velocity_enabled || _v_control_mode->data().flag_control_climb_rate_enabled) { /* in assisted modes poll 'vehicle_attitude_setpoint' topic and modify it */ //XXX get rid of memcpy memcpy(&(_v_att_sp_mod.data()), &_v_att_sp->data(), sizeof(_v_att_sp_mod.data())); } if (!_v_control_mode->data().flag_control_climb_rate_enabled) { /* pass throttle directly if not in altitude stabilized mode */ _v_att_sp_mod.data().thrust = _manual_control_sp->data().z; _publish_att_sp = true; } if (!_armed->data().armed) { /* reset yaw setpoint when disarmed */ _reset_yaw_sp = true; } /* reset yaw setpoint to current position if needed */ if (_reset_yaw_sp) { _reset_yaw_sp = false; _v_att_sp_mod.data().yaw_body = _v_att->data().yaw; _v_att_sp_mod.data().R_valid = false; // _publish_att_sp = true; } if (!_v_control_mode->data().flag_control_velocity_enabled) { if (_v_att_sp_mod.data().thrust < 0.1f) { // TODO //if (_status.condition_landed) { /* reset yaw setpoint if on ground */ // reset_yaw_sp = true; //} } else { /* move yaw setpoint */ yaw_sp_move_rate = _manual_control_sp->data().r * _params.man_yaw_max; _v_att_sp_mod.data().yaw_body = _wrap_pi( _v_att_sp_mod.data().yaw_body + yaw_sp_move_rate * dt); float yaw_offs_max = _params.man_yaw_max / _params.att_p(2); float yaw_offs = _wrap_pi(_v_att_sp_mod.data().yaw_body - _v_att->data().yaw); if (yaw_offs < -yaw_offs_max) { _v_att_sp_mod.data().yaw_body = _wrap_pi(_v_att->data().yaw - yaw_offs_max); } else if (yaw_offs > yaw_offs_max) { _v_att_sp_mod.data().yaw_body = _wrap_pi(_v_att->data().yaw + yaw_offs_max); } _v_att_sp_mod.data().R_valid = false; // _publish_att_sp = true; } /* update attitude setpoint if not in position control mode */ _v_att_sp_mod.data().roll_body = _manual_control_sp->data().y * _params.man_roll_max; _v_att_sp_mod.data().pitch_body = -_manual_control_sp->data().x * _params.man_pitch_max; _v_att_sp_mod.data().R_valid = false; // _publish_att_sp = true; } } else { /* in non-manual mode use 'vehicle_attitude_setpoint' topic */ //XXX get rid of memcpy memcpy(&(_v_att_sp_mod.data()), &_v_att_sp->data(), sizeof(_v_att_sp_mod.data())); /* reset yaw setpoint after non-manual control mode */ _reset_yaw_sp = true; } _thrust_sp = _v_att_sp_mod.data().thrust; /* construct attitude setpoint rotation matrix */ math::Matrix<3, 3> R_sp; if (_v_att_sp_mod.data().R_valid) { /* rotation matrix in _att_sp is valid, use it */ R_sp.set(&_v_att_sp_mod.data().R_body[0]); } else { /* rotation matrix in _att_sp is not valid, use euler angles instead */ R_sp.from_euler(_v_att_sp_mod.data().roll_body, _v_att_sp_mod.data().pitch_body, _v_att_sp_mod.data().yaw_body); /* copy rotation matrix back to setpoint struct */ memcpy(&_v_att_sp_mod.data().R_body[0], &R_sp.data[0][0], sizeof(_v_att_sp_mod.data().R_body)); _v_att_sp_mod.data().R_valid = true; } /* rotation matrix for current state */ math::Matrix<3, 3> R; R.set(_v_att->data().R); /* all input data is ready, run controller itself */ /* try to move thrust vector shortest way, because yaw response is slower than roll/pitch */ math::Vector < 3 > R_z(R(0, 2), R(1, 2), R(2, 2)); math::Vector < 3 > R_sp_z(R_sp(0, 2), R_sp(1, 2), R_sp(2, 2)); /* axis and sin(angle) of desired rotation */ math::Vector < 3 > e_R = R.transposed() * (R_z % R_sp_z); /* calculate angle error */ float e_R_z_sin = e_R.length(); float e_R_z_cos = R_z * R_sp_z; /* calculate weight for yaw control */ float yaw_w = R_sp(2, 2) * R_sp(2, 2); /* calculate rotation matrix after roll/pitch only rotation */ math::Matrix<3, 3> R_rp; if (e_R_z_sin > 0.0f) { /* get axis-angle representation */ float e_R_z_angle = atan2f(e_R_z_sin, e_R_z_cos); math::Vector < 3 > e_R_z_axis = e_R / e_R_z_sin; e_R = e_R_z_axis * e_R_z_angle; /* cross product matrix for e_R_axis */ math::Matrix<3, 3> e_R_cp; e_R_cp.zero(); e_R_cp(0, 1) = -e_R_z_axis(2); e_R_cp(0, 2) = e_R_z_axis(1); e_R_cp(1, 0) = e_R_z_axis(2); e_R_cp(1, 2) = -e_R_z_axis(0); e_R_cp(2, 0) = -e_R_z_axis(1); e_R_cp(2, 1) = e_R_z_axis(0); /* rotation matrix for roll/pitch only rotation */ R_rp = R * (_I + e_R_cp * e_R_z_sin + e_R_cp * e_R_cp * (1.0f - e_R_z_cos)); } else { /* zero roll/pitch rotation */ R_rp = R; } /* R_rp and R_sp has the same Z axis, calculate yaw error */ math::Vector < 3 > R_sp_x(R_sp(0, 0), R_sp(1, 0), R_sp(2, 0)); math::Vector < 3 > R_rp_x(R_rp(0, 0), R_rp(1, 0), R_rp(2, 0)); e_R(2) = atan2f((R_rp_x % R_sp_x) * R_sp_z, R_rp_x * R_sp_x) * yaw_w; if (e_R_z_cos < 0.0f) { /* for large thrust vector rotations use another rotation method: * calculate angle and axis for R -> R_sp rotation directly */ math::Quaternion q; q.from_dcm(R.transposed() * R_sp); math::Vector < 3 > e_R_d = q.imag(); e_R_d.normalize(); e_R_d *= 2.0f * atan2f(e_R_d.length(), q(0)); /* use fusion of Z axis based rotation and direct rotation */ float direct_w = e_R_z_cos * e_R_z_cos * yaw_w; e_R = e_R * (1.0f - direct_w) + e_R_d * direct_w; } /* calculate angular rates setpoint */ _rates_sp = _params.att_p.emult(e_R); /* limit yaw rate */ _rates_sp(2) = math::constrain(_rates_sp(2), -_params.yaw_rate_max, _params.yaw_rate_max); /* feed forward yaw setpoint rate */ _rates_sp(2) += yaw_sp_move_rate * yaw_w * _params.yaw_ff; } void MulticopterAttitudeControlBase::control_attitude_rates(float dt) { /* reset integral if disarmed */ if (!_armed->data().armed || !_v_status->data().is_rotary_wing) { _rates_int.zero(); } /* current body angular rates */ math::Vector < 3 > rates; rates(0) = _v_att->data().rollspeed; rates(1) = _v_att->data().pitchspeed; rates(2) = _v_att->data().yawspeed; /* angular rates error */ math::Vector < 3 > rates_err = _rates_sp - rates; _att_control = _params.rate_p.emult(rates_err) + _params.rate_d.emult(_rates_prev - rates) / dt + _rates_int; _rates_prev = rates; /* update integral only if not saturated on low limit */ if (_thrust_sp > MIN_TAKEOFF_THRUST) { for (int i = 0; i < 3; i++) { if (fabsf(_att_control(i)) < _thrust_sp) { float rate_i = _rates_int(i) + _params.rate_i(i) * rates_err(i) * dt; if (isfinite( rate_i) && rate_i > -RATES_I_LIMIT && rate_i < RATES_I_LIMIT && _att_control(i) > -RATES_I_LIMIT && _att_control(i) < RATES_I_LIMIT) { _rates_int(i) = rate_i; } } } } } void MulticopterAttitudeControlBase::set_actuator_controls() { _actuators.data().control[0] = (isfinite(_att_control(0))) ? _att_control(0) : 0.0f; _actuators.data().control[1] = (isfinite(_att_control(1))) ? _att_control(1) : 0.0f; _actuators.data().control[2] = (isfinite(_att_control(2))) ? _att_control(2) : 0.0f; _actuators.data().control[3] = (isfinite(_thrust_sp)) ? _thrust_sp : 0.0f; } <|endoftext|>
<commit_before>#include <functional> #include <future> #include "kernel.h" #include "coverage.h" #include "numericrange.h" #include "numericdomain.h" #include "columndefinition.h" #include "table.h" #include "attributerecord.h" #include "geos/geom/CoordinateArraySequence.h" #include "geos/geom/LinearRing.h" #include "geos/geom/Polygon.h" #include "geos/geom/GeometryFactory.h" #include "feature.h" #include "factory.h" #include "abstractfactory.h" #include "featurefactory.h" #include "featurecoverage.h" #include "featureiterator.h" #include "symboltable.h" #include "OperationExpression.h" #include "operationmetadata.h" #include "operation.h" //#include "commandhandler.h" #include "gridding.h" using namespace Ilwis; using namespace FeatureOperations; Gridding::Gridding() { } Gridding::Gridding(quint64 metaid, const Ilwis::OperationExpression &expr) : OperationImplementation(metaid, expr) { } bool Gridding::execute(ExecutionContext *ctx, SymbolTable &symTable) { if (_prepState == sNOTPREPARED) if((_prepState = prepare(ctx, symTable)) != sPREPARED) return false; for(int fx=0; fx < _xsize; ++fx) { for(int fy=0; fy < _ysize; ++fy) { Coordinate c1(_top + std::vector<double>{_cellXSize * fx, _cellYSize * fy }); Coordinate c2(_top +std::vector<double>{_cellXSize * (fx+1), _cellYSize * fy }); Coordinate c3(_top + std::vector<double>{_cellXSize * (fx+1), _cellYSize * (fy+1) }); Coordinate c4(_top + std::vector<double>{_cellXSize * fx, _cellYSize * (fy+1) }); geos::geom::CoordinateSequence *coords = new geos::geom::CoordinateArraySequence(); coords->add(c1); coords->add(c2); coords->add(c3); coords->add(c4); coords->add(c1); geos::geom::LinearRing *outer = _outfeatures->geomfactory()->createLinearRing(coords); geos::geom::Geometry *pol = _outfeatures->geomfactory()->createPolygon(outer, 0); _outfeatures->newFeature(pol); } } if ( ctx != 0) { QVariant value; value.setValue<IFeatureCoverage>(_outfeatures); ctx->setOutput(symTable, value, _outfeatures->name(), itFEATURE,_outfeatures->source()); } return true; } OperationImplementation *Gridding::create(quint64 metaid, const Ilwis::OperationExpression &expr) { return new Gridding(metaid, expr) ; } quint64 Gridding::createMetadata() { QString url = QString("ilwis://operations/gridding"); Resource resource(QUrl(url), itOPERATIONMETADATA); resource.addProperty("namespace","ilwis"); resource.addProperty("longname","gridding"); resource.addProperty("syntax","gridding(coordinatesyste,top-coordinate,x-cell-size, y-cell-size, horizontal-cells, vertical-cells)"); resource.addProperty("description",TR("generates a new featurecoverage(polygons) were the polygons form a rectangular grid")); resource.addProperty("inparameters","6"); resource.addProperty("pin_1_type", itCOORDSYSTEM); resource.addProperty("pin_1_name", TR("coordinate-syste,")); resource.addProperty("pin_1_desc",TR("The coordinate system of the to be created polygon coverage")); resource.addProperty("pin_2_type", itCOORDINATE); resource.addProperty("pin_2_name", TR("top corner")); resource.addProperty("pin_2_desc",TR("The top corner of the polygonmap expressed in coordinates of the coordinate system")); resource.addProperty("pin_3_type", itDOUBLE); resource.addProperty("pin_3_name", TR("X cell size")); resource.addProperty("pin_3_desc",TR("Size in the x direction of a cell in the grid expressed in untis of the coordinate system")); resource.addProperty("pin_4_type", itDOUBLE); resource.addProperty("pin_4_name", TR("Y cell size")); resource.addProperty("pin_4_desc",TR("Size in the y direction of a cell in the grid expressed in untis of the coordinate system")); resource.addProperty("pin_5_type", itINTEGER); resource.addProperty("pin_5_name", TR("Horizontal cells")); resource.addProperty("pin_5_desc",TR("Number of cells in the x directions")); resource.addProperty("pin_6_type", itINTEGER); resource.addProperty("pin_6_name", TR("Vertical cells")); resource.addProperty("pin_6_desc",TR("Number of cells in the y directions")); resource.addProperty("outparameters",1); resource.addProperty("pout_1_type", itPOLYGON); resource.addProperty("pout_1_name", TR("output polygon coverage")); resource.addProperty("pout_1_desc",TR("output polygon coverage")); resource.prepare(); url += "=" + QString::number(resource.id()); resource.setUrl(url); mastercatalog()->addItems({resource}); return resource.id(); } OperationImplementation::State Gridding::prepare(ExecutionContext *ctx, const SymbolTable &symTable) { QString csyName = _expression.parm(0).value(); if (!_csy.prepare(csyName)) { ERROR2(ERR_COULD_NOT_LOAD_2,csyName,"" ); return sPREPAREFAILED; } QString name = _expression.parm(1).value(); QVariant var = symTable.getValue(name); _top = var.value<Coordinate>(); if (!_top.isValid() || _top.is0()) { _top = var.value<Coordinate>(); } if (!_top.isValid() || _top.is0()) { ERROR2(ERR_ILLEGAL_VALUE_2,"parameter value",name); return sPREPAREFAILED; } bool ok; _cellXSize = _expression.parm(2).value().toDouble(&ok); if ( !ok ) { ERROR2(ERR_ILLEGAL_VALUE_2,"parameter value","3"); return sPREPAREFAILED; } _cellYSize = _expression.parm(3).value().toDouble(&ok); if ( !ok ) { ERROR2(ERR_ILLEGAL_VALUE_2,"parameter value","4"); return sPREPAREFAILED; } _xsize = _expression.parm(4).value().toDouble(&ok); if ( !ok ) { ERROR2(ERR_ILLEGAL_VALUE_2,"parameter value","5"); return sPREPAREFAILED; } _ysize = _expression.parm(5).value().toDouble(&ok); if ( !ok ) { ERROR2(ERR_ILLEGAL_VALUE_2,"parameter value","6"); return sPREPAREFAILED; } QString outputName = _expression.parm(0,false).value(); Resource resource = outputName != sUNDEF ? Resource("ilwis://internalcatalog/" + outputName, itFLATTABLE) : Resource(itFLATTABLE); _attTable.prepare(resource); IDomain covdom; if (!covdom.prepare("count")){ return sPREPAREFAILED; } _attTable->addColumn(FEATUREIDCOLUMN,covdom); _outfeatures.prepare(); _outfeatures->coordinateSystem(_csy); _outfeatures->attributeTable(_attTable); Envelope env(_top, _top + std::vector<double>{_cellXSize * _xsize, _cellYSize * _ysize }); _outfeatures->envelope(env); return sPREPARED; } <commit_msg>casing<commit_after>#include <functional> #include <future> #include "kernel.h" #include "coverage.h" #include "numericrange.h" #include "numericdomain.h" #include "columndefinition.h" #include "table.h" #include "attributerecord.h" #include "geos/geom/CoordinateArraySequence.h" #include "geos/geom/LinearRing.h" #include "geos/geom/Polygon.h" #include "geos/geom/GeometryFactory.h" #include "feature.h" #include "factory.h" #include "abstractfactory.h" #include "featurefactory.h" #include "featurecoverage.h" #include "featureiterator.h" #include "symboltable.h" #include "operationExpression.h" #include "operationmetadata.h" #include "operation.h" //#include "commandhandler.h" #include "gridding.h" using namespace Ilwis; using namespace FeatureOperations; Gridding::Gridding() { } Gridding::Gridding(quint64 metaid, const Ilwis::OperationExpression &expr) : OperationImplementation(metaid, expr) { } bool Gridding::execute(ExecutionContext *ctx, SymbolTable &symTable) { if (_prepState == sNOTPREPARED) if((_prepState = prepare(ctx, symTable)) != sPREPARED) return false; for(int fx=0; fx < _xsize; ++fx) { for(int fy=0; fy < _ysize; ++fy) { Coordinate c1(_top + std::vector<double>{_cellXSize * fx, _cellYSize * fy }); Coordinate c2(_top +std::vector<double>{_cellXSize * (fx+1), _cellYSize * fy }); Coordinate c3(_top + std::vector<double>{_cellXSize * (fx+1), _cellYSize * (fy+1) }); Coordinate c4(_top + std::vector<double>{_cellXSize * fx, _cellYSize * (fy+1) }); geos::geom::CoordinateSequence *coords = new geos::geom::CoordinateArraySequence(); coords->add(c1); coords->add(c2); coords->add(c3); coords->add(c4); coords->add(c1); geos::geom::LinearRing *outer = _outfeatures->geomfactory()->createLinearRing(coords); geos::geom::Geometry *pol = _outfeatures->geomfactory()->createPolygon(outer, 0); _outfeatures->newFeature(pol); } } if ( ctx != 0) { QVariant value; value.setValue<IFeatureCoverage>(_outfeatures); ctx->setOutput(symTable, value, _outfeatures->name(), itFEATURE,_outfeatures->source()); } return true; } OperationImplementation *Gridding::create(quint64 metaid, const Ilwis::OperationExpression &expr) { return new Gridding(metaid, expr) ; } quint64 Gridding::createMetadata() { QString url = QString("ilwis://operations/gridding"); Resource resource(QUrl(url), itOPERATIONMETADATA); resource.addProperty("namespace","ilwis"); resource.addProperty("longname","gridding"); resource.addProperty("syntax","gridding(coordinatesyste,top-coordinate,x-cell-size, y-cell-size, horizontal-cells, vertical-cells)"); resource.addProperty("description",TR("generates a new featurecoverage(polygons) were the polygons form a rectangular grid")); resource.addProperty("inparameters","6"); resource.addProperty("pin_1_type", itCOORDSYSTEM); resource.addProperty("pin_1_name", TR("coordinate-syste,")); resource.addProperty("pin_1_desc",TR("The coordinate system of the to be created polygon coverage")); resource.addProperty("pin_2_type", itCOORDINATE); resource.addProperty("pin_2_name", TR("top corner")); resource.addProperty("pin_2_desc",TR("The top corner of the polygonmap expressed in coordinates of the coordinate system")); resource.addProperty("pin_3_type", itDOUBLE); resource.addProperty("pin_3_name", TR("X cell size")); resource.addProperty("pin_3_desc",TR("Size in the x direction of a cell in the grid expressed in untis of the coordinate system")); resource.addProperty("pin_4_type", itDOUBLE); resource.addProperty("pin_4_name", TR("Y cell size")); resource.addProperty("pin_4_desc",TR("Size in the y direction of a cell in the grid expressed in untis of the coordinate system")); resource.addProperty("pin_5_type", itINTEGER); resource.addProperty("pin_5_name", TR("Horizontal cells")); resource.addProperty("pin_5_desc",TR("Number of cells in the x directions")); resource.addProperty("pin_6_type", itINTEGER); resource.addProperty("pin_6_name", TR("Vertical cells")); resource.addProperty("pin_6_desc",TR("Number of cells in the y directions")); resource.addProperty("outparameters",1); resource.addProperty("pout_1_type", itPOLYGON); resource.addProperty("pout_1_name", TR("output polygon coverage")); resource.addProperty("pout_1_desc",TR("output polygon coverage")); resource.prepare(); url += "=" + QString::number(resource.id()); resource.setUrl(url); mastercatalog()->addItems({resource}); return resource.id(); } OperationImplementation::State Gridding::prepare(ExecutionContext *ctx, const SymbolTable &symTable) { QString csyName = _expression.parm(0).value(); if (!_csy.prepare(csyName)) { ERROR2(ERR_COULD_NOT_LOAD_2,csyName,"" ); return sPREPAREFAILED; } QString name = _expression.parm(1).value(); QVariant var = symTable.getValue(name); _top = var.value<Coordinate>(); if (!_top.isValid() || _top.is0()) { _top = var.value<Coordinate>(); } if (!_top.isValid() || _top.is0()) { ERROR2(ERR_ILLEGAL_VALUE_2,"parameter value",name); return sPREPAREFAILED; } bool ok; _cellXSize = _expression.parm(2).value().toDouble(&ok); if ( !ok ) { ERROR2(ERR_ILLEGAL_VALUE_2,"parameter value","3"); return sPREPAREFAILED; } _cellYSize = _expression.parm(3).value().toDouble(&ok); if ( !ok ) { ERROR2(ERR_ILLEGAL_VALUE_2,"parameter value","4"); return sPREPAREFAILED; } _xsize = _expression.parm(4).value().toDouble(&ok); if ( !ok ) { ERROR2(ERR_ILLEGAL_VALUE_2,"parameter value","5"); return sPREPAREFAILED; } _ysize = _expression.parm(5).value().toDouble(&ok); if ( !ok ) { ERROR2(ERR_ILLEGAL_VALUE_2,"parameter value","6"); return sPREPAREFAILED; } QString outputName = _expression.parm(0,false).value(); Resource resource = outputName != sUNDEF ? Resource("ilwis://internalcatalog/" + outputName, itFLATTABLE) : Resource(itFLATTABLE); _attTable.prepare(resource); IDomain covdom; if (!covdom.prepare("count")){ return sPREPAREFAILED; } _attTable->addColumn(FEATUREIDCOLUMN,covdom); _outfeatures.prepare(); _outfeatures->coordinateSystem(_csy); _outfeatures->attributeTable(_attTable); Envelope env(_top, _top + std::vector<double>{_cellXSize * _xsize, _cellYSize * _ysize }); _outfeatures->envelope(env); return sPREPARED; } <|endoftext|>
<commit_before>#include "scene.h" #include "camera.h" #include <stdio.h> #include "raytracer/rt_raytracer.h" #include "rasterizer/ras_rasterizer.h" Scene::Scene() { this->camera = new Camera(0.86, 480, 480); this->raytracer = new RayTracer(); this->rasterizer = new Rasterizer(); this->rasterizer->setCamera(this->camera); } Scene::~Scene() { for(int i = 0; i < this->meshes.size(); ++i) { delete this->meshes[i]; } for (int i = 0; i < this->lights.size(); ++i) { delete this->lights[i]; } for (int i = 0; i < this->materials.size(); ++i) { delete this->materials[i]; } delete this->camera; } void Scene::addMesh(Mesh *mesh) { this->raytracer->addMesh(mesh); this->rasterizer->addMesh(mesh); this->meshes.push_back(mesh); } void Scene::draw(unsigned char *output) { int count; Eigen::Vector3f *positions, *normals; Result *results; ResultOffset *result_offsets; this->rasterizer->beginFrame(); this->rasterizer->drawPrepass(); this->rasterizer->drawLights(this->lights); this->rasterizer->drawMeshes(); this->rasterizer->getRayTraceData(&count, &positions, &normals); this->raytracer->processRays(*this->camera, count, positions, normals, &results, &result_offsets, &count); this->rasterizer->drawRayData(results, result_offsets, count); } <commit_msg>Forgot a file for the last commit.<commit_after>#include "scene.h" #include "camera.h" #include <stdio.h> #include "raytracer/rt_raytracer.h" #include "rasterizer/ras_rasterizer.h" Scene::Scene() { this->camera = new Camera(0.86, 480, 480); this->raytracer = new RayTracer(); this->rasterizer = new Rasterizer(); this->rasterizer->setCamera(this->camera); } Scene::~Scene() { for(int i = 0; i < this->meshes.size(); ++i) { delete this->meshes[i]; } for (int i = 0; i < this->lights.size(); ++i) { delete this->lights[i]; } for (int i = 0; i < this->materials.size(); ++i) { delete this->materials[i]; } delete this->camera; } void Scene::addMesh(Mesh *mesh) { this->raytracer->addMesh(mesh); this->rasterizer->addMesh(mesh); this->meshes.push_back(mesh); } void Scene::draw(unsigned char *output) { int count, material_count; Eigen::Vector3f *positions, *normals; Result *results; ResultOffset *result_offsets; this->rasterizer->beginFrame(); this->rasterizer->drawPrepass(); this->rasterizer->drawLights(this->lights); this->rasterizer->drawMeshes(); this->rasterizer->getRayTraceData(&count, &positions, &normals); this->raytracer->processRays(*this->camera, count, positions, normals, &results, &result_offsets, &count, &material_count); this->rasterizer->drawRayData(results, result_offsets, count, material_count); // unsigned char *color = new unsigned char[4 * this->camera->getWidth() * this->camera->getHeight()]; // this->raytracer->renderScene(*this, this->camera->getWidth(), this->camera->getHeight(), color); // this->rasterizer->displayImageData(color); // delete [] color; } <|endoftext|>
<commit_before>/* Copyright (c) 2011-2012 - Tőkés Attila This file is part of SmtpClient for Qt. 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. See the LICENSE file for more details. */ #include "mimecontentformatter.h" using namespace SimpleMail; MimeContentFormatter::MimeContentFormatter(int max_length) : max_length(max_length) { } QByteArray MimeContentFormatter::format(const QByteArray &content, int &chars) const { QByteArray out; out.reserve(6000); for (int i = 0, size = content.length(); i < size; i+=max_length) { out.append(content.mid(i,max_length)); out.append(QByteArrayLiteral("\r\n")); chars += i; } return out; } QByteArray MimeContentFormatter::formatQuotedPrintable(const QByteArray &content, int &chars) const { QByteArray out; for (int i = 0; i < content.length() ; ++i) { chars++; if (content[i] == '\n') { // new line out.append(content[i]); chars = 0; continue; } if ((chars > max_length - 1) || ((content[i] == '=') && (chars > max_length - 3) )) { out.append(QByteArrayLiteral("=\r\n")); chars = 1; } out.append(content[i]); } return out; } void MimeContentFormatter::setMaxLength(int l) { max_length = l; } int MimeContentFormatter::maxLength() const { return max_length; } <commit_msg>Implement dot stuffing<commit_after>/* Copyright (c) 2011-2012 - Tőkés Attila This file is part of SmtpClient for Qt. 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. See the LICENSE file for more details. */ #include "mimecontentformatter.h" using namespace SimpleMail; MimeContentFormatter::MimeContentFormatter(int max_length) : max_length(max_length) { } QByteArray MimeContentFormatter::format(const QByteArray &content, int &chars) const { QByteArray out; out.reserve(6000); for (int i = 0, size = content.length(); i < size; i+=max_length) { out.append(content.mid(i,max_length)); out.append(QByteArrayLiteral("\r\n")); chars += i; } return out; } QByteArray MimeContentFormatter::formatQuotedPrintable(const QByteArray &content, int &chars) const { QByteArray out; for (int i = 0; i < content.length() ; ++i) { chars++; if (content[i] == '\n') { // new line out.append(content[i]); chars = 0; continue; } if ((chars > max_length - 1) || ((content[i] == '=') && (chars > max_length - 3) )) { out.append(QByteArrayLiteral("=\r\n")); chars = 1; } // dot stuffing: https://www.rfc-editor.org/rfc/rfc5321#section-4.5.2 if (chars == 1 && content[i] == '.') { out.append('.'); chars++; } out.append(content[i]); } return out; } void MimeContentFormatter::setMaxLength(int l) { max_length = l; } int MimeContentFormatter::maxLength() const { return max_length; } <|endoftext|>
<commit_before>#include <iostream> #include "vtrc-server/vtrc-application.h" #include "vtrc-server/vtrc-listener-tcp.h" #include "vtrc-common/vtrc-connection-iface.h" #include "vtrc-common/vtrc-closure-holder.h" #include "vtrc-common/vtrc-thread-pool.h" #include "vtrc-common/vtrc-rpc-service-wrapper.h" #include "protocol/hello.pb.h" /// hello protocol #include "boost/lexical_cast.hpp" #include "google/protobuf/descriptor.h" /// for descriptor( )->full_name( ) using namespace vtrc; namespace { class hello_service_impl: public howto::hello_service { common::connection_iface *cl_; void send_hello(::google::protobuf::RpcController* controller, const ::howto::request_message* request, ::howto::response_message* response, ::google::protobuf::Closure* done) /*override*/ { common::closure_holder ch( done ); /// instead of done->Run( ); std::ostringstream oss; oss << "Hello " << request->name( ) << " from hello_service_impl::send_hello!\n" << "Your transport name is '" << cl_->name( ) << "'.\nHave a nice day."; response->set_hello( oss.str( ) ); /// done->Run( ); /// ch will call it } public: hello_service_impl( common::connection_iface *cl ) :cl_(cl) { } static std::string const &service_name( ) { return howto::hello_service::descriptor( )->full_name( ); } }; class hello_application: public server::application { typedef common::rpc_service_wrapper wrapper_type; typedef vtrc::shared_ptr<wrapper_type> wrapper_sptr; public: hello_application( common::thread_pool &tp ) :server::application(tp.get_io_service( )) { } wrapper_sptr get_service_by_name( common::connection_iface* connection, const std::string &service_name ) { if( service_name == hello_service_impl::service_name( ) ) { hello_service_impl *new_impl = new hello_service_impl(connection); return vtrc::make_shared<wrapper_type>( new_impl ); } return wrapper_sptr( ); } }; } int main( int argc, const char **argv ) { const char *address = "127.0.0.1"; unsigned short port = 56560; if( argc > 2 ) { address = argv[1]; port = boost::lexical_cast<unsigned short>( argv[2] ); } else if( argc > 1 ) { port = boost::lexical_cast<unsigned short>( argv[1] ); } common::thread_pool tp; hello_application app( tp ); try { vtrc::shared_ptr<server::listener> tcp( server::listeners::tcp::create( app, address, port ) ); tcp->start( ); tp.attach( ); } catch( const std::exception &ex ) { std::cerr << "Hello, world failed: " << ex.what( ) << "\n"; } tp.join_all( ); /// make valgrind happy. google::protobuf::ShutdownProtobufLibrary( ); return 0; } <commit_msg>hello<commit_after>#include <iostream> #include "vtrc-server/vtrc-application.h" #include "vtrc-server/vtrc-listener-tcp.h" #include "vtrc-common/vtrc-connection-iface.h" #include "vtrc-common/vtrc-closure-holder.h" #include "vtrc-common/vtrc-thread-pool.h" #include "vtrc-common/vtrc-rpc-service-wrapper.h" #include "protocol/hello.pb.h" /// hello protocol #include "boost/lexical_cast.hpp" #include "google/protobuf/descriptor.h" /// for descriptor( )->full_name( ) using namespace vtrc; namespace { class hello_service_impl: public howto::hello_service { common::connection_iface *cl_; void send_hello(::google::protobuf::RpcController* controller, const ::howto::request_message* request, ::howto::response_message* response, ::google::protobuf::Closure* done) /*override*/ { common::closure_holder ch( done ); /// instead of done->Run( ); std::ostringstream oss; oss << "Hello " << request->name( ) << " from hello_service_impl::send_hello!\n" << "Your transport name is '" << cl_->name( ) << "'.\nHave a nice day."; response->set_hello( oss.str( ) ); /// done->Run( ); /// ch will call it } public: hello_service_impl( common::connection_iface *cl ) :cl_(cl) { } static std::string const &service_name( ) { return howto::hello_service::descriptor( )->full_name( ); } }; class hello_application: public server::application { typedef common::rpc_service_wrapper wrapper_type; typedef vtrc::shared_ptr<wrapper_type> wrapper_sptr; public: hello_application( common::thread_pool &tp ) :server::application(tp.get_io_service( )) { } wrapper_sptr get_service_by_name( common::connection_iface* connection, const std::string &service_name ) { if( service_name == hello_service_impl::service_name( ) ) { hello_service_impl *new_impl = new hello_service_impl(connection); return vtrc::make_shared<wrapper_type>( new_impl ); } return wrapper_sptr( ); } }; } // namespace int main( int argc, const char **argv ) { const char *address = "127.0.0.1"; unsigned short port = 56560; if( argc > 2 ) { address = argv[1]; port = boost::lexical_cast<unsigned short>( argv[2] ); } else if( argc > 1 ) { port = boost::lexical_cast<unsigned short>( argv[1] ); } common::thread_pool tp; hello_application app( tp ); try { vtrc::shared_ptr<server::listener> tcp( server::listeners::tcp::create( app, address, port ) ); tcp->start( ); tp.attach( ); } catch( const std::exception &ex ) { std::cerr << "Hello, world failed: " << ex.what( ) << "\n"; } tp.join_all( ); /// make valgrind happy. google::protobuf::ShutdownProtobufLibrary( ); return 0; } <|endoftext|>