text
stringlengths
54
60.6k
<commit_before>// -*- coding: us-ascii-unix -*- // Copyright 2012 Lukas Kemmer // // 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 <algorithm> // min, max #include "geo/int-point.hh" #include "geo/int-rect.hh" #include "geo/int-size.hh" namespace faint{ IntRect::IntRect(){ x = y = w = h = 0; } IntRect::IntRect(const IntPoint& p0, const IntPoint& p1) : x(std::min(p0.x, p1.x)), y(std::min(p0.y, p1.y)), w(std::abs(p0.x - p1.x) + 1), h(std::abs(p0.y - p1.y) + 1) {} IntRect::IntRect(const IntPoint& pt, const IntSize& sz) : x(pt.x), y(pt.y), w(sz.w), h(sz.h) {} IntRect IntRect::EmptyRect(){ return IntRect(); } IntSize IntRect::GetSize() const{ return IntSize(w, h); } int IntRect::Left() const{ return x; } int IntRect::Right() const{ return x + w - 1; } int IntRect::Top() const{ return y; } int IntRect::Bottom() const{ return y + h - 1; } IntPoint IntRect::TopLeft() const{ return IntPoint(x,y); } IntPoint IntRect::TopRight() const{ return IntPoint(Right(),y); } IntPoint IntRect::BottomLeft() const{ return IntPoint(x, Bottom()); } IntPoint IntRect::BottomRight() const{ return IntPoint(Right(), Bottom()); } IntPoint IntRect::MidTop() const{ return IntPoint(x + w / 2, Top()); } IntPoint IntRect::MidBottom() const{ return IntPoint(x + w / 2, Bottom()); } IntPoint IntRect::MidLeft() const{ return IntPoint(Left(), y + h / 2); } IntPoint IntRect::MidRight() const{ return IntPoint(Right(), y + h / 2); } bool IntRect::Contains(const IntPoint& p) const{ return p.x >= x && p.y >= y && p.x <= Right() && p.y <= Bottom(); } void IntRect::MoveTo(const IntPoint& p){ x = p.x; y = p.y; } int area(const IntRect& r){ return r.w * r.h; } bool empty(const IntRect& r){ return r.w == 0 || r.h == 0; } IntRect inflated(const IntRect& r, int dx, int dy){ return IntRect(IntPoint(r.x - dx, r.y - dy), IntSize(r.w + 2 * dx, r.h + 2 * dy)); } IntRect inflated(const IntRect& r, int d){ return inflated(r, d, d); } IntRect deflated(const IntRect& r, int d){ return IntRect(IntPoint(r.x + d, r.y + d), IntSize(r.w - 2 * d, r.h - 2 * d)); } IntRect intersection(const IntRect& r1, const IntRect& r2) { const auto tl = max_coords(r1.TopLeft(), r2.TopLeft()); const auto br = min_coords(r1.BottomRight(), r2.BottomRight()); return br.x < tl.x || br.y < tl.y ? IntRect::EmptyRect() : IntRect(tl, br); } IntRect largest(const IntRect& r1, const IntRect& r2){ return area(r1) <= area(r2) ? r2 : r1; } IntRect smallest(const IntRect& r1, const IntRect& r2){ return area(r2) < area(r1) ? r2 : r1; } IntRect translated(const IntRect& r, const IntPoint& p){ return IntRect(IntPoint(r.x + p.x, r.y + p.y), IntSize(r.w, r.h)); } bool operator==(const IntRect& r1, const IntRect& r2){ return r1.x == r2.x && r1.y == r2.y && r1.w == r2.w && r1.h == r2.h; } bool operator!=(const IntRect& r1, const IntRect& r2){ return !(r1 == r2); } } // namespace <commit_msg>Using braced initializer for some return values.<commit_after>// -*- coding: us-ascii-unix -*- // Copyright 2012 Lukas Kemmer // // 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 <algorithm> // min, max #include "geo/int-point.hh" #include "geo/int-rect.hh" #include "geo/int-size.hh" namespace faint{ IntRect::IntRect(){ x = y = w = h = 0; } IntRect::IntRect(const IntPoint& p0, const IntPoint& p1) : x(std::min(p0.x, p1.x)), y(std::min(p0.y, p1.y)), w(std::abs(p0.x - p1.x) + 1), h(std::abs(p0.y - p1.y) + 1) {} IntRect::IntRect(const IntPoint& pt, const IntSize& sz) : x(pt.x), y(pt.y), w(sz.w), h(sz.h) {} IntRect IntRect::EmptyRect(){ return {}; } IntSize IntRect::GetSize() const{ return {w, h}; } int IntRect::Left() const{ return x; } int IntRect::Right() const{ return x + w - 1; } int IntRect::Top() const{ return y; } int IntRect::Bottom() const{ return y + h - 1; } IntPoint IntRect::TopLeft() const{ return {x,y}; } IntPoint IntRect::TopRight() const{ return {Right(),y}; } IntPoint IntRect::BottomLeft() const{ return {x, Bottom()}; } IntPoint IntRect::BottomRight() const{ return {Right(), Bottom()}; } IntPoint IntRect::MidTop() const{ return {x + w / 2, Top()}; } IntPoint IntRect::MidBottom() const{ return {x + w / 2, Bottom()}; } IntPoint IntRect::MidLeft() const{ return {Left(), y + h / 2}; } IntPoint IntRect::MidRight() const{ return {Right(), y + h / 2}; } bool IntRect::Contains(const IntPoint& p) const{ return p.x >= x && p.y >= y && p.x <= Right() && p.y <= Bottom(); } void IntRect::MoveTo(const IntPoint& p){ x = p.x; y = p.y; } int area(const IntRect& r){ return r.w * r.h; } bool empty(const IntRect& r){ return r.w == 0 || r.h == 0; } IntRect inflated(const IntRect& r, int dx, int dy){ return {IntPoint(r.x - dx, r.y - dy), IntSize(r.w + 2 * dx, r.h + 2 * dy)}; } IntRect inflated(const IntRect& r, int d){ return inflated(r, d, d); } IntRect deflated(const IntRect& r, int d){ return {IntPoint(r.x + d, r.y + d), IntSize(r.w - 2 * d, r.h - 2 * d)}; } IntRect intersection(const IntRect& r1, const IntRect& r2) { const auto tl = max_coords(r1.TopLeft(), r2.TopLeft()); const auto br = min_coords(r1.BottomRight(), r2.BottomRight()); return br.x < tl.x || br.y < tl.y ? IntRect::EmptyRect() : IntRect(tl, br); } IntRect largest(const IntRect& r1, const IntRect& r2){ return area(r1) <= area(r2) ? r2 : r1; } IntRect smallest(const IntRect& r1, const IntRect& r2){ return area(r2) < area(r1) ? r2 : r1; } IntRect translated(const IntRect& r, const IntPoint& p){ return {IntPoint(r.x + p.x, r.y + p.y), IntSize(r.w, r.h)}; } bool operator==(const IntRect& r1, const IntRect& r2){ return r1.x == r2.x && r1.y == r2.y && r1.w == r2.w && r1.h == r2.h; } bool operator!=(const IntRect& r1, const IntRect& r2){ return !(r1 == r2); } } // namespace <|endoftext|>
<commit_before>/* Test cases for dkm.hpp This is just simple test harness without any external dependencies. */ #include "../include/dkm.hpp" #include "opencv2/opencv.hpp" #include <vector> #include <array> #include <tuple> #include <string> #include <iterator> #include <fstream> #include <iostream> #include <chrono> #include <numeric> cv::Mat load_opencv() { std::ifstream file("iris.data.csv"); std::istream_iterator<std::string> input(file); cv::Mat data; for (auto it = std::istream_iterator<std::string>(file); it != std::istream_iterator<std::string>(); ++it) { auto comma_pos = it->find(","); if (comma_pos != std::string::npos) { cv::Vec<float, 2> values; values[0] = std::stof(it->substr(0, comma_pos)); values[1] = std::stof(it->substr(comma_pos + 1)); data.push_back(values); } } // std::copy(std::istream_iterator<float>(file), std::istream_iterator<float>(), data.begin<float>()); return data; } std::chrono::duration<double> profile_opencv(cv::Mat& data, int k) { std::cout << "--- Profiling OpenCV kmeans ---" << std::endl; std::cout << "done" << std::endl << "Running kmeans..."; auto start = std::chrono::high_resolution_clock::now(); cv::Mat centers, labels; cv::kmeans(data, k, labels, cv::TermCriteria(cv::TermCriteria::EPS, 0, 0.01), 1, cv::KMEANS_PP_CENTERS, centers); auto end = std::chrono::high_resolution_clock::now(); std::cout << "done" << std::endl; return end - start; } int main() { std::cout << "# BEGINNING PROFILING #\n" << std::endl; auto cv_data = load_opencv(); auto time_opencv = profile_opencv(cv_data, 3); std::cout << "OpenCV: " << std::chrono::duration_cast<std::chrono::duration<double, std::milli>>(time_opencv).count() << "ms" << std::endl; return 0; }<commit_msg>Added dkm benchmark.<commit_after>/* Test cases for dkm.hpp This is just simple test harness without any external dependencies. */ #include "../include/dkm.hpp" #include "opencv2/opencv.hpp" #include <vector> #include <array> #include <tuple> #include <string> #include <iterator> #include <fstream> #include <iostream> #include <chrono> #include <numeric> cv::Mat load_opencv() { std::ifstream file("iris.data.csv"); std::istream_iterator<std::string> input(file); cv::Mat data; for (auto it = std::istream_iterator<std::string>(file); it != std::istream_iterator<std::string>(); ++it) { auto comma_pos = it->find(","); if (comma_pos != std::string::npos) { cv::Vec<float, 2> values; values[0] = std::stof(it->substr(0, comma_pos)); values[1] = std::stof(it->substr(comma_pos + 1)); data.push_back(values); } } // std::copy(std::istream_iterator<float>(file), std::istream_iterator<float>(), data.begin<float>()); return data; } std::vector<std::array<float, 2>> load_dkm() { std::ifstream file("iris.data.csv"); std::istream_iterator<std::string> input(file); std::vector<std::array<float, 2>> data; for (auto it = std::istream_iterator<std::string>(file); it != std::istream_iterator<std::string>(); ++it) { auto comma_pos = it->find(","); if (comma_pos != std::string::npos) data.push_back({std::stof(it->substr(0, comma_pos)), std::stof(it->substr(comma_pos + 1))}); } return data; } std::chrono::duration<double> profile_opencv(cv::Mat& data, int k) { std::cout << "--- Profiling OpenCV kmeans ---" << std::endl; std::cout << "Running kmeans..."; auto start = std::chrono::high_resolution_clock::now(); cv::Mat centers, labels; cv::kmeans(data, k, labels, cv::TermCriteria(cv::TermCriteria::EPS, 0, 0.01), 1, cv::KMEANS_PP_CENTERS, centers); (void)centers; (void)labels; auto end = std::chrono::high_resolution_clock::now(); std::cout << "done" << std::endl; return end - start; } std::chrono::duration<double> profile_dkm(std::vector<std::array<float, 2>>& data, int k) { std::cout << "--- Profiling OpenCV kmeans ---" << std::endl; std::cout << "Running kmeans..."; auto start = std::chrono::high_resolution_clock::now(); auto result = dkm::kmeans_lloyd(data, k); auto end = std::chrono::high_resolution_clock::now(); (void)result; std::cout << "done" << std::endl; return end - start; } int main() { std::cout << "# BEGINNING PROFILING #\n" << std::endl; auto cv_data = load_opencv(); auto time_opencv = profile_opencv(cv_data, 3); auto dkm_data = load_dkm(); auto time_dkm = profile_dkm(dkm_data, 3); std::cout << "OpenCV: " << std::chrono::duration_cast<std::chrono::duration<double, std::milli>>(time_opencv).count() << "ms" << std::endl; std::cout << "DKM: " << std::chrono::duration_cast<std::chrono::duration<double, std::milli>>(time_dkm).count() << "ms" << std::endl; return 0; }<|endoftext|>
<commit_before>// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2010 Gael Guennebaud <gael.guennebaud@inria.fr> // // Eigen 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 3 of the License, or (at your option) any later version. // // Alternatively, 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. // // Eigen 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 or the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License and a copy of the GNU General Public License along with // Eigen. If not, see <http://www.gnu.org/licenses/>. // The computeRoots function included in this is based on materials // covered by the following copyright and license: // // Geometric Tools, LLC // Copyright (c) 1998-2010 // Distributed under the Boost Software License, Version 1.0. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #include <iostream> #include <Eigen/Core> #include <Eigen/Eigenvalues> #include <Eigen/Geometry> #include <bench/BenchTimer.h> using namespace Eigen; using namespace std; template<typename Matrix, typename Roots> inline void computeRoots(const Matrix& m, Roots& roots) { typedef typename Matrix::Scalar Scalar; const Scalar s_inv3 = 1.0/3.0; const Scalar s_sqrt3 = internal::sqrt(Scalar(3.0)); // The characteristic equation is x^3 - c2*x^2 + c1*x - c0 = 0. The // eigenvalues are the roots to this equation, all guaranteed to be // real-valued, because the matrix is symmetric. Scalar c0 = m(0,0)*m(1,1)*m(2,2) + Scalar(2)*m(0,1)*m(0,2)*m(1,2) - m(0,0)*m(1,2)*m(1,2) - m(1,1)*m(0,2)*m(0,2) - m(2,2)*m(0,1)*m(0,1); Scalar c1 = m(0,0)*m(1,1) - m(0,1)*m(0,1) + m(0,0)*m(2,2) - m(0,2)*m(0,2) + m(1,1)*m(2,2) - m(1,2)*m(1,2); Scalar c2 = m(0,0) + m(1,1) + m(2,2); // Construct the parameters used in classifying the roots of the equation // and in solving the equation for the roots in closed form. Scalar c2_over_3 = c2*s_inv3; Scalar a_over_3 = (c1 - c2*c2_over_3)*s_inv3; if (a_over_3 > Scalar(0)) a_over_3 = Scalar(0); Scalar half_b = Scalar(0.5)*(c0 + c2_over_3*(Scalar(2)*c2_over_3*c2_over_3 - c1)); Scalar q = half_b*half_b + a_over_3*a_over_3*a_over_3; if (q > Scalar(0)) q = Scalar(0); // Compute the eigenvalues by solving for the roots of the polynomial. Scalar rho = internal::sqrt(-a_over_3); Scalar theta = std::atan2(internal::sqrt(-q),half_b)*s_inv3; Scalar cos_theta = internal::cos(theta); Scalar sin_theta = internal::sin(theta); roots(0) = c2_over_3 + Scalar(2)*rho*cos_theta; roots(1) = c2_over_3 - rho*(cos_theta + s_sqrt3*sin_theta); roots(2) = c2_over_3 - rho*(cos_theta - s_sqrt3*sin_theta); // Sort in increasing order. if (roots(0) >= roots(1)) std::swap(roots(0),roots(1)); if (roots(1) >= roots(2)) { std::swap(roots(1),roots(2)); if (roots(0) >= roots(1)) std::swap(roots(0),roots(1)); } } template<typename Matrix, typename Vector> void eigen33(const Matrix& mat, Matrix& evecs, Vector& evals) { typedef typename Matrix::Scalar Scalar; // Scale the matrix so its entries are in [-1,1]. The scaling is applied // only when at least one matrix entry has magnitude larger than 1. Scalar scale = mat.cwiseAbs()/*.template triangularView<Lower>()*/.maxCoeff(); scale = std::max(scale,Scalar(1)); Matrix scaledMat = mat / scale; // Compute the eigenvalues // scaledMat.setZero(); computeRoots(scaledMat,evals); // compute the eigen vectors // **here we assume 3 differents eigenvalues** // "optimized version" which appears to be slower with gcc! // Vector base; // Scalar alpha, beta; // base << scaledMat(1,0) * scaledMat(2,1), // scaledMat(1,0) * scaledMat(2,0), // -scaledMat(1,0) * scaledMat(1,0); // for(int k=0; k<2; ++k) // { // alpha = scaledMat(0,0) - evals(k); // beta = scaledMat(1,1) - evals(k); // evecs.col(k) = (base + Vector(-beta*scaledMat(2,0), -alpha*scaledMat(2,1), alpha*beta)).normalized(); // } // evecs.col(2) = evecs.col(0).cross(evecs.col(1)).normalized(); // naive version Matrix tmp; tmp = scaledMat; tmp.diagonal().array() -= evals(0); evecs.col(0) = tmp.row(0).cross(tmp.row(1)).normalized(); tmp = scaledMat; tmp.diagonal().array() -= evals(1); evecs.col(1) = tmp.row(0).cross(tmp.row(1)).normalized(); tmp = scaledMat; tmp.diagonal().array() -= evals(2); evecs.col(2) = tmp.row(0).cross(tmp.row(1)).normalized(); // Rescale back to the original size. evals *= scale; } int main() { BenchTimer t; int tries = 10; int rep = 400000; typedef Matrix3f Mat; typedef Vector3f Vec; Mat A = Mat::Random(3,3); A = A.adjoint() * A; SelfAdjointEigenSolver<Mat> eig(A); BENCH(t, tries, rep, eig.compute(A)); std::cout << "Eigen: " << t.best() << "s\n"; Mat evecs; Vec evals; BENCH(t, tries, rep, eigen33(A,evecs,evals)); std::cout << "Direct: " << t.best() << "s\n\n"; std::cerr << "Eigenvalue/eigenvector diffs:\n"; std::cerr << (evals - eig.eigenvalues()).transpose() << "\n"; for(int k=0;k<3;++k) if(evecs.col(k).dot(eig.eigenvectors().col(k))<0) evecs.col(k) = -evecs.col(k); std::cerr << evecs - eig.eigenvectors() << "\n\n"; } <commit_msg>slightly more stable eigen vector computation<commit_after>// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2010 Gael Guennebaud <gael.guennebaud@inria.fr> // // Eigen 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 3 of the License, or (at your option) any later version. // // Alternatively, 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. // // Eigen 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 or the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License and a copy of the GNU General Public License along with // Eigen. If not, see <http://www.gnu.org/licenses/>. // The computeRoots function included in this is based on materials // covered by the following copyright and license: // // Geometric Tools, LLC // Copyright (c) 1998-2010 // Distributed under the Boost Software License, Version 1.0. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #include <iostream> #include <Eigen/Core> #include <Eigen/Eigenvalues> #include <Eigen/Geometry> #include <bench/BenchTimer.h> using namespace Eigen; using namespace std; template<typename Matrix, typename Roots> inline void computeRoots(const Matrix& m, Roots& roots) { typedef typename Matrix::Scalar Scalar; const Scalar s_inv3 = 1.0/3.0; const Scalar s_sqrt3 = internal::sqrt(Scalar(3.0)); // The characteristic equation is x^3 - c2*x^2 + c1*x - c0 = 0. The // eigenvalues are the roots to this equation, all guaranteed to be // real-valued, because the matrix is symmetric. Scalar c0 = m(0,0)*m(1,1)*m(2,2) + Scalar(2)*m(0,1)*m(0,2)*m(1,2) - m(0,0)*m(1,2)*m(1,2) - m(1,1)*m(0,2)*m(0,2) - m(2,2)*m(0,1)*m(0,1); Scalar c1 = m(0,0)*m(1,1) - m(0,1)*m(0,1) + m(0,0)*m(2,2) - m(0,2)*m(0,2) + m(1,1)*m(2,2) - m(1,2)*m(1,2); Scalar c2 = m(0,0) + m(1,1) + m(2,2); // Construct the parameters used in classifying the roots of the equation // and in solving the equation for the roots in closed form. Scalar c2_over_3 = c2*s_inv3; Scalar a_over_3 = (c1 - c2*c2_over_3)*s_inv3; if (a_over_3 > Scalar(0)) a_over_3 = Scalar(0); Scalar half_b = Scalar(0.5)*(c0 + c2_over_3*(Scalar(2)*c2_over_3*c2_over_3 - c1)); Scalar q = half_b*half_b + a_over_3*a_over_3*a_over_3; if (q > Scalar(0)) q = Scalar(0); // Compute the eigenvalues by solving for the roots of the polynomial. Scalar rho = internal::sqrt(-a_over_3); Scalar theta = std::atan2(internal::sqrt(-q),half_b)*s_inv3; Scalar cos_theta = internal::cos(theta); Scalar sin_theta = internal::sin(theta); roots(0) = c2_over_3 + Scalar(2)*rho*cos_theta; roots(1) = c2_over_3 - rho*(cos_theta + s_sqrt3*sin_theta); roots(2) = c2_over_3 - rho*(cos_theta - s_sqrt3*sin_theta); // Sort in increasing order. if (roots(0) >= roots(1)) std::swap(roots(0),roots(1)); if (roots(1) >= roots(2)) { std::swap(roots(1),roots(2)); if (roots(0) >= roots(1)) std::swap(roots(0),roots(1)); } } template<typename Matrix, typename Vector> void eigen33(const Matrix& mat, Matrix& evecs, Vector& evals) { typedef typename Matrix::Scalar Scalar; // Scale the matrix so its entries are in [-1,1]. The scaling is applied // only when at least one matrix entry has magnitude larger than 1. Scalar scale = mat.cwiseAbs()/*.template triangularView<Lower>()*/.maxCoeff(); scale = std::max(scale,Scalar(1)); Matrix scaledMat = mat / scale; // Compute the eigenvalues // scaledMat.setZero(); computeRoots(scaledMat,evals); // compute the eigen vectors // **here we assume 3 differents eigenvalues** // "optimized version" which appears to be slower with gcc! // Vector base; // Scalar alpha, beta; // base << scaledMat(1,0) * scaledMat(2,1), // scaledMat(1,0) * scaledMat(2,0), // -scaledMat(1,0) * scaledMat(1,0); // for(int k=0; k<2; ++k) // { // alpha = scaledMat(0,0) - evals(k); // beta = scaledMat(1,1) - evals(k); // evecs.col(k) = (base + Vector(-beta*scaledMat(2,0), -alpha*scaledMat(2,1), alpha*beta)).normalized(); // } // evecs.col(2) = evecs.col(0).cross(evecs.col(1)).normalized(); // // naive version // Matrix tmp; // tmp = scaledMat; // tmp.diagonal().array() -= evals(0); // evecs.col(0) = tmp.row(0).cross(tmp.row(1)).normalized(); // // tmp = scaledMat; // tmp.diagonal().array() -= evals(1); // evecs.col(1) = tmp.row(0).cross(tmp.row(1)).normalized(); // // tmp = scaledMat; // tmp.diagonal().array() -= evals(2); // evecs.col(2) = tmp.row(0).cross(tmp.row(1)).normalized(); // a slighlty more stable version: Matrix tmp; tmp = scaledMat; tmp.diagonal ().array () -= evals (2); evecs.col (2) = tmp.row (0).cross (tmp.row (1)).normalized (); tmp = scaledMat; tmp.diagonal ().array () -= evals (1); evecs.col(1) = tmp.row (0).cross(tmp.row (1)); Scalar n1 = evecs.col(1).norm(); if(n1<=Eigen::NumTraits<Scalar>::epsilon()) evecs.col(1) = evecs.col(2).unitOrthogonal(); else evecs.col(1) /= n1; evecs.col(0) = evecs.col(2).cross(evecs.col(1)); // Rescale back to the original size. evals *= scale; } int main() { BenchTimer t; int tries = 10; int rep = 400000; typedef Matrix3f Mat; typedef Vector3f Vec; Mat A = Mat::Random(3,3); A = A.adjoint() * A; SelfAdjointEigenSolver<Mat> eig(A); BENCH(t, tries, rep, eig.compute(A)); std::cout << "Eigen: " << t.best() << "s\n"; Mat evecs; Vec evals; BENCH(t, tries, rep, eigen33(A,evecs,evals)); std::cout << "Direct: " << t.best() << "s\n\n"; std::cerr << "Eigenvalue/eigenvector diffs:\n"; std::cerr << (evals - eig.eigenvalues()).transpose() << "\n"; for(int k=0;k<3;++k) if(evecs.col(k).dot(eig.eigenvectors().col(k))<0) evecs.col(k) = -evecs.col(k); std::cerr << evecs - eig.eigenvectors() << "\n\n"; } <|endoftext|>
<commit_before>/* -*- mode: c++; c-basic-offset:4 -*- crypto/signencryptfilescontroller.cpp This file is part of Kleopatra, the KDE keymanager Copyright (c) 2007 Klarälvdalens Datakonsult AB Kleopatra is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Kleopatra is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include <config-kleopatra.h> #include "signencryptfilescontroller.h" #include "signencryptfilestask.h" #include "certificateresolver.h" #include <crypto/gui/signencryptfileswizard.h> #include <crypto/taskcollection.h> #include <utils/input.h> #include <utils/output.h> #include <utils/classify.h> #include <utils/stl_util.h> #include <utils/kleo_assert.h> #include <utils/exception.h> #include <kmime/kmime_header_parsing.h> #include <KLocale> #include <kdebug.h> #include <QPointer> #include <QTimer> #include <QFileInfo> #include <boost/bind.hpp> using namespace Kleo; using namespace Kleo::Crypto; using namespace Kleo::Crypto::Gui; using namespace boost; using namespace GpgME; using namespace KMime::Types; class SignEncryptFilesController::Private { friend class ::Kleo::Crypto::SignEncryptFilesController; SignEncryptFilesController * const q; public: explicit Private( SignEncryptFilesController * qq ); ~Private(); private: void slotWizardOperationPrepared(); void slotWizardCanceled(); void slotTaskDone(); private: void ensureWizardCreated(); void ensureWizardVisible(); void cancelAllTasks(); void reportError( int err, const QString & details ) { emit q->error( err, details ); } void schedule(); shared_ptr<SignEncryptFilesTask> takeRunnable( GpgME::Protocol proto ); static void assertValidOperation( unsigned int ); static QString titleForOperation( unsigned int op ); private: std::vector< shared_ptr<SignEncryptFilesTask> > runnable, completed; shared_ptr<SignEncryptFilesTask> cms, openpgp; QPointer<SignEncryptFilesWizard> wizard; unsigned int operation; Protocol protocol; }; SignEncryptFilesController::Private::Private( SignEncryptFilesController * qq ) : q( qq ), runnable(), cms(), openpgp(), wizard(), operation( SignAllowed|EncryptAllowed ), protocol( UnknownProtocol ) { } SignEncryptFilesController::Private::~Private() { kDebug(); } QString SignEncryptFilesController::Private::titleForOperation( unsigned int op ) { const bool signDisallowed = (op & SignMask) == SignDisallowed; const bool encryptDisallowed = (op & EncryptMask) == EncryptDisallowed; kleo_assert( !signDisallowed || !encryptDisallowed ); if ( !signDisallowed && encryptDisallowed ) return i18n( "Sign Files" ); if ( signDisallowed && !encryptDisallowed ) return i18n( "Encrypt Files" ); return i18n( "Sign/Encrypt Files" ); } SignEncryptFilesController::SignEncryptFilesController( QObject * p ) : Controller( p ), d( new Private( this ) ) { } SignEncryptFilesController::SignEncryptFilesController( const shared_ptr<const ExecutionContext> & ctx, QObject * p ) : Controller( ctx, p ), d( new Private( this ) ) { } SignEncryptFilesController::~SignEncryptFilesController() { kDebug(); if ( d->wizard && !d->wizard->isVisible() ) delete d->wizard; //d->wizard->close(); ### ? } void SignEncryptFilesController::setProtocol( Protocol proto ) { kleo_assert( d->protocol == UnknownProtocol || d->protocol == proto ); d->protocol = proto; d->ensureWizardCreated(); d->wizard->setPresetProtocol( proto ); } Protocol SignEncryptFilesController::protocol() const { return d->protocol; } // static void SignEncryptFilesController::Private::assertValidOperation( unsigned int op ) { kleo_assert( ( op & SignMask ) == SignDisallowed || ( op & SignMask ) == SignAllowed || ( op & SignMask ) == SignForced ); kleo_assert( ( op & EncryptMask ) == EncryptDisallowed || ( op & EncryptMask ) == EncryptAllowed || ( op & EncryptMask ) == EncryptForced ); kleo_assert( ( op & ~(SignMask|EncryptMask) ) == 0 ); } void SignEncryptFilesController::setOperationMode( unsigned int mode ) { Private::assertValidOperation( mode ); d->operation = mode; if ( d->wizard ) d->wizard->setWindowTitle( d->titleForOperation( d->operation ) ); } void SignEncryptFilesController::setFiles( const QStringList & files ) { kleo_assert( !files.empty() ); d->ensureWizardVisible(); d->wizard->setFiles( files ); } void SignEncryptFilesController::Private::slotWizardCanceled() { kDebug(); reportError( gpg_error( GPG_ERR_CANCELED ), i18n("User cancel") ); } void SignEncryptFilesController::start() { d->ensureWizardVisible(); } static shared_ptr<SignEncryptFilesTask> createSignEncryptTaskForFileInfo( const QFileInfo & fi, bool pgp, bool sign, bool encrypt, bool ascii, bool removeUnencrypted, const std::vector<Key> & recipients, const std::vector<Key> & signers ) { const shared_ptr<SignEncryptFilesTask> task( new SignEncryptFilesTask ); task->setSign( sign ); task->setEncrypt( encrypt ); task->setAsciiArmor( ascii ); task->setRemoveInputFileOnSuccess( removeUnencrypted ); if ( sign ) task->setSigners( signers ); if ( encrypt ) task->setRecipients( recipients ); unsigned int cls = pgp ? Class::OpenPGP : Class::CMS ; if ( encrypt ) cls |= Class::CipherText; else if ( sign ) cls |= Class::DetachedSignature; cls |= ascii ? Class::Ascii : Class::Binary ; const QString input = fi.absoluteFilePath(); task->setInputFileName( input ); const char * ext = outputFileExtension( cls ); if ( !ext ) ext = "out"; // ### error out? const QString output = input + '.' + ext; task->setOutputFileName( output ); return task; } static std::vector< shared_ptr<SignEncryptFilesTask> > createSignEncryptTasksForFileInfo( const QFileInfo & fi, bool sign, bool encrypt, bool ascii, bool removeUnencrypted, const std::vector<Key> & pgpRecipients, const std::vector<Key> & pgpSigners, const std::vector<Key> & cmsRecipients, const std::vector<Key> & cmsSigners ) { std::vector< shared_ptr<SignEncryptFilesTask> > result; const bool shallPgpSign = sign && !pgpSigners.empty(); const bool shallPgpEncrypt = encrypt && !pgpRecipients.empty(); const bool pgp = shallPgpEncrypt && ( !sign || shallPgpSign ) || !encrypt && shallPgpSign; const bool shallCmsSign = sign && !cmsSigners.empty(); const bool shallCmsEncrypt = encrypt && !cmsRecipients.empty(); const bool cms = shallCmsEncrypt && ( !sign || shallCmsSign ) || !encrypt && shallCmsSign; result.reserve( pgp + cms ); if ( pgp ) result.push_back( createSignEncryptTaskForFileInfo( fi, true, sign, encrypt, ascii, removeUnencrypted, pgpRecipients, pgpSigners ) ); if ( cms ) result.push_back( createSignEncryptTaskForFileInfo( fi, false, sign, encrypt, ascii, removeUnencrypted, cmsRecipients, cmsSigners ) ); return result; } void SignEncryptFilesController::Private::slotWizardOperationPrepared() { try { kleo_assert( wizard ); const bool sign = wizard->signingSelected(); const bool encrypt = wizard->encryptionSelected(); const bool ascii = wizard->isAsciiArmorEnabled(); const bool removeUnencrypted = wizard->removeUnencryptedFile(); const QFileInfoList files = wizard->resolvedFiles(); std::vector<Key> pgpRecipients, cmsRecipients, pgpSigners, cmsSigners; if ( encrypt ) { const std::vector<Key> recipients = wizard->resolvedCertificates(); kdtools::copy_if( recipients.begin(), recipients.end(), std::back_inserter( pgpRecipients ), bind( &Key::protocol, _1 ) == GpgME::OpenPGP ); kdtools::copy_if( recipients.begin(), recipients.end(), std::back_inserter( cmsRecipients ), bind( &Key::protocol, _1 ) == GpgME::CMS ); kleo_assert( pgpRecipients.size() + cmsRecipients.size() == recipients.size() ); } if ( sign ) { const std::vector<Key> signers = wizard->resolvedSigners(); kdtools::copy_if( signers.begin(), signers.end(), std::back_inserter( pgpSigners ), bind( &Key::protocol, _1 ) == GpgME::OpenPGP ); kdtools::copy_if( signers.begin(), signers.end(), std::back_inserter( cmsSigners ), bind( &Key::protocol, _1 ) == GpgME::CMS ); kleo_assert( pgpSigners.size() + cmsSigners.size() == signers.size() ); } kleo_assert( !files.empty() ); std::vector< shared_ptr<SignEncryptFilesTask> > tasks; tasks.reserve( files.size() ); Q_FOREACH( const QFileInfo & fi, files ) { const std::vector< shared_ptr<SignEncryptFilesTask> > created = createSignEncryptTasksForFileInfo( fi, sign, encrypt, ascii, removeUnencrypted, pgpRecipients, pgpSigners, cmsRecipients, cmsSigners ); tasks.insert( tasks.end(), created.begin(), created.end() ); } kleo_assert( runnable.empty() ); runnable.swap( tasks ); int i = 0; Q_FOREACH( const shared_ptr<Task> task, runnable ) connect( task.get(), SIGNAL(result(boost::shared_ptr<const Kleo::Crypto::Task::Result>)), q, SLOT(slotTaskDone()) ); ensureWizardCreated(); shared_ptr<TaskCollection> coll( new TaskCollection ); std::vector<shared_ptr<Task> > tmp; std::copy( runnable.begin(), runnable.end(), std::back_inserter( tmp ) ); coll->setTasks( tmp ); wizard->setTaskCollection( coll ); QTimer::singleShot( 0, q, SLOT(schedule()) ); } catch ( const Kleo::Exception & e ) { reportError( e.error().encodedError(), e.message() ); } catch ( const std::exception & e ) { reportError( gpg_error( GPG_ERR_UNEXPECTED ), i18n("Caught unexpected exception in SignEncryptFilesController::Private::slotWizardOperationPrepared: %1", QString::fromLocal8Bit( e.what() ) ) ); } catch ( ... ) { reportError( gpg_error( GPG_ERR_UNEXPECTED ), i18n("Caught unknown exception in SignEncryptFilesController::Private::slotWizardOperationPrepared") ); } } void SignEncryptFilesController::Private::schedule() { if ( !cms ) if ( const shared_ptr<SignEncryptFilesTask> t = takeRunnable( CMS ) ) { t->start(); cms = t; } if ( !openpgp ) if ( const shared_ptr<SignEncryptFilesTask> t = takeRunnable( OpenPGP ) ) { t->start(); openpgp = t; } if ( !cms && !openpgp ) { kleo_assert( runnable.empty() ); emit q->done(); } } shared_ptr<SignEncryptFilesTask> SignEncryptFilesController::Private::takeRunnable( GpgME::Protocol proto ) { const std::vector< shared_ptr<SignEncryptFilesTask> >::iterator it = std::find_if( runnable.begin(), runnable.end(), bind( &Task::protocol, _1 ) == proto ); if ( it == runnable.end() ) return shared_ptr<SignEncryptFilesTask>(); const shared_ptr<SignEncryptFilesTask> result = *it; runnable.erase( it ); return result; } void SignEncryptFilesController::Private::slotTaskDone() { assert( q->sender() ); // We could just delete the tasks here, but we can't use // Qt::QueuedConnection here (we need sender()) and other slots // might not yet have executed. Therefore, we push completed tasks // into a burial container if ( q->sender() == cms.get() ) { completed.push_back( cms ); cms.reset(); } else if ( q->sender() == openpgp.get() ) { completed.push_back( openpgp ); openpgp.reset(); } QTimer::singleShot( 0, q, SLOT(schedule()) ); } void SignEncryptFilesController::cancel() { kDebug(); try { if ( d->wizard ) d->wizard->close(); d->cancelAllTasks(); } catch ( const std::exception & e ) { qDebug( "Caught exception: %s", e.what() ); } } void SignEncryptFilesController::Private::cancelAllTasks() { // we just kill all runnable tasks - this will not result in // signal emissions. runnable.clear(); // a cancel() will result in a call to if ( cms ) cms->cancel(); if ( openpgp ) openpgp->cancel(); } void SignEncryptFilesController::Private::ensureWizardCreated() { if ( wizard ) return; std::auto_ptr<SignEncryptFilesWizard> w( new SignEncryptFilesWizard ); w->setWindowTitle( titleForOperation( operation ) ); w->setAttribute( Qt::WA_DeleteOnClose ); connect( w.get(), SIGNAL(operationPrepared()), q, SLOT(slotWizardOperationPrepared()), Qt::QueuedConnection ); connect( w.get(), SIGNAL(canceled()), q, SLOT(slotWizardCanceled()), Qt::QueuedConnection ); wizard = w.release(); } void SignEncryptFilesController::Private::ensureWizardVisible() { ensureWizardCreated(); q->bringToForeground( wizard ); } #include "moc_signencryptfilescontroller.cpp" <commit_msg>for files, created detached signatures<commit_after>/* -*- mode: c++; c-basic-offset:4 -*- crypto/signencryptfilescontroller.cpp This file is part of Kleopatra, the KDE keymanager Copyright (c) 2007 Klarälvdalens Datakonsult AB Kleopatra is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Kleopatra is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include <config-kleopatra.h> #include "signencryptfilescontroller.h" #include "signencryptfilestask.h" #include "certificateresolver.h" #include <crypto/gui/signencryptfileswizard.h> #include <crypto/taskcollection.h> #include <utils/input.h> #include <utils/output.h> #include <utils/classify.h> #include <utils/stl_util.h> #include <utils/kleo_assert.h> #include <utils/exception.h> #include <kmime/kmime_header_parsing.h> #include <KLocale> #include <kdebug.h> #include <QPointer> #include <QTimer> #include <QFileInfo> #include <boost/bind.hpp> using namespace Kleo; using namespace Kleo::Crypto; using namespace Kleo::Crypto::Gui; using namespace boost; using namespace GpgME; using namespace KMime::Types; class SignEncryptFilesController::Private { friend class ::Kleo::Crypto::SignEncryptFilesController; SignEncryptFilesController * const q; public: explicit Private( SignEncryptFilesController * qq ); ~Private(); private: void slotWizardOperationPrepared(); void slotWizardCanceled(); void slotTaskDone(); private: void ensureWizardCreated(); void ensureWizardVisible(); void cancelAllTasks(); void reportError( int err, const QString & details ) { emit q->error( err, details ); } void schedule(); shared_ptr<SignEncryptFilesTask> takeRunnable( GpgME::Protocol proto ); static void assertValidOperation( unsigned int ); static QString titleForOperation( unsigned int op ); private: std::vector< shared_ptr<SignEncryptFilesTask> > runnable, completed; shared_ptr<SignEncryptFilesTask> cms, openpgp; QPointer<SignEncryptFilesWizard> wizard; unsigned int operation; Protocol protocol; }; SignEncryptFilesController::Private::Private( SignEncryptFilesController * qq ) : q( qq ), runnable(), cms(), openpgp(), wizard(), operation( SignAllowed|EncryptAllowed ), protocol( UnknownProtocol ) { } SignEncryptFilesController::Private::~Private() { kDebug(); } QString SignEncryptFilesController::Private::titleForOperation( unsigned int op ) { const bool signDisallowed = (op & SignMask) == SignDisallowed; const bool encryptDisallowed = (op & EncryptMask) == EncryptDisallowed; kleo_assert( !signDisallowed || !encryptDisallowed ); if ( !signDisallowed && encryptDisallowed ) return i18n( "Sign Files" ); if ( signDisallowed && !encryptDisallowed ) return i18n( "Encrypt Files" ); return i18n( "Sign/Encrypt Files" ); } SignEncryptFilesController::SignEncryptFilesController( QObject * p ) : Controller( p ), d( new Private( this ) ) { } SignEncryptFilesController::SignEncryptFilesController( const shared_ptr<const ExecutionContext> & ctx, QObject * p ) : Controller( ctx, p ), d( new Private( this ) ) { } SignEncryptFilesController::~SignEncryptFilesController() { kDebug(); if ( d->wizard && !d->wizard->isVisible() ) delete d->wizard; //d->wizard->close(); ### ? } void SignEncryptFilesController::setProtocol( Protocol proto ) { kleo_assert( d->protocol == UnknownProtocol || d->protocol == proto ); d->protocol = proto; d->ensureWizardCreated(); d->wizard->setPresetProtocol( proto ); } Protocol SignEncryptFilesController::protocol() const { return d->protocol; } // static void SignEncryptFilesController::Private::assertValidOperation( unsigned int op ) { kleo_assert( ( op & SignMask ) == SignDisallowed || ( op & SignMask ) == SignAllowed || ( op & SignMask ) == SignForced ); kleo_assert( ( op & EncryptMask ) == EncryptDisallowed || ( op & EncryptMask ) == EncryptAllowed || ( op & EncryptMask ) == EncryptForced ); kleo_assert( ( op & ~(SignMask|EncryptMask) ) == 0 ); } void SignEncryptFilesController::setOperationMode( unsigned int mode ) { Private::assertValidOperation( mode ); d->operation = mode; if ( d->wizard ) d->wizard->setWindowTitle( d->titleForOperation( d->operation ) ); } void SignEncryptFilesController::setFiles( const QStringList & files ) { kleo_assert( !files.empty() ); d->ensureWizardVisible(); d->wizard->setFiles( files ); } void SignEncryptFilesController::Private::slotWizardCanceled() { kDebug(); reportError( gpg_error( GPG_ERR_CANCELED ), i18n("User cancel") ); } void SignEncryptFilesController::start() { d->ensureWizardVisible(); } static shared_ptr<SignEncryptFilesTask> createSignEncryptTaskForFileInfo( const QFileInfo & fi, bool pgp, bool sign, bool encrypt, bool ascii, bool removeUnencrypted, const std::vector<Key> & recipients, const std::vector<Key> & signers ) { const shared_ptr<SignEncryptFilesTask> task( new SignEncryptFilesTask ); task->setSign( sign ); task->setEncrypt( encrypt ); task->setAsciiArmor( ascii ); task->setRemoveInputFileOnSuccess( removeUnencrypted ); if ( sign ) { task->setSigners( signers ); task->setDetachedSignature( true ); } if ( encrypt ) task->setRecipients( recipients ); unsigned int cls = pgp ? Class::OpenPGP : Class::CMS ; if ( encrypt ) cls |= Class::CipherText; else if ( sign ) cls |= Class::DetachedSignature; cls |= ascii ? Class::Ascii : Class::Binary ; const QString input = fi.absoluteFilePath(); task->setInputFileName( input ); const char * ext = outputFileExtension( cls ); if ( !ext ) ext = "out"; // ### error out? const QString output = input + '.' + ext; task->setOutputFileName( output ); return task; } static std::vector< shared_ptr<SignEncryptFilesTask> > createSignEncryptTasksForFileInfo( const QFileInfo & fi, bool sign, bool encrypt, bool ascii, bool removeUnencrypted, const std::vector<Key> & pgpRecipients, const std::vector<Key> & pgpSigners, const std::vector<Key> & cmsRecipients, const std::vector<Key> & cmsSigners ) { std::vector< shared_ptr<SignEncryptFilesTask> > result; const bool shallPgpSign = sign && !pgpSigners.empty(); const bool shallPgpEncrypt = encrypt && !pgpRecipients.empty(); const bool pgp = shallPgpEncrypt && ( !sign || shallPgpSign ) || !encrypt && shallPgpSign; const bool shallCmsSign = sign && !cmsSigners.empty(); const bool shallCmsEncrypt = encrypt && !cmsRecipients.empty(); const bool cms = shallCmsEncrypt && ( !sign || shallCmsSign ) || !encrypt && shallCmsSign; result.reserve( pgp + cms ); if ( pgp ) result.push_back( createSignEncryptTaskForFileInfo( fi, true, sign, encrypt, ascii, removeUnencrypted, pgpRecipients, pgpSigners ) ); if ( cms ) result.push_back( createSignEncryptTaskForFileInfo( fi, false, sign, encrypt, ascii, removeUnencrypted, cmsRecipients, cmsSigners ) ); return result; } void SignEncryptFilesController::Private::slotWizardOperationPrepared() { try { kleo_assert( wizard ); const bool sign = wizard->signingSelected(); const bool encrypt = wizard->encryptionSelected(); const bool ascii = wizard->isAsciiArmorEnabled(); const bool removeUnencrypted = wizard->removeUnencryptedFile(); const QFileInfoList files = wizard->resolvedFiles(); std::vector<Key> pgpRecipients, cmsRecipients, pgpSigners, cmsSigners; if ( encrypt ) { const std::vector<Key> recipients = wizard->resolvedCertificates(); kdtools::copy_if( recipients.begin(), recipients.end(), std::back_inserter( pgpRecipients ), bind( &Key::protocol, _1 ) == GpgME::OpenPGP ); kdtools::copy_if( recipients.begin(), recipients.end(), std::back_inserter( cmsRecipients ), bind( &Key::protocol, _1 ) == GpgME::CMS ); kleo_assert( pgpRecipients.size() + cmsRecipients.size() == recipients.size() ); } if ( sign ) { const std::vector<Key> signers = wizard->resolvedSigners(); kdtools::copy_if( signers.begin(), signers.end(), std::back_inserter( pgpSigners ), bind( &Key::protocol, _1 ) == GpgME::OpenPGP ); kdtools::copy_if( signers.begin(), signers.end(), std::back_inserter( cmsSigners ), bind( &Key::protocol, _1 ) == GpgME::CMS ); kleo_assert( pgpSigners.size() + cmsSigners.size() == signers.size() ); } kleo_assert( !files.empty() ); std::vector< shared_ptr<SignEncryptFilesTask> > tasks; tasks.reserve( files.size() ); Q_FOREACH( const QFileInfo & fi, files ) { const std::vector< shared_ptr<SignEncryptFilesTask> > created = createSignEncryptTasksForFileInfo( fi, sign, encrypt, ascii, removeUnencrypted, pgpRecipients, pgpSigners, cmsRecipients, cmsSigners ); tasks.insert( tasks.end(), created.begin(), created.end() ); } kleo_assert( runnable.empty() ); runnable.swap( tasks ); int i = 0; Q_FOREACH( const shared_ptr<Task> task, runnable ) connect( task.get(), SIGNAL(result(boost::shared_ptr<const Kleo::Crypto::Task::Result>)), q, SLOT(slotTaskDone()) ); ensureWizardCreated(); shared_ptr<TaskCollection> coll( new TaskCollection ); std::vector<shared_ptr<Task> > tmp; std::copy( runnable.begin(), runnable.end(), std::back_inserter( tmp ) ); coll->setTasks( tmp ); wizard->setTaskCollection( coll ); QTimer::singleShot( 0, q, SLOT(schedule()) ); } catch ( const Kleo::Exception & e ) { reportError( e.error().encodedError(), e.message() ); } catch ( const std::exception & e ) { reportError( gpg_error( GPG_ERR_UNEXPECTED ), i18n("Caught unexpected exception in SignEncryptFilesController::Private::slotWizardOperationPrepared: %1", QString::fromLocal8Bit( e.what() ) ) ); } catch ( ... ) { reportError( gpg_error( GPG_ERR_UNEXPECTED ), i18n("Caught unknown exception in SignEncryptFilesController::Private::slotWizardOperationPrepared") ); } } void SignEncryptFilesController::Private::schedule() { if ( !cms ) if ( const shared_ptr<SignEncryptFilesTask> t = takeRunnable( CMS ) ) { t->start(); cms = t; } if ( !openpgp ) if ( const shared_ptr<SignEncryptFilesTask> t = takeRunnable( OpenPGP ) ) { t->start(); openpgp = t; } if ( !cms && !openpgp ) { kleo_assert( runnable.empty() ); emit q->done(); } } shared_ptr<SignEncryptFilesTask> SignEncryptFilesController::Private::takeRunnable( GpgME::Protocol proto ) { const std::vector< shared_ptr<SignEncryptFilesTask> >::iterator it = std::find_if( runnable.begin(), runnable.end(), bind( &Task::protocol, _1 ) == proto ); if ( it == runnable.end() ) return shared_ptr<SignEncryptFilesTask>(); const shared_ptr<SignEncryptFilesTask> result = *it; runnable.erase( it ); return result; } void SignEncryptFilesController::Private::slotTaskDone() { assert( q->sender() ); // We could just delete the tasks here, but we can't use // Qt::QueuedConnection here (we need sender()) and other slots // might not yet have executed. Therefore, we push completed tasks // into a burial container if ( q->sender() == cms.get() ) { completed.push_back( cms ); cms.reset(); } else if ( q->sender() == openpgp.get() ) { completed.push_back( openpgp ); openpgp.reset(); } QTimer::singleShot( 0, q, SLOT(schedule()) ); } void SignEncryptFilesController::cancel() { kDebug(); try { if ( d->wizard ) d->wizard->close(); d->cancelAllTasks(); } catch ( const std::exception & e ) { qDebug( "Caught exception: %s", e.what() ); } } void SignEncryptFilesController::Private::cancelAllTasks() { // we just kill all runnable tasks - this will not result in // signal emissions. runnable.clear(); // a cancel() will result in a call to if ( cms ) cms->cancel(); if ( openpgp ) openpgp->cancel(); } void SignEncryptFilesController::Private::ensureWizardCreated() { if ( wizard ) return; std::auto_ptr<SignEncryptFilesWizard> w( new SignEncryptFilesWizard ); w->setWindowTitle( titleForOperation( operation ) ); w->setAttribute( Qt::WA_DeleteOnClose ); connect( w.get(), SIGNAL(operationPrepared()), q, SLOT(slotWizardOperationPrepared()), Qt::QueuedConnection ); connect( w.get(), SIGNAL(canceled()), q, SLOT(slotWizardCanceled()), Qt::QueuedConnection ); wizard = w.release(); } void SignEncryptFilesController::Private::ensureWizardVisible() { ensureWizardCreated(); q->bringToForeground( wizard ); } #include "moc_signencryptfilescontroller.cpp" <|endoftext|>
<commit_before>/* -------------------------------------------------------------------------- * * OpenSim: GCVSplineSet.cpp * * -------------------------------------------------------------------------- * * The OpenSim API is a toolkit for musculoskeletal modeling and simulation. * * See http://opensim.stanford.edu and the NOTICE file for more information. * * OpenSim is developed at Stanford University and supported by the US * * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA * * through the Warrior Web program. * * * * Copyright (c) 2005-2017 Stanford University and the Authors * * Author(s): Frank C. Anderson * * * * 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. * * -------------------------------------------------------------------------- */ /* Note: This code was originally developed by Realistic Dynamics Inc. * Author: Frank C. Anderson */ // INCLUDES #include "GCVSplineSet.h" #include "GCVSpline.h" #include "Storage.h" //============================================================================= // DESTRUCTOR AND CONSTRUCTORS //============================================================================= //_____________________________________________________________________________ using namespace OpenSim; /** * Destructor. */ GCVSplineSet::~GCVSplineSet() { } //_____________________________________________________________________________ /** * Default constructor. */ GCVSplineSet:: GCVSplineSet() { setNull(); } //_____________________________________________________________________________ /** * Construct a set of generalized cross-validated splines from file. * * @param aFileName Name of the file. */ GCVSplineSet:: GCVSplineSet(const char *aFileName) : FunctionSet(aFileName) { setNull(); } //_____________________________________________________________________________ /** * Construct a set of generalized cross-validated splines based on the states * stored in an Storage object. * * Each column in the Storage object is fit with a spline of the specified * degree and is named the name of its corresponding column label. Note that * column labels in the storage object are assumed to be tab delimited. * * @param aDegree Degree of the constructed splines (1, 3, 5, or 7). * @param aStore Storage object. * @param aErrorVariance Estimate of the variance of the error in the data to * be fit. If negative, the variance will be estimated. If 0.0, the fit will * try to fit the data points exactly- no smoothing. If * positive, the fits will be smoothed according to the specified variance. * The larger the error variance, the more the smoothing. Note that this is * the error variance assumed for each column in the Storage. If different * variances should be set for the various columns, you will need to * construct each GCVSpline individually. * @see Storage * @see GCVSpline */ GCVSplineSet:: GCVSplineSet(int aDegree,const Storage *aStore,double aErrorVariance) { setNull(); if(aStore==NULL) return; setName(aStore->getName()); // CAPACITY StateVector *vec = aStore->getStateVector(0); if(vec==NULL) return; ensureCapacity(2*vec->getSize()); // CONSTRUCT construct(aDegree,aStore,aErrorVariance); } //_____________________________________________________________________________ /** * Construct a set of generalized cross-validated splines based on the states * stored in a TimeSeriesTable. * * Each column in the TimeSeriesTable is fit with a spline of the specified * degree and is named the name of its corresponding column label. * * @param table TimeSeriesTable object. * @param labels Columns to use from TimeSeriesTable. * @param degree Degree of the constructed splines (1, 3, 5, or 7). * @param aErrorVariance Estimate of the variance of the error in the data to * be fit. If negative, the variance will be estimated. If 0.0, the fit will * try to fit the data points exactly- no smoothing. If * positive, the fits will be smoothed according to the specified variance. * The larger the error variance, the more the smoothing. Note that this is * the error variance assumed for each column in the Storage. If different * variances should be set for the various columns, you will need to * construct each GCVSpline individually. * @see Storage * @see GCVSpline */ GCVSplineSet:: GCVSplineSet(const TimeSeriesTable& table, const std::vector<std::string>& labels, int degree, double errorVariance) { const auto& time = table.getIndependentColumn(); auto labelsToUse = labels; if (labelsToUse.empty()) labelsToUse = table.getColumnLabels(); for (const auto& label : labelsToUse) { const auto& column = table.getDependentColumn(label); adoptAndAppend(new GCVSpline(degree, column.size(), time.data(), &column[0], label, errorVariance)); } } //============================================================================= // CONSTRUCTION //============================================================================= //_____________________________________________________________________________ /** * Set all member variables to NULL values. */ void GCVSplineSet:: setNull() { } //_____________________________________________________________________________ /** * Construct a set of generalized cross-validated splines based on the states * stored in an Storage object. * * @param aDegree Degree of the constructed splines (1, 3, 5, or 7). * @param aStore Storage object. * @param aErrorVariance Error variance for the data. */ void GCVSplineSet:: construct(int aDegree,const Storage *aStore,double aErrorVariance) { if(aStore==NULL) return; // DESCRIPTION setDescription(aStore->getDescription()); // GET COLUMN NAMES const Array<std::string> &labels = aStore->getColumnLabels(); char tmp[32]; std::string name; // LOOP THROUGH THE STATES int nTime=1,nData=1; double *times=NULL,*data=NULL; GCVSpline *spline; //printf("GCVSplineSet.construct: constructing splines...\n"); for(int i=0;nData>0;i++) { // GET TIMES AND DATA nTime = aStore->getTimeColumn(times,i); nData = aStore->getDataColumn(i,data); // CHECK if(nTime!=nData) { std::cout << "\nGCVSplineSet.construct: ERR- number of times (" << nTime << ")" << " and number of data (" << nData << ") don't agree.\n"; break; } if(nData==0) break; // GET COLUMN NAME // Note that state i is in column i+1 if(i+1 < labels.getSize()) { name = labels[i+1]; } else { sprintf(tmp,"data_%d",i); name = tmp; } // CONSTRUCT SPLINE //printf("%s\t",name); spline = new GCVSpline(aDegree,nData,times,data,name,aErrorVariance); SimTK::Function* fp = spline->createSimTKFunction(); delete fp; // ADD SPLINE adoptAndAppend(spline); } //printf("\n%d splines constructed.\n\n",i); // CLEANUP if(times!=NULL) delete[] times; if(data!=NULL) delete[] data; } //============================================================================= // SET AND GET //============================================================================= //_____________________________________________________________________________ /** * Get the function at a specified index. * * @param aIndex Index of the desired function: 0 <= aIndex < getSize(). * @return Function at index aIndex. If aIndex is not value NULL is returned. */ GCVSpline* GCVSplineSet:: getGCVSpline(int aIndex) const { GCVSpline& func = (GCVSpline&)get(aIndex); return(&func); } //============================================================================= // UTILITY //============================================================================= //_____________________________________________________________________________ /** * Construct a storage object (see Storage) for this spline \set\ or for some * derivative of this spline set. * * @param aDerivOrder Derivative order. 0 constructs from the spline, * 1 constructs from the first derivative of the spline, 2 constructs from * the second derivative of the spline, etc. * @param aDX Spacing of the data points in the independent variable. If * negative the spacing of the independent variable is taken from the * original data, as determined from the first non-NULL spline in the set. * aDX has a default value of -1. * @return Storage object. If a valid storage object cannot be constructed * NULL is returned. * @see Storage */ Storage* GCVSplineSet:: constructStorage(int aDerivOrder,double aDX) { if(aDerivOrder<0) return(NULL); if(getSize()<=0) return(NULL); // GET FIRST NON-NULL SPLINE GCVSpline *spl; int n = getSize(); for(int i=0;i<n;i++) { spl = getGCVSpline(i); if(spl!=NULL) break; } if(spl==NULL) return(NULL); // HOW MANY X STEPS double xRange = getMaxX() - getMinX(); int nSteps; if(aDX<=0.0) { nSteps = spl->getSize(); } else { nSteps = 10 + (int)(xRange/aDX); } // CONSTRUCT STORAGE OBJECT std::string name=""; if(aDerivOrder==0) { name=getName()+"_GCVSpline"; } else { char temp[10]; sprintf(temp, "%d", aDerivOrder); name=getName()+"_GCVSpline_Deriv_"+std::string(temp); } Storage *store = new Storage(nSteps,name); // DESCRIPTION store->setDescription(getDescription()); // SET COLUMN LABELS GCVSpline *spline; Array<std::string> labels; labels.append("time"); for(int i=0;i<n;i++) { spline = getGCVSpline(i); if(spline==NULL) { char cName[32]; sprintf(cName,"data_%d",i); labels.append(std::string(cName)); } else { labels.append(spline->getName()); } } store->setColumnLabels(labels); // SET STATES Array<double> y(0.0,n); // LOOP THROUGH THE DATA // constant increments if(aDX>0.0) { for(double x=getMinX(); x<=getMaxX(); x+=aDX) { evaluate(y,aDerivOrder,x); store->append(x,n,&y[0]); } // original independent variable increments } else { const Array<double> &xOrig = spl->getX(); for(int ix=0;ix<nSteps;ix++) { // ONLY WITHIN BOUNDS OF THE SET if(xOrig[ix]<getMinX()) continue; if(xOrig[ix]>getMaxX()) break; evaluate(y,aDerivOrder,xOrig[ix]); store->append(xOrig[ix],n,&y[0]); } } return(store); } double GCVSplineSet::getMinX() const { double min = SimTK::Infinity; for (int i=0; i<getSize(); i++) { const GCVSpline* spl = getGCVSpline(i); if (spl && spl->getMinX() < min) min = spl->getMinX(); } return min; } double GCVSplineSet::getMaxX() const { double max = -SimTK::Infinity; for (int i=0; i<getSize(); i++) { const GCVSpline* spl = getGCVSpline(i); if (spl && spl->getMaxX() > max) max = spl->getMaxX(); } return max; } <commit_msg>Fix comments. [skip ci]<commit_after>/* -------------------------------------------------------------------------- * * OpenSim: GCVSplineSet.cpp * * -------------------------------------------------------------------------- * * The OpenSim API is a toolkit for musculoskeletal modeling and simulation. * * See http://opensim.stanford.edu and the NOTICE file for more information. * * OpenSim is developed at Stanford University and supported by the US * * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA * * through the Warrior Web program. * * * * Copyright (c) 2005-2017 Stanford University and the Authors * * Author(s): Frank C. Anderson * * * * 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. * * -------------------------------------------------------------------------- */ /* Note: This code was originally developed by Realistic Dynamics Inc. * Author: Frank C. Anderson */ // INCLUDES #include "GCVSplineSet.h" #include "GCVSpline.h" #include "Storage.h" //============================================================================= // DESTRUCTOR AND CONSTRUCTORS //============================================================================= //_____________________________________________________________________________ using namespace OpenSim; /** * Destructor. */ GCVSplineSet::~GCVSplineSet() { } //_____________________________________________________________________________ /** * Default constructor. */ GCVSplineSet:: GCVSplineSet() { setNull(); } //_____________________________________________________________________________ /** * Construct a set of generalized cross-validated splines from file. * * @param aFileName Name of the file. */ GCVSplineSet:: GCVSplineSet(const char *aFileName) : FunctionSet(aFileName) { setNull(); } //_____________________________________________________________________________ /** * Construct a set of generalized cross-validated splines based on the states * stored in an Storage object. * * Each column in the Storage object is fit with a spline of the specified * degree and is named the name of its corresponding column label. Note that * column labels in the storage object are assumed to be tab delimited. * * @param aDegree Degree of the constructed splines (1, 3, 5, or 7). * @param aStore Storage object. * @param aErrorVariance Estimate of the variance of the error in the data to * be fit. If negative, the variance will be estimated. If 0.0, the fit will * try to fit the data points exactly- no smoothing. If * positive, the fits will be smoothed according to the specified variance. * The larger the error variance, the more the smoothing. Note that this is * the error variance assumed for each column in the Storage. If different * variances should be set for the various columns, you will need to * construct each GCVSpline individually. * @see Storage * @see GCVSpline */ GCVSplineSet:: GCVSplineSet(int aDegree,const Storage *aStore,double aErrorVariance) { setNull(); if(aStore==NULL) return; setName(aStore->getName()); // CAPACITY StateVector *vec = aStore->getStateVector(0); if(vec==NULL) return; ensureCapacity(2*vec->getSize()); // CONSTRUCT construct(aDegree,aStore,aErrorVariance); } //_____________________________________________________________________________ /** * Construct a set of generalized cross-validated splines based on the states * stored in a TimeSeriesTable. * * Each column in the TimeSeriesTable is fit with a spline of the specified * degree and is named the name of its corresponding column label. * * @param table TimeSeriesTable object. * @param labels Columns to use from TimeSeriesTable. * @param degree Degree of the constructed splines (1, 3, 5, or 7). * @param aErrorVariance Estimate of the variance of the error in the data to * be fit. If negative, the variance will be estimated. If 0.0, the fit will * try to fit the data points exactly- no smoothing. If * positive, the fits will be smoothed according to the specified variance. * The larger the error variance, the more the smoothing. Note that this is * the error variance assumed for each column in the TimeSeriesTable. If * different variances should be set for the various columns, you will need to * construct each GCVSpline individually. * @see TimeSeriesTable. * @see GCVSpline */ GCVSplineSet:: GCVSplineSet(const TimeSeriesTable& table, const std::vector<std::string>& labels, int degree, double errorVariance) { const auto& time = table.getIndependentColumn(); auto labelsToUse = labels; if (labelsToUse.empty()) labelsToUse = table.getColumnLabels(); for (const auto& label : labelsToUse) { const auto& column = table.getDependentColumn(label); adoptAndAppend(new GCVSpline(degree, column.size(), time.data(), &column[0], label, errorVariance)); } } //============================================================================= // CONSTRUCTION //============================================================================= //_____________________________________________________________________________ /** * Set all member variables to NULL values. */ void GCVSplineSet:: setNull() { } //_____________________________________________________________________________ /** * Construct a set of generalized cross-validated splines based on the states * stored in an Storage object. * * @param aDegree Degree of the constructed splines (1, 3, 5, or 7). * @param aStore Storage object. * @param aErrorVariance Error variance for the data. */ void GCVSplineSet:: construct(int aDegree,const Storage *aStore,double aErrorVariance) { if(aStore==NULL) return; // DESCRIPTION setDescription(aStore->getDescription()); // GET COLUMN NAMES const Array<std::string> &labels = aStore->getColumnLabels(); char tmp[32]; std::string name; // LOOP THROUGH THE STATES int nTime=1,nData=1; double *times=NULL,*data=NULL; GCVSpline *spline; //printf("GCVSplineSet.construct: constructing splines...\n"); for(int i=0;nData>0;i++) { // GET TIMES AND DATA nTime = aStore->getTimeColumn(times,i); nData = aStore->getDataColumn(i,data); // CHECK if(nTime!=nData) { std::cout << "\nGCVSplineSet.construct: ERR- number of times (" << nTime << ")" << " and number of data (" << nData << ") don't agree.\n"; break; } if(nData==0) break; // GET COLUMN NAME // Note that state i is in column i+1 if(i+1 < labels.getSize()) { name = labels[i+1]; } else { sprintf(tmp,"data_%d",i); name = tmp; } // CONSTRUCT SPLINE //printf("%s\t",name); spline = new GCVSpline(aDegree,nData,times,data,name,aErrorVariance); SimTK::Function* fp = spline->createSimTKFunction(); delete fp; // ADD SPLINE adoptAndAppend(spline); } //printf("\n%d splines constructed.\n\n",i); // CLEANUP if(times!=NULL) delete[] times; if(data!=NULL) delete[] data; } //============================================================================= // SET AND GET //============================================================================= //_____________________________________________________________________________ /** * Get the function at a specified index. * * @param aIndex Index of the desired function: 0 <= aIndex < getSize(). * @return Function at index aIndex. If aIndex is not value NULL is returned. */ GCVSpline* GCVSplineSet:: getGCVSpline(int aIndex) const { GCVSpline& func = (GCVSpline&)get(aIndex); return(&func); } //============================================================================= // UTILITY //============================================================================= //_____________________________________________________________________________ /** * Construct a storage object (see Storage) for this spline \set\ or for some * derivative of this spline set. * * @param aDerivOrder Derivative order. 0 constructs from the spline, * 1 constructs from the first derivative of the spline, 2 constructs from * the second derivative of the spline, etc. * @param aDX Spacing of the data points in the independent variable. If * negative the spacing of the independent variable is taken from the * original data, as determined from the first non-NULL spline in the set. * aDX has a default value of -1. * @return Storage object. If a valid storage object cannot be constructed * NULL is returned. * @see Storage */ Storage* GCVSplineSet:: constructStorage(int aDerivOrder,double aDX) { if(aDerivOrder<0) return(NULL); if(getSize()<=0) return(NULL); // GET FIRST NON-NULL SPLINE GCVSpline *spl; int n = getSize(); for(int i=0;i<n;i++) { spl = getGCVSpline(i); if(spl!=NULL) break; } if(spl==NULL) return(NULL); // HOW MANY X STEPS double xRange = getMaxX() - getMinX(); int nSteps; if(aDX<=0.0) { nSteps = spl->getSize(); } else { nSteps = 10 + (int)(xRange/aDX); } // CONSTRUCT STORAGE OBJECT std::string name=""; if(aDerivOrder==0) { name=getName()+"_GCVSpline"; } else { char temp[10]; sprintf(temp, "%d", aDerivOrder); name=getName()+"_GCVSpline_Deriv_"+std::string(temp); } Storage *store = new Storage(nSteps,name); // DESCRIPTION store->setDescription(getDescription()); // SET COLUMN LABELS GCVSpline *spline; Array<std::string> labels; labels.append("time"); for(int i=0;i<n;i++) { spline = getGCVSpline(i); if(spline==NULL) { char cName[32]; sprintf(cName,"data_%d",i); labels.append(std::string(cName)); } else { labels.append(spline->getName()); } } store->setColumnLabels(labels); // SET STATES Array<double> y(0.0,n); // LOOP THROUGH THE DATA // constant increments if(aDX>0.0) { for(double x=getMinX(); x<=getMaxX(); x+=aDX) { evaluate(y,aDerivOrder,x); store->append(x,n,&y[0]); } // original independent variable increments } else { const Array<double> &xOrig = spl->getX(); for(int ix=0;ix<nSteps;ix++) { // ONLY WITHIN BOUNDS OF THE SET if(xOrig[ix]<getMinX()) continue; if(xOrig[ix]>getMaxX()) break; evaluate(y,aDerivOrder,xOrig[ix]); store->append(xOrig[ix],n,&y[0]); } } return(store); } double GCVSplineSet::getMinX() const { double min = SimTK::Infinity; for (int i=0; i<getSize(); i++) { const GCVSpline* spl = getGCVSpline(i); if (spl && spl->getMinX() < min) min = spl->getMinX(); } return min; } double GCVSplineSet::getMaxX() const { double max = -SimTK::Infinity; for (int i=0; i<getSize(); i++) { const GCVSpline* spl = getGCVSpline(i); if (spl && spl->getMaxX() > max) max = spl->getMaxX(); } return max; } <|endoftext|>
<commit_before>/* FasTC * Copyright (c) 2013 University of North Carolina at Chapel Hill. * All rights reserved. * * Permission to use, copy, modify, and distribute this software and its * documentation for educational, research, and non-profit purposes, without * fee, and without a written agreement is hereby granted, provided that the * above copyright notice, this paragraph, and the following four paragraphs * appear in all copies. * * Permission to incorporate this software into commercial products may be * obtained by contacting the authors or the Office of Technology Development * at the University of North Carolina at Chapel Hill <otd@unc.edu>. * * This software program and documentation are copyrighted by the University of * North Carolina at Chapel Hill. The software program and documentation are * supplied "as is," without any accompanying services from the University of * North Carolina at Chapel Hill or the authors. The University of North * Carolina at Chapel Hill and the authors do not warrant that the operation of * the program will be uninterrupted or error-free. The end-user understands * that the program was developed for research purposes and is advised not to * rely exclusively on the program for any reason. * * IN NO EVENT SHALL THE UNIVERSITY OF NORTH CAROLINA AT CHAPEL HILL OR THE * AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, * OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF * THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF NORTH CAROLINA * AT CHAPEL HILL OR THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. * * THE UNIVERSITY OF NORTH CAROLINA AT CHAPEL HILL AND THE AUTHORS SPECIFICALLY * DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE AND ANY * STATUTORY WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE PROVIDED HEREUNDER IS ON * AN "AS IS" BASIS, AND THE UNIVERSITY OF NORTH CAROLINA AT CHAPEL HILL AND * THE AUTHORS HAVE NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, * ENHANCEMENTS, OR MODIFICATIONS. * * Please send all BUG REPORTS to <pavel@cs.unc.edu>. * * The authors may be contacted via: * * Pavel Krajcevski * Dept of Computer Science * 201 S Columbia St * Frederick P. Brooks, Jr. Computer Science Bldg * Chapel Hill, NC 27599-3175 * USA * * <http://gamma.cs.unc.edu/FasTC/> */ #include "gtest/gtest.h" #include "Image.h" #include "Pixel.h" TEST(Image, NonSpecificConstructor) { PVRTCC::Pixel p; PVRTCC::Image img (4, 4); for(int i = 0; i < 4; i++) { for(int j = 0; j < 4; j++) { EXPECT_TRUE(img(i, j) == p); } } } TEST(Image, SpecificConstructor) { PVRTCC::Pixel pxs[16]; for(int i = 0; i < 4; i++) { for(int j = 0; j < 4; j++) { pxs[j*4 + i].R() = i; pxs[j*4 + i].G() = j; } } PVRTCC::Image img(4, 4, pxs); for(int i = 0; i < 4; i++) { for(int j = 0; j < 4; j++) { EXPECT_TRUE(img(i, j) == pxs[j*4 + i]); } } } TEST(Image, CopyConstructor) { PVRTCC::Pixel pxs[16]; for(int i = 0; i < 4; i++) { for(int j = 0; j < 4; j++) { pxs[j*4 + i].R() = i; pxs[j*4 + i].G() = j; } } PVRTCC::Image img(4, 4, pxs); PVRTCC::Image img2(img); for(int i = 0; i < 4; i++) { for(int j = 0; j < 4; j++) { EXPECT_TRUE(img2(i, j) == pxs[j*4 + i]); } } } TEST(Image, AssignmentOperator) { PVRTCC::Pixel pxs[16]; for(int i = 0; i < 4; i++) { for(int j = 0; j < 4; j++) { pxs[j*4 + i].R() = i; pxs[j*4 + i].G() = j; } } PVRTCC::Image img(4, 4, pxs); PVRTCC::Image img2 = img; for(int i = 0; i < 4; i++) { for(int j = 0; j < 4; j++) { EXPECT_TRUE(img2(i, j) == pxs[j*4 + i]); } } } TEST(Image, BilinearUpscale) { PVRTCC::Pixel pxs[16]; for(int i = 0; i < 4; i++) { for(int j = 0; j < 4; j++) { pxs[j*4 + i].R() = i*2; pxs[j*4 + i].G() = j*2; } } PVRTCC::Image img(4, 4, pxs); img.BilinearUpscale(1); EXPECT_EQ(img.GetWidth(), static_cast<uint32>(8)); EXPECT_EQ(img.GetHeight(), static_cast<uint32>(8)); for(uint32 i = 0; i < img.GetWidth(); i++) { for(uint32 j = 0; j < img.GetHeight(); j++) { if(i == 0) { EXPECT_EQ(img(i, j).R(), i); } else { EXPECT_EQ(img(i, j).R(), i-1); } if(j == 0) { EXPECT_EQ(img(i, j).G(), j); } else { EXPECT_EQ(img(i, j).G(), j-1); } } } } TEST(Image, BilinearUpscaleWrapped) { PVRTCC::Pixel pxs[16]; // Make sure that our bit depth is less than full... for(int i = 0; i < 16; i++) { const uint8 newBitDepth[4] = { 6, 5, 6, 5 }; pxs[i].ChangeBitDepth(newBitDepth); } for(int i = 0; i < 4; i++) { for(int j = 0; j < 4; j++) { pxs[j*4 + i].R() = i*4; pxs[j*4 + i].G() = j*4; } } PVRTCC::Image img(4, 4, pxs); img.BilinearUpscale(2, PVRTCC::eWrapMode_Wrap); EXPECT_EQ(img.GetWidth(), static_cast<uint32>(16)); EXPECT_EQ(img.GetHeight(), static_cast<uint32>(16)); for(uint32 i = 0; i < img.GetWidth(); i++) { for(uint32 j = 0; j < img.GetHeight(); j++) { const PVRTCC::Pixel &p = img(i, j); // First make sure that the bit depth didn't change uint8 depth[4]; p.GetBitDepth(depth); EXPECT_EQ(depth[0], 6); EXPECT_EQ(depth[1], 5); EXPECT_EQ(depth[2], 6); EXPECT_EQ(depth[3], 5); // Now make sure that the values are correct. if(i == 0) { EXPECT_EQ(p.R(), 6); } else if(i == 1) { EXPECT_EQ(p.R(), 3); } else if(i == 15) { EXPECT_EQ(p.R(), 9); } else { EXPECT_EQ(p.R(), i-2); } if(j == 0) { EXPECT_EQ(p.G(), 6); } else if(j == 1) { EXPECT_EQ(p.G(), 3); } else if(j == 15) { EXPECT_EQ(p.G(), 9); } else { EXPECT_EQ(p.G(), j-2); } } } } TEST(Image, ChangeBitDepth) { PVRTCC::Image img(4, 4); uint8 testDepth[4] = { 2, 3, 5, 0 }; img.ChangeBitDepth(testDepth); uint8 depth[4]; for(uint32 j = 0; j < img.GetHeight(); j++) { for(uint32 i = 0; i < img.GetWidth(); i++) { img(i, j).GetBitDepth(depth); for(int d = 0; d < 4; d++) { EXPECT_EQ(testDepth[d], depth[d]); } } } } <commit_msg>Add a test to make sure that after a bilerp the pixels that should remain unaffected do in fact remain unaffected.<commit_after>/* FasTC * Copyright (c) 2013 University of North Carolina at Chapel Hill. * All rights reserved. * * Permission to use, copy, modify, and distribute this software and its * documentation for educational, research, and non-profit purposes, without * fee, and without a written agreement is hereby granted, provided that the * above copyright notice, this paragraph, and the following four paragraphs * appear in all copies. * * Permission to incorporate this software into commercial products may be * obtained by contacting the authors or the Office of Technology Development * at the University of North Carolina at Chapel Hill <otd@unc.edu>. * * This software program and documentation are copyrighted by the University of * North Carolina at Chapel Hill. The software program and documentation are * supplied "as is," without any accompanying services from the University of * North Carolina at Chapel Hill or the authors. The University of North * Carolina at Chapel Hill and the authors do not warrant that the operation of * the program will be uninterrupted or error-free. The end-user understands * that the program was developed for research purposes and is advised not to * rely exclusively on the program for any reason. * * IN NO EVENT SHALL THE UNIVERSITY OF NORTH CAROLINA AT CHAPEL HILL OR THE * AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, * OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF * THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF NORTH CAROLINA * AT CHAPEL HILL OR THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. * * THE UNIVERSITY OF NORTH CAROLINA AT CHAPEL HILL AND THE AUTHORS SPECIFICALLY * DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE AND ANY * STATUTORY WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE PROVIDED HEREUNDER IS ON * AN "AS IS" BASIS, AND THE UNIVERSITY OF NORTH CAROLINA AT CHAPEL HILL AND * THE AUTHORS HAVE NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, * ENHANCEMENTS, OR MODIFICATIONS. * * Please send all BUG REPORTS to <pavel@cs.unc.edu>. * * The authors may be contacted via: * * Pavel Krajcevski * Dept of Computer Science * 201 S Columbia St * Frederick P. Brooks, Jr. Computer Science Bldg * Chapel Hill, NC 27599-3175 * USA * * <http://gamma.cs.unc.edu/FasTC/> */ #include "gtest/gtest.h" #include "Image.h" #include "Pixel.h" #include "TestUtils.h" #include <cstdlib> TEST(Image, NonSpecificConstructor) { PVRTCC::Pixel p; PVRTCC::Image img (4, 4); for(int i = 0; i < 4; i++) { for(int j = 0; j < 4; j++) { EXPECT_TRUE(img(i, j) == p); } } } TEST(Image, SpecificConstructor) { PVRTCC::Pixel pxs[16]; for(int i = 0; i < 4; i++) { for(int j = 0; j < 4; j++) { pxs[j*4 + i].R() = i; pxs[j*4 + i].G() = j; } } PVRTCC::Image img(4, 4, pxs); for(int i = 0; i < 4; i++) { for(int j = 0; j < 4; j++) { EXPECT_TRUE(img(i, j) == pxs[j*4 + i]); } } } TEST(Image, CopyConstructor) { PVRTCC::Pixel pxs[16]; for(int i = 0; i < 4; i++) { for(int j = 0; j < 4; j++) { pxs[j*4 + i].R() = i; pxs[j*4 + i].G() = j; } } PVRTCC::Image img(4, 4, pxs); PVRTCC::Image img2(img); for(int i = 0; i < 4; i++) { for(int j = 0; j < 4; j++) { EXPECT_TRUE(img2(i, j) == pxs[j*4 + i]); } } } TEST(Image, AssignmentOperator) { PVRTCC::Pixel pxs[16]; for(int i = 0; i < 4; i++) { for(int j = 0; j < 4; j++) { pxs[j*4 + i].R() = i; pxs[j*4 + i].G() = j; } } PVRTCC::Image img(4, 4, pxs); PVRTCC::Image img2 = img; for(int i = 0; i < 4; i++) { for(int j = 0; j < 4; j++) { EXPECT_TRUE(img2(i, j) == pxs[j*4 + i]); } } } TEST(Image, BilinearUpscale) { PVRTCC::Pixel pxs[16]; for(int i = 0; i < 4; i++) { for(int j = 0; j < 4; j++) { pxs[j*4 + i].R() = i*2; pxs[j*4 + i].G() = j*2; } } PVRTCC::Image img(4, 4, pxs); img.BilinearUpscale(1); EXPECT_EQ(img.GetWidth(), static_cast<uint32>(8)); EXPECT_EQ(img.GetHeight(), static_cast<uint32>(8)); for(uint32 i = 0; i < img.GetWidth(); i++) { for(uint32 j = 0; j < img.GetHeight(); j++) { if(i == 0) { EXPECT_EQ(img(i, j).R(), i); } else { EXPECT_EQ(img(i, j).R(), i-1); } if(j == 0) { EXPECT_EQ(img(i, j).G(), j); } else { EXPECT_EQ(img(i, j).G(), j-1); } } } } TEST(Image, BilinearUpscaleMaintainsPixels) { srand(0xabd1ca7e); const uint32 w = 4; const uint32 h = 4; PVRTCC::Pixel pxs[16]; for(int i = 0; i < w; i++) { for(int j = 0; j < h; j++) { pxs[j*w + i].R() = rand() % 256; pxs[j*w + i].G() = rand() % 256; pxs[j*w + i].B() = rand() % 256; pxs[j*w + i].A() = rand() % 256; } } PVRTCC::Image img(w, h, pxs); img.BilinearUpscale(2); EXPECT_EQ(img.GetWidth(), w << 2); EXPECT_EQ(img.GetHeight(), h << 2); for(uint32 i = 2; i < img.GetWidth(); i+=4) { for(uint32 j = 2; j < img.GetHeight(); j+=4) { PVRTCC::Pixel p = img(i, j); uint32 idx = ((j - 2) / 4) * w + ((i-2)/4); EXPECT_EQ(PixelPrinter(p.PackRGBA()), PixelPrinter(pxs[idx].PackRGBA())); } } } TEST(Image, BilinearUpscaleWrapped) { PVRTCC::Pixel pxs[16]; // Make sure that our bit depth is less than full... for(int i = 0; i < 16; i++) { const uint8 newBitDepth[4] = { 6, 5, 6, 5 }; pxs[i].ChangeBitDepth(newBitDepth); } for(int i = 0; i < 4; i++) { for(int j = 0; j < 4; j++) { pxs[j*4 + i].R() = i*4; pxs[j*4 + i].G() = j*4; } } PVRTCC::Image img(4, 4, pxs); img.BilinearUpscale(2, PVRTCC::eWrapMode_Wrap); EXPECT_EQ(img.GetWidth(), static_cast<uint32>(16)); EXPECT_EQ(img.GetHeight(), static_cast<uint32>(16)); for(uint32 i = 0; i < img.GetWidth(); i++) { for(uint32 j = 0; j < img.GetHeight(); j++) { const PVRTCC::Pixel &p = img(i, j); // First make sure that the bit depth didn't change uint8 depth[4]; p.GetBitDepth(depth); EXPECT_EQ(depth[0], 6); EXPECT_EQ(depth[1], 5); EXPECT_EQ(depth[2], 6); EXPECT_EQ(depth[3], 5); // Now make sure that the values are correct. if(i == 0) { EXPECT_EQ(p.R(), 6); } else if(i == 1) { EXPECT_EQ(p.R(), 3); } else if(i == 15) { EXPECT_EQ(p.R(), 9); } else { EXPECT_EQ(p.R(), i-2); } if(j == 0) { EXPECT_EQ(p.G(), 6); } else if(j == 1) { EXPECT_EQ(p.G(), 3); } else if(j == 15) { EXPECT_EQ(p.G(), 9); } else { EXPECT_EQ(p.G(), j-2); } } } } TEST(Image, ChangeBitDepth) { PVRTCC::Image img(4, 4); uint8 testDepth[4] = { 2, 3, 5, 0 }; img.ChangeBitDepth(testDepth); uint8 depth[4]; for(uint32 j = 0; j < img.GetHeight(); j++) { for(uint32 i = 0; i < img.GetWidth(); i++) { img(i, j).GetBitDepth(depth); for(int d = 0; d < 4; d++) { EXPECT_EQ(testDepth[d], depth[d]); } } } } <|endoftext|>
<commit_before>#include "AliGFWWeights.h" #include "TMath.h" AliGFWWeights::AliGFWWeights(): fDataFilled(kFALSE), fMCFilled(kFALSE), fW_data(0), fW_mcrec(0), fW_mcgen(0), fEffInt(0), fAccInt(0), fNbinsPt(0), fbinsPt(0) { }; AliGFWWeights::~AliGFWWeights() { delete fW_data; delete fW_mcrec; delete fW_mcgen; delete fEffInt; delete fAccInt; if(fbinsPt) delete [] fbinsPt; }; void AliGFWWeights::SetPtBins(Int_t Nbins, Double_t *bins) { if(fbinsPt) delete [] fbinsPt; fNbinsPt = Nbins; fbinsPt = new Double_t[fNbinsPt+1]; for(Int_t i=0;i<=fNbinsPt;++i) fbinsPt[i] = bins[i]; }; void AliGFWWeights::Init(Bool_t AddData, Bool_t AddMC) { fW_data = new TObjArray(); fW_data->SetName("AliGFWWeights_Data"); fW_mcrec = new TObjArray(); fW_mcrec->SetName("AliGFWWeights_MCRec"); fW_mcgen = new TObjArray(); fW_mcgen->SetName("AliGFWWeights_MCGen"); fW_data->SetOwner(kTRUE); fW_mcrec->SetOwner(kTRUE); fW_mcgen->SetOwner(kTRUE); fDataFilled = kFALSE; fMCFilled = kFALSE; if(!fbinsPt) { //If pT bins not initialized, set to default (-1 to 1e6) to accept everything fNbinsPt=1; fbinsPt = new Double_t[2]; fbinsPt[0] = -1; fbinsPt[1] = 1e6; }; if(AddData) { const char *tnd = GetBinName(0,0,Form("data_%s",this->GetName())); fW_data->Add(new TH3D(tnd,";#varphi;#eta;v_{z}",60,0,TMath::TwoPi(),64,-1.6,1.6,40,-10,10)); }; if(AddMC) { const char *tnr = GetBinName(0,0,"mcrec"); //all integrated over cent. anyway const char *tng = GetBinName(0,0,"mcgen"); //all integrated over cent. anyway fW_mcrec->Add(new TH3D(tnr,";#it{p}_{T};#eta;v_{z}",fNbinsPt,0,20,64,-1.6,1.6,40,-10,10)); fW_mcgen->Add(new TH3D(tng,";#it{p}_{T};#eta;v_{z}",fNbinsPt,0,20,64,-1.6,1.6,40,-10,10)); ((TH3D*)fW_mcrec->At(fW_mcrec->GetEntries()-1))->GetXaxis()->Set(fNbinsPt,fbinsPt); ((TH3D*)fW_mcgen->At(fW_mcgen->GetEntries()-1))->GetXaxis()->Set(fNbinsPt,fbinsPt); }; }; void AliGFWWeights::Fill(Double_t phi, Double_t eta, Double_t vz, Double_t pt, Double_t cent, Int_t htype) { TObjArray *tar=0; const char *pf=""; if(htype==0) { tar = fW_data; pf = Form("data_%s",this->GetName()); }; if(htype==1) { tar = fW_mcrec; pf = "mcrec"; }; if(htype==2) { tar = fW_mcgen; pf = "mcgen"; }; if(!tar) return; TH3D *th3 = (TH3D*)tar->FindObject(GetBinName(0,0,pf)); //pT bin 0, V0M bin 0, since all integrated if(!th3) { if(!htype) tar->Add(new TH3D(GetBinName(0,0,pf),";#varphi;#eta;v_{z}",60,0,TMath::TwoPi(),64,-1.6,1.6,40,-10,10)); //0,0 since all integrated th3 = (TH3D*)tar->At(tar->GetEntries()-1); }; th3->Fill(htype?pt:phi,eta,vz); }; Double_t AliGFWWeights::GetWeight(Double_t phi, Double_t eta, Double_t vz, Double_t pt, Double_t cent, Int_t htype) { TObjArray *tar=0; const char *pf=""; if(htype==0) { tar = fW_data; pf = "data"; }; if(htype==1) { tar = fW_mcrec; pf = "mcrec"; }; if(htype==2) { tar = fW_mcgen; pf = "mcgen"; }; if(!tar) return 1; TH3D *th3 = (TH3D*)tar->FindObject(GetBinName(0,0,pf)); if(!th3) return 1;//-1; Int_t xind = th3->GetXaxis()->FindBin(htype?pt:phi); Int_t etaind = th3->GetYaxis()->FindBin(eta); Int_t vzind = th3->GetZaxis()->FindBin(vz); Double_t weight = th3->GetBinContent(xind, etaind, vzind); if(weight!=0) return 1./weight; return 1; }; Double_t AliGFWWeights::FindMax(TH3D *inh, Int_t &ix, Int_t &iy, Int_t &iz) { Double_t maxv=inh->GetBinContent(1,1,1); for(Int_t i=1;i<=inh->GetNbinsX();i++) for(Int_t j=1;j<=inh->GetNbinsY();j++) for(Int_t k=1;k<=inh->GetNbinsZ();k++) if(inh->GetBinContent(i,j,k)>maxv) { ix=i; iy=j; iz=k; maxv=inh->GetBinContent(i,j,k); }; return maxv; }; void AliGFWWeights::MCToEfficiency() { if(fW_mcgen->GetEntries()<1) { printf("MC gen. array empty. This is probably because effs. have been calculated and the generated particle histograms have been cleared out!\n"); return; }; for(Int_t i=0;i<fW_mcrec->GetEntries();i++) { TH3D *hr = (TH3D*)fW_mcrec->At(i); TH3D *hg = (TH3D*)fW_mcgen->At(i); hr->Sumw2(); hg->Sumw2(); hr->Divide(hg); }; fW_mcgen->Clear(); }; void AliGFWWeights::CreateNUA(Bool_t IntegrateOverCentAndPt) { if(!IntegrateOverCentAndPt) { printf("Method is outdated! NUA is integrated over centrality and pT. Quit now, or the behaviour will be bad\n"); return; }; TH3D *h3; TH1D *h1; if(fW_data->GetEntries()<1) return; if(IntegrateOverCentAndPt) { if(fAccInt) delete fAccInt; fAccInt = (TH3D*)fW_data->At(0)->Clone("IntegratedAcceptance"); fAccInt->RebinY(2); fAccInt->RebinZ(5); fAccInt->Sumw2(); for(Int_t etai=1;etai<=fAccInt->GetNbinsY();etai++) { fAccInt->GetYaxis()->SetRange(etai,etai); if(fAccInt->Integral()<1) continue; for(Int_t vzi=1;vzi<=fAccInt->GetNbinsZ();vzi++) { fAccInt->GetZaxis()->SetRange(vzi,vzi); if(fAccInt->Integral()<1) continue; h1 = (TH1D*)fAccInt->Project3D("x"); Double_t maxv = h1->GetMaximum(); for(Int_t phii=1;phii<=h1->GetNbinsX();phii++) fAccInt->SetBinContent(phii,etai,vzi,fAccInt->GetBinContent(phii,etai,vzi)/maxv); delete h1; }; fAccInt->GetZaxis()->SetRange(1,fAccInt->GetNbinsZ()); }; fAccInt->GetYaxis()->SetRange(1,fAccInt->GetNbinsY()); return; }; }; void AliGFWWeights::CreateNUE(Bool_t IntegrateOverCentrality) { if(!IntegrateOverCentrality) { printf("Method is outdated! NUE is integrated over centrality. Quit now, or the behaviour will be bad\n"); return; }; TH3D *num=0; TH3D *den=0; if(fW_mcrec->GetEntries()<1 || fW_mcgen->GetEntries()<1) return; if(IntegrateOverCentrality) { num=(TH3D*)fW_mcrec->At(0);//->Clone(Form("temp_%s",fW_mcrec->At(0)->GetName())); den=(TH3D*)fW_mcgen->At(0);//->Clone(Form("temp_%s",fW_mcgen->At(0)->GetName())); num->Sumw2(); den->Sumw2(); num->RebinY(2); den->RebinY(2); num->RebinZ(5); den->RebinZ(5); fEffInt = (TH3D*)num->Clone("Efficiency_Integrated"); fEffInt->Divide(den); return; }; }; void AliGFWWeights::ReadAndMerge(const char *filelinks) { FILE *flist = fopen(filelinks,"r"); char str[150]; Int_t nFiles=0; while(fscanf(flist,"%s\n",str)==1) nFiles++; rewind(flist); if(nFiles==0) { printf("No files to read!\n"); return; }; if(!fW_data) { fW_data = new TObjArray(); fW_data->SetName("Weights_Data"); fW_data->SetOwner(kTRUE); }; if(!fW_mcrec) { fW_mcrec = new TObjArray(); fW_mcrec->SetName("Weights_MCRec"); fW_mcrec->SetOwner(kTRUE); }; if(!fW_mcgen) { fW_mcgen = new TObjArray(); fW_mcgen->SetName("Weights_MCGen"); fW_mcgen->SetOwner(kTRUE); }; fDataFilled = kFALSE; fMCFilled = kFALSE; TFile *tf=0; for(Int_t i=0;i<nFiles;i++) { Int_t trash = fscanf(flist,"%s\n",str); tf = new TFile(str,"READ"); if(tf->IsZombie()) { printf("Could not open file %s!\n",str); tf->Close(); continue; }; TList *tl = (TList*)tf->Get("OutputList"); AliGFWWeights *tw = (AliGFWWeights*)tl->FindObject(this->GetName()); if(!tw) { printf("Could not fetch weights object from %s\n",str); tf->Close(); continue; }; AddArray(fW_data,tw->GetDataArray()); AddArray(fW_mcrec,tw->GetRecArray()); AddArray(fW_mcgen,tw->GetGenArray()); tf->Close(); delete tw; }; }; void AliGFWWeights::AddArray(TObjArray *targ, TObjArray *sour) { if(!sour) { printf("Source array does not exist!\n"); return; }; for(Int_t i=0;i<sour->GetEntries();i++) { TH3D *sourh = (TH3D*)sour->At(i); TH3D *targh = (TH3D*)targ->FindObject(sourh->GetName()); if(!targh) { targh = (TH3D*)sourh->Clone(sourh->GetName()); targh->SetDirectory(0); targ->Add(targh); } else targh->Add(sourh); }; }; Long64_t AliGFWWeights::Merge(TCollection *collist) { Long64_t nmerged=0; if(!fW_data) { fW_data = new TObjArray(); fW_data->SetName("Weights_Data"); fW_data->SetOwner(kTRUE); }; if(!fW_mcrec) { fW_mcrec = new TObjArray(); fW_mcrec->SetName("Weights_MCRec"); fW_mcrec->SetOwner(kTRUE); }; if(!fW_mcgen) { fW_mcgen = new TObjArray(); fW_mcgen->SetName("Weights_MCGen"); fW_mcgen->SetOwner(kTRUE); }; AliGFWWeights *l_w = 0; TIter all_w(collist); while (l_w = (AliGFWWeights*) all_w()) { AddArray(fW_data,l_w->GetDataArray()); AddArray(fW_mcrec,tw->GetRecArray()); AddArray(fW_mcgen,tw->GetGenArray()); nmerged++; }; return nmerged; }; <commit_msg>Fixed the wrong variable name in AliGFWWeights<commit_after>#include "AliGFWWeights.h" #include "TMath.h" AliGFWWeights::AliGFWWeights(): fDataFilled(kFALSE), fMCFilled(kFALSE), fW_data(0), fW_mcrec(0), fW_mcgen(0), fEffInt(0), fAccInt(0), fNbinsPt(0), fbinsPt(0) { }; AliGFWWeights::~AliGFWWeights() { delete fW_data; delete fW_mcrec; delete fW_mcgen; delete fEffInt; delete fAccInt; if(fbinsPt) delete [] fbinsPt; }; void AliGFWWeights::SetPtBins(Int_t Nbins, Double_t *bins) { if(fbinsPt) delete [] fbinsPt; fNbinsPt = Nbins; fbinsPt = new Double_t[fNbinsPt+1]; for(Int_t i=0;i<=fNbinsPt;++i) fbinsPt[i] = bins[i]; }; void AliGFWWeights::Init(Bool_t AddData, Bool_t AddMC) { fW_data = new TObjArray(); fW_data->SetName("AliGFWWeights_Data"); fW_mcrec = new TObjArray(); fW_mcrec->SetName("AliGFWWeights_MCRec"); fW_mcgen = new TObjArray(); fW_mcgen->SetName("AliGFWWeights_MCGen"); fW_data->SetOwner(kTRUE); fW_mcrec->SetOwner(kTRUE); fW_mcgen->SetOwner(kTRUE); fDataFilled = kFALSE; fMCFilled = kFALSE; if(!fbinsPt) { //If pT bins not initialized, set to default (-1 to 1e6) to accept everything fNbinsPt=1; fbinsPt = new Double_t[2]; fbinsPt[0] = -1; fbinsPt[1] = 1e6; }; if(AddData) { const char *tnd = GetBinName(0,0,Form("data_%s",this->GetName())); fW_data->Add(new TH3D(tnd,";#varphi;#eta;v_{z}",60,0,TMath::TwoPi(),64,-1.6,1.6,40,-10,10)); }; if(AddMC) { const char *tnr = GetBinName(0,0,"mcrec"); //all integrated over cent. anyway const char *tng = GetBinName(0,0,"mcgen"); //all integrated over cent. anyway fW_mcrec->Add(new TH3D(tnr,";#it{p}_{T};#eta;v_{z}",fNbinsPt,0,20,64,-1.6,1.6,40,-10,10)); fW_mcgen->Add(new TH3D(tng,";#it{p}_{T};#eta;v_{z}",fNbinsPt,0,20,64,-1.6,1.6,40,-10,10)); ((TH3D*)fW_mcrec->At(fW_mcrec->GetEntries()-1))->GetXaxis()->Set(fNbinsPt,fbinsPt); ((TH3D*)fW_mcgen->At(fW_mcgen->GetEntries()-1))->GetXaxis()->Set(fNbinsPt,fbinsPt); }; }; void AliGFWWeights::Fill(Double_t phi, Double_t eta, Double_t vz, Double_t pt, Double_t cent, Int_t htype) { TObjArray *tar=0; const char *pf=""; if(htype==0) { tar = fW_data; pf = Form("data_%s",this->GetName()); }; if(htype==1) { tar = fW_mcrec; pf = "mcrec"; }; if(htype==2) { tar = fW_mcgen; pf = "mcgen"; }; if(!tar) return; TH3D *th3 = (TH3D*)tar->FindObject(GetBinName(0,0,pf)); //pT bin 0, V0M bin 0, since all integrated if(!th3) { if(!htype) tar->Add(new TH3D(GetBinName(0,0,pf),";#varphi;#eta;v_{z}",60,0,TMath::TwoPi(),64,-1.6,1.6,40,-10,10)); //0,0 since all integrated th3 = (TH3D*)tar->At(tar->GetEntries()-1); }; th3->Fill(htype?pt:phi,eta,vz); }; Double_t AliGFWWeights::GetWeight(Double_t phi, Double_t eta, Double_t vz, Double_t pt, Double_t cent, Int_t htype) { TObjArray *tar=0; const char *pf=""; if(htype==0) { tar = fW_data; pf = "data"; }; if(htype==1) { tar = fW_mcrec; pf = "mcrec"; }; if(htype==2) { tar = fW_mcgen; pf = "mcgen"; }; if(!tar) return 1; TH3D *th3 = (TH3D*)tar->FindObject(GetBinName(0,0,pf)); if(!th3) return 1;//-1; Int_t xind = th3->GetXaxis()->FindBin(htype?pt:phi); Int_t etaind = th3->GetYaxis()->FindBin(eta); Int_t vzind = th3->GetZaxis()->FindBin(vz); Double_t weight = th3->GetBinContent(xind, etaind, vzind); if(weight!=0) return 1./weight; return 1; }; Double_t AliGFWWeights::FindMax(TH3D *inh, Int_t &ix, Int_t &iy, Int_t &iz) { Double_t maxv=inh->GetBinContent(1,1,1); for(Int_t i=1;i<=inh->GetNbinsX();i++) for(Int_t j=1;j<=inh->GetNbinsY();j++) for(Int_t k=1;k<=inh->GetNbinsZ();k++) if(inh->GetBinContent(i,j,k)>maxv) { ix=i; iy=j; iz=k; maxv=inh->GetBinContent(i,j,k); }; return maxv; }; void AliGFWWeights::MCToEfficiency() { if(fW_mcgen->GetEntries()<1) { printf("MC gen. array empty. This is probably because effs. have been calculated and the generated particle histograms have been cleared out!\n"); return; }; for(Int_t i=0;i<fW_mcrec->GetEntries();i++) { TH3D *hr = (TH3D*)fW_mcrec->At(i); TH3D *hg = (TH3D*)fW_mcgen->At(i); hr->Sumw2(); hg->Sumw2(); hr->Divide(hg); }; fW_mcgen->Clear(); }; void AliGFWWeights::CreateNUA(Bool_t IntegrateOverCentAndPt) { if(!IntegrateOverCentAndPt) { printf("Method is outdated! NUA is integrated over centrality and pT. Quit now, or the behaviour will be bad\n"); return; }; TH3D *h3; TH1D *h1; if(fW_data->GetEntries()<1) return; if(IntegrateOverCentAndPt) { if(fAccInt) delete fAccInt; fAccInt = (TH3D*)fW_data->At(0)->Clone("IntegratedAcceptance"); fAccInt->RebinY(2); fAccInt->RebinZ(5); fAccInt->Sumw2(); for(Int_t etai=1;etai<=fAccInt->GetNbinsY();etai++) { fAccInt->GetYaxis()->SetRange(etai,etai); if(fAccInt->Integral()<1) continue; for(Int_t vzi=1;vzi<=fAccInt->GetNbinsZ();vzi++) { fAccInt->GetZaxis()->SetRange(vzi,vzi); if(fAccInt->Integral()<1) continue; h1 = (TH1D*)fAccInt->Project3D("x"); Double_t maxv = h1->GetMaximum(); for(Int_t phii=1;phii<=h1->GetNbinsX();phii++) fAccInt->SetBinContent(phii,etai,vzi,fAccInt->GetBinContent(phii,etai,vzi)/maxv); delete h1; }; fAccInt->GetZaxis()->SetRange(1,fAccInt->GetNbinsZ()); }; fAccInt->GetYaxis()->SetRange(1,fAccInt->GetNbinsY()); return; }; }; void AliGFWWeights::CreateNUE(Bool_t IntegrateOverCentrality) { if(!IntegrateOverCentrality) { printf("Method is outdated! NUE is integrated over centrality. Quit now, or the behaviour will be bad\n"); return; }; TH3D *num=0; TH3D *den=0; if(fW_mcrec->GetEntries()<1 || fW_mcgen->GetEntries()<1) return; if(IntegrateOverCentrality) { num=(TH3D*)fW_mcrec->At(0);//->Clone(Form("temp_%s",fW_mcrec->At(0)->GetName())); den=(TH3D*)fW_mcgen->At(0);//->Clone(Form("temp_%s",fW_mcgen->At(0)->GetName())); num->Sumw2(); den->Sumw2(); num->RebinY(2); den->RebinY(2); num->RebinZ(5); den->RebinZ(5); fEffInt = (TH3D*)num->Clone("Efficiency_Integrated"); fEffInt->Divide(den); return; }; }; void AliGFWWeights::ReadAndMerge(const char *filelinks) { FILE *flist = fopen(filelinks,"r"); char str[150]; Int_t nFiles=0; while(fscanf(flist,"%s\n",str)==1) nFiles++; rewind(flist); if(nFiles==0) { printf("No files to read!\n"); return; }; if(!fW_data) { fW_data = new TObjArray(); fW_data->SetName("Weights_Data"); fW_data->SetOwner(kTRUE); }; if(!fW_mcrec) { fW_mcrec = new TObjArray(); fW_mcrec->SetName("Weights_MCRec"); fW_mcrec->SetOwner(kTRUE); }; if(!fW_mcgen) { fW_mcgen = new TObjArray(); fW_mcgen->SetName("Weights_MCGen"); fW_mcgen->SetOwner(kTRUE); }; fDataFilled = kFALSE; fMCFilled = kFALSE; TFile *tf=0; for(Int_t i=0;i<nFiles;i++) { Int_t trash = fscanf(flist,"%s\n",str); tf = new TFile(str,"READ"); if(tf->IsZombie()) { printf("Could not open file %s!\n",str); tf->Close(); continue; }; TList *tl = (TList*)tf->Get("OutputList"); AliGFWWeights *tw = (AliGFWWeights*)tl->FindObject(this->GetName()); if(!tw) { printf("Could not fetch weights object from %s\n",str); tf->Close(); continue; }; AddArray(fW_data,tw->GetDataArray()); AddArray(fW_mcrec,tw->GetRecArray()); AddArray(fW_mcgen,tw->GetGenArray()); tf->Close(); delete tw; }; }; void AliGFWWeights::AddArray(TObjArray *targ, TObjArray *sour) { if(!sour) { printf("Source array does not exist!\n"); return; }; for(Int_t i=0;i<sour->GetEntries();i++) { TH3D *sourh = (TH3D*)sour->At(i); TH3D *targh = (TH3D*)targ->FindObject(sourh->GetName()); if(!targh) { targh = (TH3D*)sourh->Clone(sourh->GetName()); targh->SetDirectory(0); targ->Add(targh); } else targh->Add(sourh); }; }; Long64_t AliGFWWeights::Merge(TCollection *collist) { Long64_t nmerged=0; if(!fW_data) { fW_data = new TObjArray(); fW_data->SetName("Weights_Data"); fW_data->SetOwner(kTRUE); }; if(!fW_mcrec) { fW_mcrec = new TObjArray(); fW_mcrec->SetName("Weights_MCRec"); fW_mcrec->SetOwner(kTRUE); }; if(!fW_mcgen) { fW_mcgen = new TObjArray(); fW_mcgen->SetName("Weights_MCGen"); fW_mcgen->SetOwner(kTRUE); }; AliGFWWeights *l_w = 0; TIter all_w(collist); while (l_w = ((AliGFWWeights*) all_w())) { AddArray(fW_data,l_w->GetDataArray()); AddArray(fW_mcrec,l_w->GetRecArray()); AddArray(fW_mcgen,l_w->GetGenArray()); nmerged++; }; return nmerged; }; <|endoftext|>
<commit_before>/****************************************************************************** * This file is part of dirtsand. * * * * dirtsand 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. * * * * dirtsand 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 dirtsand. If not, see <http://www.gnu.org/licenses/>. * ******************************************************************************/ #include "AvSeekMsg.h" void MOUL::AvSeekMsg::read(DS::Stream* stream) { AvTaskMsg::read(stream); m_seekPoint.read(stream); if (!m_seekPoint.isNull()) { m_targetPos = stream->read<DS::Vector3>(); m_targetLook = stream->read<DS::Vector3>(); } m_duration = stream->read<float>(); m_smartSeek = stream->read<bool>(); m_animName = stream->readSafeString(); m_alignType = stream->read<uint16_t>(); m_noSeek = stream->read<bool>(); m_flags = stream->read<uint8_t>(); m_finishKey.read(stream); } void MOUL::AvSeekMsg::write(DS::Stream* stream) const { AvTaskMsg::write(stream); m_seekPoint.write(stream); if (!m_seekPoint.isNull()) { stream->write<DS::Vector3>(m_targetPos); stream->write<DS::Vector3>(m_targetLook); } stream->write<float>(m_duration); stream->write<bool>(m_smartSeek); stream->writeSafeString(m_animName); stream->write<uint16_t>(m_alignType); stream->write<bool>(m_noSeek); stream->write<uint8_t>(m_flags); m_finishKey.write(stream); } void MOUL::AvOneShotMsg::read(DS::Stream* stream) { AvSeekMsg::read(stream); m_oneShotAnimName = stream->readSafeString(); m_drivable = stream->read<bool>(); m_reversible = stream->read<bool>(); } void MOUL::AvOneShotMsg::write(DS::Stream* stream) const { AvSeekMsg::write(stream); stream->writeSafeString(m_oneShotAnimName); stream->write<bool>(m_drivable); stream->write<bool>(m_reversible); } <commit_msg>Fix typo when reading/writing AvSeekMsg<commit_after>/****************************************************************************** * This file is part of dirtsand. * * * * dirtsand 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. * * * * dirtsand 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 dirtsand. If not, see <http://www.gnu.org/licenses/>. * ******************************************************************************/ #include "AvSeekMsg.h" void MOUL::AvSeekMsg::read(DS::Stream* stream) { AvTaskMsg::read(stream); m_seekPoint.read(stream); if (m_seekPoint.isNull()) { m_targetPos = stream->read<DS::Vector3>(); m_targetLook = stream->read<DS::Vector3>(); } m_duration = stream->read<float>(); m_smartSeek = stream->read<bool>(); m_animName = stream->readSafeString(); m_alignType = stream->read<uint16_t>(); m_noSeek = stream->read<bool>(); m_flags = stream->read<uint8_t>(); m_finishKey.read(stream); } void MOUL::AvSeekMsg::write(DS::Stream* stream) const { AvTaskMsg::write(stream); m_seekPoint.write(stream); if (m_seekPoint.isNull()) { stream->write<DS::Vector3>(m_targetPos); stream->write<DS::Vector3>(m_targetLook); } stream->write<float>(m_duration); stream->write<bool>(m_smartSeek); stream->writeSafeString(m_animName); stream->write<uint16_t>(m_alignType); stream->write<bool>(m_noSeek); stream->write<uint8_t>(m_flags); m_finishKey.write(stream); } void MOUL::AvOneShotMsg::read(DS::Stream* stream) { AvSeekMsg::read(stream); m_oneShotAnimName = stream->readSafeString(); m_drivable = stream->read<bool>(); m_reversible = stream->read<bool>(); } void MOUL::AvOneShotMsg::write(DS::Stream* stream) const { AvSeekMsg::write(stream); stream->writeSafeString(m_oneShotAnimName); stream->write<bool>(m_drivable); stream->write<bool>(m_reversible); } <|endoftext|>
<commit_before> #include "../../Flare.h" #include "FlareShipStatus.h" #define LOCTEXT_NAMESPACE "FlareShipStatus" /*---------------------------------------------------- Construct ----------------------------------------------------*/ void SFlareShipStatus::Construct(const FArguments& InArgs) { TargetShip = InArgs._Ship; ChildSlot .VAlign(VAlign_Fill) .HAlign(HAlign_Fill) .Padding(FMargin(8)) [ SNew(SHorizontalBox) + SHorizontalBox::Slot() .AutoWidth() [ SNew(SImage) .Image(FFlareStyleSet::GetIcon("Temperature")) .ColorAndOpacity(FLinearColor::Red) .Visibility(this, &SFlareShipStatus::IsVisible, EFlareSubsystem::SYS_Temperature) ] + SHorizontalBox::Slot() .AutoWidth() [ SNew(SImage) .Image(FFlareStyleSet::GetIcon("Power")) .ColorAndOpacity(FLinearColor::Red) .Visibility(this, &SFlareShipStatus::IsVisible, EFlareSubsystem::SYS_Power) ] + SHorizontalBox::Slot() .AutoWidth() [ SNew(SImage) .Image(FFlareStyleSet::GetIcon("Propulsion")) .ColorAndOpacity(FLinearColor::Red) .Visibility(this, &SFlareShipStatus::IsVisible, EFlareSubsystem::SYS_Propulsion) ] + SHorizontalBox::Slot() .AutoWidth() [ SNew(SImage) .Image(FFlareStyleSet::GetIcon("RCS")) .ColorAndOpacity(FLinearColor::Red) .Visibility(this, &SFlareShipStatus::IsVisible, EFlareSubsystem::SYS_RCS) ] + SHorizontalBox::Slot() .AutoWidth() [ SNew(SImage) .Image(FFlareStyleSet::GetIcon("LifeSupport")) .ColorAndOpacity(FLinearColor::Red) .Visibility(this, &SFlareShipStatus::IsVisible, EFlareSubsystem::SYS_LifeSupport) ] + SHorizontalBox::Slot() .AutoWidth() [ SNew(SImage) .Image(FFlareStyleSet::GetIcon("Shell")) .ColorAndOpacity(FLinearColor::Red) .Visibility(this, &SFlareShipStatus::IsVisible, EFlareSubsystem::SYS_Weapon) ] ]; } /*---------------------------------------------------- Interaction ----------------------------------------------------*/ void SFlareShipStatus::SetTargetShip(IFlareShipInterface* Target) { TargetShip = Target; } /*---------------------------------------------------- Callbacks ----------------------------------------------------*/ EVisibility SFlareShipStatus::IsVisible(EFlareSubsystem::Type Type) const { if (TargetShip) { return ((TargetShip->GetSubsystemHealth(Type) <= 0.3f) ? EVisibility::Visible : EVisibility::Collapsed); } { return EVisibility::Collapsed; } } #undef LOCTEXT_NAMESPACE <commit_msg>Nicer color for disabled systems in menus<commit_after> #include "../../Flare.h" #include "FlareShipStatus.h" #define LOCTEXT_NAMESPACE "FlareShipStatus" /*---------------------------------------------------- Construct ----------------------------------------------------*/ void SFlareShipStatus::Construct(const FArguments& InArgs) { TargetShip = InArgs._Ship; FLinearColor Color(1.0, 0.05, 0, 1.0); ChildSlot .VAlign(VAlign_Fill) .HAlign(HAlign_Fill) .Padding(FMargin(8)) [ SNew(SHorizontalBox) + SHorizontalBox::Slot() .AutoWidth() [ SNew(SImage) .Image(FFlareStyleSet::GetIcon("Temperature")) .ColorAndOpacity(Color) .Visibility(this, &SFlareShipStatus::IsVisible, EFlareSubsystem::SYS_Temperature) ] + SHorizontalBox::Slot() .AutoWidth() [ SNew(SImage) .Image(FFlareStyleSet::GetIcon("Power")) .ColorAndOpacity(Color) .Visibility(this, &SFlareShipStatus::IsVisible, EFlareSubsystem::SYS_Power) ] + SHorizontalBox::Slot() .AutoWidth() [ SNew(SImage) .Image(FFlareStyleSet::GetIcon("Propulsion")) .ColorAndOpacity(Color) .Visibility(this, &SFlareShipStatus::IsVisible, EFlareSubsystem::SYS_Propulsion) ] + SHorizontalBox::Slot() .AutoWidth() [ SNew(SImage) .Image(FFlareStyleSet::GetIcon("RCS")) .ColorAndOpacity(Color) .Visibility(this, &SFlareShipStatus::IsVisible, EFlareSubsystem::SYS_RCS) ] + SHorizontalBox::Slot() .AutoWidth() [ SNew(SImage) .Image(FFlareStyleSet::GetIcon("LifeSupport")) .ColorAndOpacity(Color) .Visibility(this, &SFlareShipStatus::IsVisible, EFlareSubsystem::SYS_LifeSupport) ] + SHorizontalBox::Slot() .AutoWidth() [ SNew(SImage) .Image(FFlareStyleSet::GetIcon("Shell")) .ColorAndOpacity(Color) .Visibility(this, &SFlareShipStatus::IsVisible, EFlareSubsystem::SYS_Weapon) ] ]; } /*---------------------------------------------------- Interaction ----------------------------------------------------*/ void SFlareShipStatus::SetTargetShip(IFlareShipInterface* Target) { TargetShip = Target; } /*---------------------------------------------------- Callbacks ----------------------------------------------------*/ EVisibility SFlareShipStatus::IsVisible(EFlareSubsystem::Type Type) const { if (TargetShip) { return ((TargetShip->GetSubsystemHealth(Type) <= 0.3f) ? EVisibility::Visible : EVisibility::Collapsed); } { return EVisibility::Collapsed; } } #undef LOCTEXT_NAMESPACE <|endoftext|>
<commit_before>#include <assert.h> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/xml_parser.hpp> #include <iostream> #include "Create.h" #include "File.h" #include "Map.h" #include "Node.h" #include "stdlib.h" #include "utils.h" namespace Maps { Map::Map(): Map(DEFAULT_MAP_SIZE) { setID(0); for (auto &i: grid) { i = new Node; } buildMoveData(); } Map::Map(int mapSize): grid{mapSize*mapSize, nullptr} , mapSize{mapSize} { setID(0); } Map::~Map() { deleteGrid(); } void Map::activate() { for ( auto &node : grid ) { node->activate(); } } void Map::setNode(int xInd, int yInd, Node* node) { // Reference to node ptr being replaced Node *&alreadyThere = grid.at(yInd*mapSize + xInd); delete alreadyThere; // Deletes the node that might be there alreadyThere = node; } void Map::buildMoveData() { for ( int yIndex( 0 ); yIndex < mapSize; yIndex++ ) { for ( int xIndex( 0 ); xIndex < mapSize; xIndex++ ) { // Add node links to the current node Node &currentNode = *getNode(xIndex, yIndex); if ( yIndex < mapSize-1 ) { // Build north Node *north = getNode(xIndex, yIndex+1); currentNode.setNodeLink(Dir::North, north); } if ( xIndex < mapSize-1 ) { // build east Node *east = getNode(xIndex+1, yIndex); currentNode.setNodeLink(Dir::East, east); } if ( xIndex > 0 ) { // build west Node *west = getNode(xIndex-1, yIndex); currentNode.setNodeLink(Dir::West, west); } if ( yIndex > 0 ) { // build south Node *south = getNode(xIndex, yIndex-1); currentNode.setNodeLink(Dir::South, south); } } } } Node* Map::getNode(int xInd, int yInd) { assert(xInd < mapSize && yInd < mapSize); assert(grid.at(yInd*mapSize + xInd) != nullptr); return grid.at(yInd*mapSize + xInd); } void Map::deleteGrid() { for (int i(0); i < grid.size(); ++i) { delete grid.at(i); } } pairType Map::toTree() { using namespace boost::property_tree; ptree tree; tree.push_back(XML_VAR_PAIR(mapSize)); // Should a location be saved? for (Node* node : grid) { tree.push_back(node->toTree()); } return ptree::value_type("Map", tree); } void Map::fromTree(const pairType &p) { const treeType &tree = p.second; { // Get the mapSize first: auto mapSizeIterator = tree.find("mapSize"); const std::string &data = mapSizeIterator->second.data(); mapSize = std::stoi(data); deleteGrid(); grid = std::vector<Node*>(mapSize*mapSize, nullptr); } auto it = tree.begin(); int nodeNumber = 0; while (it != tree.end()) { const std::string &key = it->first; const std::string &data = it->second.data(); if (key == "Node") { // Sets the next node from xml // Note that since x,y is not recorded in the xml, // nodes can only be loaded in the order they were saved grid.at(nodeNumber) = Create::newNode(*it); nodeNumber++; } it++; } // So that the player can move around in the map. buildMoveData(); } void Map::save() { startSave("Map"); endSave(); } void Map::load() { startLoad("Map"); endLoad(); } } // End namespace Maps <commit_msg>Map LS<commit_after>#include <assert.h> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/xml_parser.hpp> #include <iostream> #include "Create.h" #include "File.h" #include "Map.h" #include "Node.h" #include "stdlib.h" #include "utils.h" namespace Maps { Map::Map(): Map(DEFAULT_MAP_SIZE) { setID(0); for (auto &i: grid) { i = new Node; } buildMoveData(); } Map::Map(int mapSize): grid{mapSize*mapSize, nullptr} , mapSize{mapSize} { setID(0); } Map::~Map() { deleteGrid(); } void Map::activate() { for ( auto &node : grid ) { node->activate(); } } void Map::setNode(int xInd, int yInd, Node* node) { // Reference to node ptr being replaced Node *&alreadyThere = grid.at(yInd*mapSize + xInd); delete alreadyThere; // Deletes the node that might be there alreadyThere = node; } void Map::buildMoveData() { for ( int yIndex( 0 ); yIndex < mapSize; yIndex++ ) { for ( int xIndex( 0 ); xIndex < mapSize; xIndex++ ) { // Add node links to the current node Node &currentNode = *getNode(xIndex, yIndex); if ( yIndex < mapSize-1 ) { // Build north Node *north = getNode(xIndex, yIndex+1); currentNode.setNodeLink(Dir::North, north); } if ( xIndex < mapSize-1 ) { // build east Node *east = getNode(xIndex+1, yIndex); currentNode.setNodeLink(Dir::East, east); } if ( xIndex > 0 ) { // build west Node *west = getNode(xIndex-1, yIndex); currentNode.setNodeLink(Dir::West, west); } if ( yIndex > 0 ) { // build south Node *south = getNode(xIndex, yIndex-1); currentNode.setNodeLink(Dir::South, south); } } } } Node* Map::getNode(int xInd, int yInd) { assert(xInd < mapSize && yInd < mapSize); assert(grid.at(yInd*mapSize + xInd) != nullptr); return grid.at(yInd*mapSize + xInd); } void Map::deleteGrid() { for (int i(0); i < grid.size(); ++i) { delete grid.at(i); } } pairType Map::toTree() { using namespace boost::property_tree; ptree tree; tree.push_back(XML_VAR_PAIR(mapSize)); // Should a location be saved? for (Node* node : grid) { tree.push_back(node->toTree()); } return ptree::value_type("Map", tree); } void Map::fromTree(const pairType &p) { const treeType &tree = p.second; { // Get the mapSize first: auto mapSizeIterator = tree.find("mapSize"); const std::string &data = mapSizeIterator->second.data(); mapSize = std::stoi(data); deleteGrid(); grid = std::vector<Node*>(mapSize*mapSize, nullptr); } auto it = tree.begin(); int nodeNumber = 0; while (it != tree.end()) { const std::string &key = it->first; const std::string &data = it->second.data(); if (key == "Node") { // Sets the next node from xml // Note that since x,y is not recorded in the xml, // nodes can only be loaded in the order they were saved grid.at(nodeNumber) = Create::newNode(*it); nodeNumber++; } it++; } // So that the player can move around in the map. buildMoveData(); } void Map::save() { startSave("Map"); // Save the nodes SAVE(mapSize); for (int i = 0; i < grid.size(); i++) { grid.at(i)->save(); } endSave(); } void Map::load() { startLoad("Map"); // Load the nodes LOAD(mapSize); grid = std::vector<Node*>(mapSize * mapSize, nullptr); for (int i = 0; i < grid.size(); i++) { grid.at(i) = Create::loadNewNode(); } buildMoveData(); // Get map ready for use. endLoad(); } } // End namespace Maps <|endoftext|>
<commit_before>/** * @file Main.cpp */ #include "GLFWEW.h" #include <glm/gtc/matrix_transform.hpp> #include <iostream> #include <vector> /// 3DxN^[^. struct Vector3 { float x, y, z; }; /// RGBAJ[^. struct Color { float r, g, b, a; }; /// _f[^^. struct Vertex { Vector3 position; ///< W Color color; ///< F }; /// _f[^. const Vertex vertices[] = { { {-0.5f, -0.3f, 0.5f}, {0.0f, 1.0f, 0.0f, 1.0f} }, { { 0.3f, -0.3f, 0.5f}, {0.0f, 0.0f, 1.0f, 1.0f} }, { { 0.3f, 0.5f, 0.5f}, {1.0f, 0.0f, 0.0f, 1.0f} }, { {-0.5f, 0.5f, 0.5f}, {0.0f, 0.0f, 1.0f, 1.0f} }, { {-0.3f, 0.3f, 0.1f}, {0.0f, 0.0f, 1.0f, 1.0f} }, { {-0.3f, -0.5f, 0.1f}, {0.0f, 1.0f, 1.0f, 1.0f} }, { { 0.5f, -0.5f, 0.1f}, {0.0f, 0.0f, 1.0f, 1.0f} }, { { 0.5f, -0.5f, 0.1f}, {1.0f, 0.0f, 0.0f, 1.0f} }, { { 0.5f, 0.3f, 0.1f}, {1.0f, 1.0f, 0.0f, 1.0f} }, { {-0.3f, 0.3f, 0.1f}, {1.0f, 0.0f, 0.0f, 1.0f} }, }; /// CfbNXf[^. const GLuint indices[] = { 0, 1, 2, 2, 3, 0, 4, 5, 6, 7, 8, 9, }; /// _VF[_. static const char* vsCode = "#version 410 \n" "layout(location=0) in vec3 vPosition;" "layout(location=1) in vec4 vColor;" "layout(location=0) out vec4 outColor;" "uniform mat4x4 matMVP;" "void main() {" " outColor = vColor;" " gl_Position = matMVP * vec4(vPosition, 1.0);" "}"; /// tOgVF[_. static const char* fsCode = "#version 410 \n" "layout(location=0) in vec4 inColor;" "out vec4 fragColor;" "void main() {" " fragColor = inColor;" "}"; /** * Vertex Buffer Object쐬. * * @param size _f[^̃TCY. * @param data _f[^ւ̃|C^. * * @return 쐬VBO. */ GLuint CreateVBO(GLsizeiptr size, const GLvoid* data) { GLuint vbo = 0; glGenBuffers(1, &vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER, size, data, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); return vbo; } /** * Index Buffer Object쐬. * * @param size CfbNXf[^̃TCY. * @param data CfbNXf[^ւ̃|C^. * * @return 쐬IBO. */ GLuint CreateIBO(GLsizeiptr size, const GLvoid* data) { GLuint ibo = 0; glGenBuffers(1, &ibo); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo); glBufferData(GL_ELEMENT_ARRAY_BUFFER, size, data, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); return ibo; } /** * _Agr[gݒ肷. * * @param index _Agr[g̃CfbNX. * @param cls _f[^^. * @param mbr _Agr[gɐݒ肷cls̃oϐ. */ #define SetVertexAttribPointer(index, cls, mbr) SetVertexAttribPointerI( \ index, \ sizeof(cls::mbr) / sizeof(float), \ sizeof(cls), \ reinterpret_cast<GLvoid*>(offsetof(cls, mbr))) void SetVertexAttribPointerI(GLuint index, GLint size, GLsizei stride, const GLvoid* pointer) { glEnableVertexAttribArray(index); glVertexAttribPointer(index, size, GL_FLOAT, GL_FALSE, stride, pointer); } /** * Vertex Array Object쐬. * * @param vbo VAOɊ֘AtVBO. * @param ibo VAOɊ֘AtIBO. * * @return 쐬VAO. */ GLuint CreateVAO(GLuint vbo, GLuint ibo) { GLuint vao = 0; glGenVertexArrays(1, &vao); glBindVertexArray(vao); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo); SetVertexAttribPointer(0, Vertex, position); SetVertexAttribPointer(1, Vertex, color); glBindVertexArray(0); glDeleteBuffers(1, &vbo); glDeleteBuffers(1, &ibo); return vao; } /** * VF[_R[hRpC. * * @param type VF[_̎. * @param string VF[_R[hւ̃|C^. * * @return 쐬VF[_IuWFNg. */ GLuint CompileShader(GLenum type, const GLchar* string) { GLuint shader = glCreateShader(type); glShaderSource(shader, 1, &string, nullptr); glCompileShader(shader); GLint compiled = 0; glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled); if (!compiled) { GLint infoLen = 0; glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLen); if (infoLen) { std::vector<char> buf; buf.resize(infoLen); if (static_cast<int>(buf.size()) >= infoLen) { glGetShaderInfoLog(shader, infoLen, NULL, buf.data()); std::cerr << "ERROR: VF[_̃RpCɎsn" << buf.data() << std::endl; } } glDeleteShader(shader); return 0; } return shader; } /** * vOIuWFNg쐬. * * @param vsCode _VF[_R[hւ̃|C^. * @param fsCode tOgVF[_R[hւ̃|C^. * * @return 쐬vOIuWFNg. */ GLuint CreateShaderProgram(const GLchar* vsCode, const GLchar* fsCode) { GLuint vs = CompileShader(GL_VERTEX_SHADER, vsCode); GLuint fs = CompileShader(GL_FRAGMENT_SHADER, fsCode); if (!vs || !fs) { return 0; } GLuint program = glCreateProgram(); glAttachShader(program, fs); glDeleteShader(fs); glAttachShader(program, vs); glDeleteShader(vs); glLinkProgram(program); GLint linkStatus = GL_FALSE; glGetProgramiv(program, GL_LINK_STATUS, &linkStatus); if (linkStatus != GL_TRUE) { GLint infoLen = 0; glGetProgramiv(program, GL_INFO_LOG_LENGTH, &infoLen); if (infoLen) { std::vector<char> buf; buf.resize(infoLen); if (static_cast<int>(buf.size()) >= infoLen) { glGetProgramInfoLog(program, infoLen, NULL, buf.data()); std::cerr << "ERROR: VF[_̃NɎsn"<< buf.data() << std::endl; } } glDeleteProgram(program); return 0; } return program; } /// Gg[|Cg. int main() { GLFWEW::Window& window = GLFWEW::Window::Instance(); if (!window.Init(800, 600, "OpenGL Tutorial")) { return 1; } const GLuint vbo = CreateVBO(sizeof(vertices), vertices); const GLuint ibo = CreateIBO(sizeof(indices), indices); const GLuint vao = CreateVAO(vbo, ibo); const GLuint shaderProgram = CreateShaderProgram(vsCode, fsCode); if (!vbo || !ibo || !vao || !shaderProgram) { return 1; } // C[v. while (!window.ShouldClose()) { glClearColor(0.1f, 0.3f, 0.5f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // _]ړ. static float degree = 0.0f; degree += 0.1f; if (degree >= 360.0f) { degree -= 360.0f; } const glm::vec3 viewPos = glm::rotate(glm::mat4(), glm::radians(degree), glm::vec3(0, 1, 0)) * glm::vec4(2, 3, 3, 1); glUseProgram(shaderProgram); const GLint matMVPLoc = glGetUniformLocation(shaderProgram, "matMVP"); if (matMVPLoc >= 0) { const glm::mat4x4 matProj = glm::perspective(glm::radians(45.0f), 800.0f / 600.0f, 0.1f, 100.0f); const glm::mat4x4 matView = glm::lookAt(viewPos, glm::vec3(0, 0, 0), glm::vec3(0, 1, 0)); const glm::mat4x4 matMVP = matProj * matView; glUniformMatrix4fv(matMVPLoc, 1, GL_FALSE, &matMVP[0][0]); } glBindVertexArray(vao); glDrawElements( GL_TRIANGLES, sizeof(indices)/sizeof(indices[0]), GL_UNSIGNED_INT, reinterpret_cast<const GLvoid*>(0)); window.SwapBuffers(); } glDeleteProgram(shaderProgram); glDeleteVertexArrays(1, &vao); return 0; }<commit_msg>第03回9章まで実装.<commit_after>/** * @file Main.cpp */ #include "GLFWEW.h" #include <glm/gtc/matrix_transform.hpp> #include <iostream> #include <vector> /// 3DxN^[^. struct Vector3 { float x, y, z; }; /// RGBAJ[^. struct Color { float r, g, b, a; }; /// _f[^^. struct Vertex { Vector3 position; ///< W Color color; ///< F }; /// _f[^. const Vertex vertices[] = { { {-0.5f, -0.3f, 0.5f}, {0.0f, 1.0f, 0.0f, 1.0f} }, { { 0.3f, -0.3f, 0.5f}, {0.0f, 0.0f, 1.0f, 1.0f} }, { { 0.3f, 0.5f, 0.5f}, {1.0f, 0.0f, 0.0f, 1.0f} }, { {-0.5f, 0.5f, 0.5f}, {0.0f, 0.0f, 1.0f, 1.0f} }, { {-0.3f, 0.3f, 0.1f}, {0.0f, 0.0f, 1.0f, 1.0f} }, { {-0.3f, -0.5f, 0.1f}, {0.0f, 1.0f, 1.0f, 1.0f} }, { { 0.5f, -0.5f, 0.1f}, {0.0f, 0.0f, 1.0f, 1.0f} }, { { 0.5f, -0.5f, 0.1f}, {1.0f, 0.0f, 0.0f, 1.0f} }, { { 0.5f, 0.3f, 0.1f}, {1.0f, 1.0f, 0.0f, 1.0f} }, { {-0.3f, 0.3f, 0.1f}, {1.0f, 0.0f, 0.0f, 1.0f} }, }; /// CfbNXf[^. const GLuint indices[] = { 0, 1, 2, 2, 3, 0, 4, 5, 6, 7, 8, 9, }; /// _VF[_. static const char* vsCode = "#version 410 \n" "layout(location=0) in vec3 vPosition;" "layout(location=1) in vec4 vColor;" "layout(location=0) out vec4 outColor;" "uniform mat4x4 matMVP;" "void main() {" " outColor = vColor;" " gl_Position = matMVP * vec4(vPosition, 1.0);" "}"; /// tOgVF[_. static const char* fsCode = "#version 410 \n" "layout(location=0) in vec4 inColor;" "out vec4 fragColor;" "void main() {" " fragColor = inColor;" "}"; /** * Vertex Buffer Object쐬. * * @param size _f[^̃TCY. * @param data _f[^ւ̃|C^. * * @return 쐬VBO. */ GLuint CreateVBO(GLsizeiptr size, const GLvoid* data) { GLuint vbo = 0; glGenBuffers(1, &vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER, size, data, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); return vbo; } /** * Index Buffer Object쐬. * * @param size CfbNXf[^̃TCY. * @param data CfbNXf[^ւ̃|C^. * * @return 쐬IBO. */ GLuint CreateIBO(GLsizeiptr size, const GLvoid* data) { GLuint ibo = 0; glGenBuffers(1, &ibo); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo); glBufferData(GL_ELEMENT_ARRAY_BUFFER, size, data, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); return ibo; } /** * _Agr[gݒ肷. * * @param index _Agr[g̃CfbNX. * @param cls _f[^^. * @param mbr _Agr[gɐݒ肷cls̃oϐ. */ #define SetVertexAttribPointer(index, cls, mbr) SetVertexAttribPointerI( \ index, \ sizeof(cls::mbr) / sizeof(float), \ sizeof(cls), \ reinterpret_cast<GLvoid*>(offsetof(cls, mbr))) void SetVertexAttribPointerI(GLuint index, GLint size, GLsizei stride, const GLvoid* pointer) { glEnableVertexAttribArray(index); glVertexAttribPointer(index, size, GL_FLOAT, GL_FALSE, stride, pointer); } /** * Vertex Array Object쐬. * * @param vbo VAOɊ֘AtVBO. * @param ibo VAOɊ֘AtIBO. * * @return 쐬VAO. */ GLuint CreateVAO(GLuint vbo, GLuint ibo) { GLuint vao = 0; glGenVertexArrays(1, &vao); glBindVertexArray(vao); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo); SetVertexAttribPointer(0, Vertex, position); SetVertexAttribPointer(1, Vertex, color); glBindVertexArray(0); glDeleteBuffers(1, &vbo); glDeleteBuffers(1, &ibo); return vao; } /** * VF[_R[hRpC. * * @param type VF[_̎. * @param string VF[_R[hւ̃|C^. * * @return 쐬VF[_IuWFNg. */ GLuint CompileShader(GLenum type, const GLchar* string) { GLuint shader = glCreateShader(type); glShaderSource(shader, 1, &string, nullptr); glCompileShader(shader); GLint compiled = 0; glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled); if (!compiled) { GLint infoLen = 0; glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLen); if (infoLen) { std::vector<char> buf; buf.resize(infoLen); if (static_cast<int>(buf.size()) >= infoLen) { glGetShaderInfoLog(shader, infoLen, NULL, buf.data()); std::cerr << "ERROR: VF[_̃RpCɎsn" << buf.data() << std::endl; } } glDeleteShader(shader); return 0; } return shader; } /** * vOIuWFNg쐬. * * @param vsCode _VF[_R[hւ̃|C^. * @param fsCode tOgVF[_R[hւ̃|C^. * * @return 쐬vOIuWFNg. */ GLuint CreateShaderProgram(const GLchar* vsCode, const GLchar* fsCode) { GLuint vs = CompileShader(GL_VERTEX_SHADER, vsCode); GLuint fs = CompileShader(GL_FRAGMENT_SHADER, fsCode); if (!vs || !fs) { return 0; } GLuint program = glCreateProgram(); glAttachShader(program, fs); glDeleteShader(fs); glAttachShader(program, vs); glDeleteShader(vs); glLinkProgram(program); GLint linkStatus = GL_FALSE; glGetProgramiv(program, GL_LINK_STATUS, &linkStatus); if (linkStatus != GL_TRUE) { GLint infoLen = 0; glGetProgramiv(program, GL_INFO_LOG_LENGTH, &infoLen); if (infoLen) { std::vector<char> buf; buf.resize(infoLen); if (static_cast<int>(buf.size()) >= infoLen) { glGetProgramInfoLog(program, infoLen, NULL, buf.data()); std::cerr << "ERROR: VF[_̃NɎsn"<< buf.data() << std::endl; } } glDeleteProgram(program); return 0; } return program; } /// Gg[|Cg. int main() { GLFWEW::Window& window = GLFWEW::Window::Instance(); if (!window.Init(800, 600, "OpenGL Tutorial")) { return 1; } const GLuint vbo = CreateVBO(sizeof(vertices), vertices); const GLuint ibo = CreateIBO(sizeof(indices), indices); const GLuint vao = CreateVAO(vbo, ibo); const GLuint shaderProgram = CreateShaderProgram(vsCode, fsCode); if (!vbo || !ibo || !vao || !shaderProgram) { return 1; } glEnable(GL_DEPTH_TEST); // C[v. while (!window.ShouldClose()) { glClearColor(0.1f, 0.3f, 0.5f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // _]ړ. static float degree = 0.0f; degree += 0.1f; if (degree >= 360.0f) { degree -= 360.0f; } const glm::vec3 viewPos = glm::rotate(glm::mat4(), glm::radians(degree), glm::vec3(0, 1, 0)) * glm::vec4(2, 3, 3, 1); glUseProgram(shaderProgram); const GLint matMVPLoc = glGetUniformLocation(shaderProgram, "matMVP"); if (matMVPLoc >= 0) { const glm::mat4x4 matProj = glm::perspective(glm::radians(45.0f), 800.0f / 600.0f, 0.1f, 100.0f); const glm::mat4x4 matView = glm::lookAt(viewPos, glm::vec3(0, 0, 0), glm::vec3(0, 1, 0)); const glm::mat4x4 matMVP = matProj * matView; glUniformMatrix4fv(matMVPLoc, 1, GL_FALSE, &matMVP[0][0]); } glBindVertexArray(vao); glDrawElements( GL_TRIANGLES, sizeof(indices)/sizeof(indices[0]), GL_UNSIGNED_INT, reinterpret_cast<const GLvoid*>(0)); window.SwapBuffers(); } glDeleteProgram(shaderProgram); glDeleteVertexArrays(1, &vao); return 0; }<|endoftext|>
<commit_before>/** * Copyright (C) 2005-2008 Christoph Rupp (chris@crupp.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. * * See files COPYING.* for License information. */ #include <cstring> #include <cppunit/extensions/HelperMacros.h> #include <ham/hamsterdb.h> #include "../src/os.h" #include "os.hpp" #if WIN32 # include <windows.h> #else # include <unistd.h> #endif static void HAM_CALLCONV my_errhandler(int level, const char *message) { (void)message; } class OsTest : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(OsTest); CPPUNIT_TEST (openCloseTest); CPPUNIT_TEST (openReadOnlyCloseTest); CPPUNIT_TEST (negativeOpenCloseTest); CPPUNIT_TEST (createCloseTest); CPPUNIT_TEST (createCloseOverwriteTest); CPPUNIT_TEST (closeTest); CPPUNIT_TEST (openExclusiveTest); CPPUNIT_TEST (readWriteTest); CPPUNIT_TEST (pagesizeTest); CPPUNIT_TEST (mmapTest); CPPUNIT_TEST (mmapReadOnlyTest); CPPUNIT_TEST (multipleMmapTest); CPPUNIT_TEST (negativeMmapTest); CPPUNIT_TEST (seekTellTest); CPPUNIT_TEST (negativeSeekTest); CPPUNIT_TEST (truncateTest); CPPUNIT_TEST (largefileTest); CPPUNIT_TEST_SUITE_END(); public: void setUp() { ham_set_errhandler(my_errhandler); } void tearDown() { (void)os::unlink(".test"); } void openCloseTest() { ham_status_t st; ham_fd_t fd; st=os_open("Makefile.am", 0, &fd); CPPUNIT_ASSERT(st==0); st=os_close(fd, 0); CPPUNIT_ASSERT(st==0); } void openReadOnlyCloseTest() { ham_status_t st; ham_fd_t fd; const char *p="# XXXXXXXXX ERROR\n"; st=os_open("Makefile.am", HAM_READ_ONLY, &fd); CPPUNIT_ASSERT(st==0); st=os_pwrite(fd, 0, p, (ham_size_t)strlen(p)); CPPUNIT_ASSERT(st==HAM_IO_ERROR); st=os_close(fd, 0); CPPUNIT_ASSERT(st==0); } void negativeOpenCloseTest() { ham_status_t st; ham_fd_t fd; st=os_open("__98324kasdlf.blöd", 0, &fd); CPPUNIT_ASSERT(st==HAM_FILE_NOT_FOUND); } void createCloseTest() { ham_status_t st; ham_fd_t fd; st=os_create(".test", 0, 0664, &fd); CPPUNIT_ASSERT_EQUAL(0, st); st=os_close(fd, 0); CPPUNIT_ASSERT_EQUAL(0, st); } void createCloseOverwriteTest() { ham_fd_t fd; ham_offset_t filesize; for (int i=0; i<3; i++) { CPPUNIT_ASSERT(os_create(".test", 0, 0664, &fd)==HAM_SUCCESS); CPPUNIT_ASSERT(os_seek(fd, 0, HAM_OS_SEEK_END)==HAM_SUCCESS); CPPUNIT_ASSERT(os_tell(fd, &filesize)==HAM_SUCCESS); CPPUNIT_ASSERT(filesize==0); CPPUNIT_ASSERT(os_truncate(fd, 1024)==HAM_SUCCESS); CPPUNIT_ASSERT(os_seek(fd, 0, HAM_OS_SEEK_END)==HAM_SUCCESS); CPPUNIT_ASSERT(os_tell(fd, &filesize)==HAM_SUCCESS); CPPUNIT_ASSERT(filesize==1024); CPPUNIT_ASSERT(os_close(fd, 0)==HAM_SUCCESS); } } void closeTest() { #ifndef WIN32 // crashs in ntdll.dll ham_status_t st; st=os_close((ham_fd_t)0x12345, 0); CPPUNIT_ASSERT(st==HAM_IO_ERROR); #endif } void openExclusiveTest() { /* fails on cygwin - cygwin bug? */ #ifndef __CYGWIN__ ham_fd_t fd, fd2; CPPUNIT_ASSERT_EQUAL(0, os_create(".test", HAM_LOCK_EXCLUSIVE, 0664, &fd)); CPPUNIT_ASSERT_EQUAL(0, os_close(fd, HAM_LOCK_EXCLUSIVE)); CPPUNIT_ASSERT_EQUAL(0, os_open(".test", HAM_LOCK_EXCLUSIVE, &fd)); CPPUNIT_ASSERT_EQUAL(HAM_WOULD_BLOCK, os_open(".test", HAM_LOCK_EXCLUSIVE, &fd2)); CPPUNIT_ASSERT_EQUAL(0, os_close(fd, HAM_LOCK_EXCLUSIVE)); CPPUNIT_ASSERT_EQUAL(0, os_open(".test", HAM_LOCK_EXCLUSIVE, &fd2)); CPPUNIT_ASSERT_EQUAL(0, os_close(fd2, HAM_LOCK_EXCLUSIVE)); CPPUNIT_ASSERT_EQUAL(0, os_open(".test", 0, &fd2)); CPPUNIT_ASSERT_EQUAL(0, os_close(fd2, 0)); #endif } void readWriteTest() { int i; ham_status_t st; ham_fd_t fd; char buffer[128], orig[128]; st=os_create(".test", 0, 0664, &fd); CPPUNIT_ASSERT(st==0); for (i=0; i<10; i++) { memset(buffer, i, sizeof(buffer)); st=os_pwrite(fd, i*sizeof(buffer), buffer, sizeof(buffer)); CPPUNIT_ASSERT(st==0); } for (i=0; i<10; i++) { memset(orig, i, sizeof(orig)); memset(buffer, 0, sizeof(buffer)); st=os_pread(fd, i*sizeof(buffer), buffer, sizeof(buffer)); CPPUNIT_ASSERT(st==0); CPPUNIT_ASSERT(0==memcmp(buffer, orig, sizeof(buffer))); } st=os_close(fd, 0); CPPUNIT_ASSERT(st==0); } void pagesizeTest() { ham_size_t ps=os_get_pagesize(); CPPUNIT_ASSERT(ps!=0); CPPUNIT_ASSERT(ps%1024==0); } void mmapTest() { int i; ham_status_t st; ham_fd_t fd, mmaph; ham_size_t ps=os_get_pagesize(); ham_u8_t *p1, *p2; p1=(ham_u8_t *)malloc(ps); st=os_create(".test", 0, 0664, &fd); CPPUNIT_ASSERT(st==0); for (i=0; i<10; i++) { memset(p1, i, ps); st=os_pwrite(fd, i*ps, p1, ps); CPPUNIT_ASSERT(st==0); } for (i=0; i<10; i++) { memset(p1, i, ps); st=os_mmap(fd, &mmaph, i*ps, ps, 0, &p2); CPPUNIT_ASSERT(st==0); CPPUNIT_ASSERT(0==memcmp(p1, p2, ps)); st=os_munmap(&mmaph, p2, ps); CPPUNIT_ASSERT(st==0); } st=os_close(fd, 0); CPPUNIT_ASSERT(st==0); free(p1); } void mmapReadOnlyTest() { int i; ham_fd_t fd, mmaph; ham_size_t ps=os_get_pagesize(); ham_u8_t *p1, *p2; p1=(ham_u8_t *)malloc(ps); CPPUNIT_ASSERT_EQUAL(0, os_create(".test", 0, 0664, &fd)); for (i=0; i<10; i++) { memset(p1, i, ps); CPPUNIT_ASSERT_EQUAL(0, os_pwrite(fd, i*ps, p1, ps)); } CPPUNIT_ASSERT_EQUAL(0, os_close(fd, 0)); CPPUNIT_ASSERT_EQUAL(0, os_open(".test", HAM_READ_ONLY, &fd)); for (i=0; i<10; i++) { memset(p1, i, ps); CPPUNIT_ASSERT_EQUAL(0, os_mmap(fd, &mmaph, i*ps, ps, HAM_READ_ONLY, &p2)); CPPUNIT_ASSERT_EQUAL(0, memcmp(p1, p2, ps)); CPPUNIT_ASSERT_EQUAL(0, os_munmap(&mmaph, p2, ps)); } CPPUNIT_ASSERT_EQUAL(0, os_close(fd, HAM_READ_ONLY)); free(p1); } void multipleMmapTest() { int i; ham_status_t st; ham_fd_t fd, mmaph; ham_size_t ps=os_get_pagesize(); ham_u8_t *p1, *p2; ham_offset_t addr=0, size; st=os_create(".test", 0, 0664, &fd); CPPUNIT_ASSERT(st==0); for (i=0; i<5; i++) { size=ps*(i+1); p1=(ham_u8_t *)malloc((size_t)size); memset(p1, i, (size_t)size); st=os_pwrite(fd, addr, p1, (ham_size_t)size); CPPUNIT_ASSERT(st==0); free(p1); addr+=size; } addr=0; for (i=0; i<5; i++) { size=ps*(i+1); p1=(ham_u8_t *)malloc((size_t)size); memset(p1, i, (size_t)size); st=os_mmap(fd, &mmaph, addr, (ham_size_t)size, 0, &p2); CPPUNIT_ASSERT(st==0); CPPUNIT_ASSERT(0==memcmp(p1, p2, (size_t)size)); st=os_munmap(&mmaph, p2, (ham_size_t)size); CPPUNIT_ASSERT(st==0); free(p1); addr+=size; } st=os_close(fd, 0); CPPUNIT_ASSERT(st==0); } void negativeMmapTest() { ham_fd_t fd, mmaph; ham_u8_t *page; CPPUNIT_ASSERT_EQUAL(0, os_create(".test", 0, 0664, &fd)); // bad address && page size! - i don't know why this succeeds // on MacOS... #ifndef __MACH__ CPPUNIT_ASSERT_EQUAL(HAM_IO_ERROR, os_mmap(fd, &mmaph, 33, 66, 0, &page)); #endif CPPUNIT_ASSERT_EQUAL(0, os_close(fd, 0)); } void seekTellTest() { int i; ham_status_t st; ham_fd_t fd; ham_offset_t tell; st=os_create(".test", 0, 0664, &fd); CPPUNIT_ASSERT(st==0); for (i=0; i<10; i++) { st=os_seek(fd, i, HAM_OS_SEEK_SET); CPPUNIT_ASSERT(st==0); st=os_tell(fd, &tell); CPPUNIT_ASSERT(st==0); CPPUNIT_ASSERT(tell==(ham_offset_t)i); } st=os_close(fd, 0); CPPUNIT_ASSERT(st==0); } void negativeSeekTest() { ham_status_t st; st=os_seek((ham_fd_t)0x12345, 0, HAM_OS_SEEK_SET); CPPUNIT_ASSERT(st==HAM_IO_ERROR); } void truncateTest() { int i; ham_status_t st; ham_fd_t fd; ham_offset_t fsize; st=os_create(".test", 0, 0664, &fd); CPPUNIT_ASSERT(st==0); for (i=0; i<10; i++) { st=os_truncate(fd, i*128); CPPUNIT_ASSERT(st==0); st=os_get_filesize(fd, &fsize); CPPUNIT_ASSERT(st==0); CPPUNIT_ASSERT(fsize==(ham_offset_t)(i*128)); } st=os_close(fd, 0); CPPUNIT_ASSERT(st==0); } void largefileTest() { int i; ham_status_t st; ham_fd_t fd; ham_u8_t kb[1024]; ham_offset_t tell; memset(kb, 0, sizeof(kb)); st=os_create(".test", 0, 0664, &fd); CPPUNIT_ASSERT(st==0); for (i=0; i<4*1024; i++) { st=os_pwrite(fd, i*sizeof(kb), kb, sizeof(kb)); CPPUNIT_ASSERT(st==0); } st=os_close(fd, 0); CPPUNIT_ASSERT(st==0); st=os_open(".test", 0, &fd); CPPUNIT_ASSERT(st==0); st=os_seek(fd, 0, HAM_OS_SEEK_END); CPPUNIT_ASSERT(st==0); st=os_tell(fd, &tell); CPPUNIT_ASSERT(st==0); CPPUNIT_ASSERT(tell==(ham_offset_t)1024*1024*4); st=os_close(fd, 0); CPPUNIT_ASSERT(st==0); } }; CPPUNIT_TEST_SUITE_REGISTRATION(OsTest); <commit_msg>disable mmap-tests for platforms without mmap<commit_after>/** * Copyright (C) 2005-2008 Christoph Rupp (chris@crupp.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. * * See files COPYING.* for License information. */ #include <cstring> #include <cppunit/extensions/HelperMacros.h> #include <ham/hamsterdb.h> #include "../src/os.h" #include "os.hpp" #if WIN32 # include <windows.h> #else # include <unistd.h> #endif static void HAM_CALLCONV my_errhandler(int level, const char *message) { (void)message; } class OsTest : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(OsTest); CPPUNIT_TEST (openCloseTest); CPPUNIT_TEST (openReadOnlyCloseTest); CPPUNIT_TEST (negativeOpenCloseTest); CPPUNIT_TEST (createCloseTest); CPPUNIT_TEST (createCloseOverwriteTest); CPPUNIT_TEST (closeTest); CPPUNIT_TEST (openExclusiveTest); CPPUNIT_TEST (readWriteTest); CPPUNIT_TEST (pagesizeTest); #if HAVE_MMAP CPPUNIT_TEST (mmapTest); CPPUNIT_TEST (mmapReadOnlyTest); CPPUNIT_TEST (multipleMmapTest); CPPUNIT_TEST (negativeMmapTest); #endif CPPUNIT_TEST (seekTellTest); CPPUNIT_TEST (negativeSeekTest); CPPUNIT_TEST (truncateTest); CPPUNIT_TEST (largefileTest); CPPUNIT_TEST_SUITE_END(); public: void setUp() { ham_set_errhandler(my_errhandler); } void tearDown() { (void)os::unlink(".test"); } void openCloseTest() { ham_status_t st; ham_fd_t fd; st=os_open("Makefile.am", 0, &fd); CPPUNIT_ASSERT(st==0); st=os_close(fd, 0); CPPUNIT_ASSERT(st==0); } void openReadOnlyCloseTest() { ham_status_t st; ham_fd_t fd; const char *p="# XXXXXXXXX ERROR\n"; st=os_open("Makefile.am", HAM_READ_ONLY, &fd); CPPUNIT_ASSERT(st==0); st=os_pwrite(fd, 0, p, (ham_size_t)strlen(p)); CPPUNIT_ASSERT(st==HAM_IO_ERROR); st=os_close(fd, 0); CPPUNIT_ASSERT(st==0); } void negativeOpenCloseTest() { ham_status_t st; ham_fd_t fd; st=os_open("__98324kasdlf.blöd", 0, &fd); CPPUNIT_ASSERT(st==HAM_FILE_NOT_FOUND); } void createCloseTest() { ham_status_t st; ham_fd_t fd; st=os_create(".test", 0, 0664, &fd); CPPUNIT_ASSERT_EQUAL(0, st); st=os_close(fd, 0); CPPUNIT_ASSERT_EQUAL(0, st); } void createCloseOverwriteTest() { ham_fd_t fd; ham_offset_t filesize; for (int i=0; i<3; i++) { CPPUNIT_ASSERT(os_create(".test", 0, 0664, &fd)==HAM_SUCCESS); CPPUNIT_ASSERT(os_seek(fd, 0, HAM_OS_SEEK_END)==HAM_SUCCESS); CPPUNIT_ASSERT(os_tell(fd, &filesize)==HAM_SUCCESS); CPPUNIT_ASSERT(filesize==0); CPPUNIT_ASSERT(os_truncate(fd, 1024)==HAM_SUCCESS); CPPUNIT_ASSERT(os_seek(fd, 0, HAM_OS_SEEK_END)==HAM_SUCCESS); CPPUNIT_ASSERT(os_tell(fd, &filesize)==HAM_SUCCESS); CPPUNIT_ASSERT(filesize==1024); CPPUNIT_ASSERT(os_close(fd, 0)==HAM_SUCCESS); } } void closeTest() { #ifndef WIN32 // crashs in ntdll.dll ham_status_t st; st=os_close((ham_fd_t)0x12345, 0); CPPUNIT_ASSERT(st==HAM_IO_ERROR); #endif } void openExclusiveTest() { /* fails on cygwin - cygwin bug? */ #ifndef __CYGWIN__ ham_fd_t fd, fd2; CPPUNIT_ASSERT_EQUAL(0, os_create(".test", HAM_LOCK_EXCLUSIVE, 0664, &fd)); CPPUNIT_ASSERT_EQUAL(0, os_close(fd, HAM_LOCK_EXCLUSIVE)); CPPUNIT_ASSERT_EQUAL(0, os_open(".test", HAM_LOCK_EXCLUSIVE, &fd)); CPPUNIT_ASSERT_EQUAL(HAM_WOULD_BLOCK, os_open(".test", HAM_LOCK_EXCLUSIVE, &fd2)); CPPUNIT_ASSERT_EQUAL(0, os_close(fd, HAM_LOCK_EXCLUSIVE)); CPPUNIT_ASSERT_EQUAL(0, os_open(".test", HAM_LOCK_EXCLUSIVE, &fd2)); CPPUNIT_ASSERT_EQUAL(0, os_close(fd2, HAM_LOCK_EXCLUSIVE)); CPPUNIT_ASSERT_EQUAL(0, os_open(".test", 0, &fd2)); CPPUNIT_ASSERT_EQUAL(0, os_close(fd2, 0)); #endif } void readWriteTest() { int i; ham_status_t st; ham_fd_t fd; char buffer[128], orig[128]; st=os_create(".test", 0, 0664, &fd); CPPUNIT_ASSERT(st==0); for (i=0; i<10; i++) { memset(buffer, i, sizeof(buffer)); st=os_pwrite(fd, i*sizeof(buffer), buffer, sizeof(buffer)); CPPUNIT_ASSERT(st==0); } for (i=0; i<10; i++) { memset(orig, i, sizeof(orig)); memset(buffer, 0, sizeof(buffer)); st=os_pread(fd, i*sizeof(buffer), buffer, sizeof(buffer)); CPPUNIT_ASSERT(st==0); CPPUNIT_ASSERT(0==memcmp(buffer, orig, sizeof(buffer))); } st=os_close(fd, 0); CPPUNIT_ASSERT(st==0); } void pagesizeTest() { ham_size_t ps=os_get_pagesize(); CPPUNIT_ASSERT(ps!=0); CPPUNIT_ASSERT(ps%1024==0); } void mmapTest() { int i; ham_status_t st; ham_fd_t fd, mmaph; ham_size_t ps=os_get_pagesize(); ham_u8_t *p1, *p2; p1=(ham_u8_t *)malloc(ps); st=os_create(".test", 0, 0664, &fd); CPPUNIT_ASSERT(st==0); for (i=0; i<10; i++) { memset(p1, i, ps); st=os_pwrite(fd, i*ps, p1, ps); CPPUNIT_ASSERT(st==0); } for (i=0; i<10; i++) { memset(p1, i, ps); st=os_mmap(fd, &mmaph, i*ps, ps, 0, &p2); CPPUNIT_ASSERT(st==0); CPPUNIT_ASSERT(0==memcmp(p1, p2, ps)); st=os_munmap(&mmaph, p2, ps); CPPUNIT_ASSERT(st==0); } st=os_close(fd, 0); CPPUNIT_ASSERT(st==0); free(p1); } void mmapReadOnlyTest() { int i; ham_fd_t fd, mmaph; ham_size_t ps=os_get_pagesize(); ham_u8_t *p1, *p2; p1=(ham_u8_t *)malloc(ps); CPPUNIT_ASSERT_EQUAL(0, os_create(".test", 0, 0664, &fd)); for (i=0; i<10; i++) { memset(p1, i, ps); CPPUNIT_ASSERT_EQUAL(0, os_pwrite(fd, i*ps, p1, ps)); } CPPUNIT_ASSERT_EQUAL(0, os_close(fd, 0)); CPPUNIT_ASSERT_EQUAL(0, os_open(".test", HAM_READ_ONLY, &fd)); for (i=0; i<10; i++) { memset(p1, i, ps); CPPUNIT_ASSERT_EQUAL(0, os_mmap(fd, &mmaph, i*ps, ps, HAM_READ_ONLY, &p2)); CPPUNIT_ASSERT_EQUAL(0, memcmp(p1, p2, ps)); CPPUNIT_ASSERT_EQUAL(0, os_munmap(&mmaph, p2, ps)); } CPPUNIT_ASSERT_EQUAL(0, os_close(fd, HAM_READ_ONLY)); free(p1); } void multipleMmapTest() { int i; ham_status_t st; ham_fd_t fd, mmaph; ham_size_t ps=os_get_pagesize(); ham_u8_t *p1, *p2; ham_offset_t addr=0, size; st=os_create(".test", 0, 0664, &fd); CPPUNIT_ASSERT(st==0); for (i=0; i<5; i++) { size=ps*(i+1); p1=(ham_u8_t *)malloc((size_t)size); memset(p1, i, (size_t)size); st=os_pwrite(fd, addr, p1, (ham_size_t)size); CPPUNIT_ASSERT(st==0); free(p1); addr+=size; } addr=0; for (i=0; i<5; i++) { size=ps*(i+1); p1=(ham_u8_t *)malloc((size_t)size); memset(p1, i, (size_t)size); st=os_mmap(fd, &mmaph, addr, (ham_size_t)size, 0, &p2); CPPUNIT_ASSERT(st==0); CPPUNIT_ASSERT(0==memcmp(p1, p2, (size_t)size)); st=os_munmap(&mmaph, p2, (ham_size_t)size); CPPUNIT_ASSERT(st==0); free(p1); addr+=size; } st=os_close(fd, 0); CPPUNIT_ASSERT(st==0); } void negativeMmapTest() { ham_fd_t fd, mmaph; ham_u8_t *page; CPPUNIT_ASSERT_EQUAL(0, os_create(".test", 0, 0664, &fd)); // bad address && page size! - i don't know why this succeeds // on MacOS... #ifndef __MACH__ CPPUNIT_ASSERT_EQUAL(HAM_IO_ERROR, os_mmap(fd, &mmaph, 33, 66, 0, &page)); #endif CPPUNIT_ASSERT_EQUAL(0, os_close(fd, 0)); } void seekTellTest() { int i; ham_status_t st; ham_fd_t fd; ham_offset_t tell; st=os_create(".test", 0, 0664, &fd); CPPUNIT_ASSERT(st==0); for (i=0; i<10; i++) { st=os_seek(fd, i, HAM_OS_SEEK_SET); CPPUNIT_ASSERT(st==0); st=os_tell(fd, &tell); CPPUNIT_ASSERT(st==0); CPPUNIT_ASSERT(tell==(ham_offset_t)i); } st=os_close(fd, 0); CPPUNIT_ASSERT(st==0); } void negativeSeekTest() { ham_status_t st; st=os_seek((ham_fd_t)0x12345, 0, HAM_OS_SEEK_SET); CPPUNIT_ASSERT(st==HAM_IO_ERROR); } void truncateTest() { int i; ham_status_t st; ham_fd_t fd; ham_offset_t fsize; st=os_create(".test", 0, 0664, &fd); CPPUNIT_ASSERT(st==0); for (i=0; i<10; i++) { st=os_truncate(fd, i*128); CPPUNIT_ASSERT(st==0); st=os_get_filesize(fd, &fsize); CPPUNIT_ASSERT(st==0); CPPUNIT_ASSERT(fsize==(ham_offset_t)(i*128)); } st=os_close(fd, 0); CPPUNIT_ASSERT(st==0); } void largefileTest() { int i; ham_status_t st; ham_fd_t fd; ham_u8_t kb[1024]; ham_offset_t tell; memset(kb, 0, sizeof(kb)); st=os_create(".test", 0, 0664, &fd); CPPUNIT_ASSERT(st==0); for (i=0; i<4*1024; i++) { st=os_pwrite(fd, i*sizeof(kb), kb, sizeof(kb)); CPPUNIT_ASSERT(st==0); } st=os_close(fd, 0); CPPUNIT_ASSERT(st==0); st=os_open(".test", 0, &fd); CPPUNIT_ASSERT(st==0); st=os_seek(fd, 0, HAM_OS_SEEK_END); CPPUNIT_ASSERT(st==0); st=os_tell(fd, &tell); CPPUNIT_ASSERT(st==0); CPPUNIT_ASSERT(tell==(ham_offset_t)1024*1024*4); st=os_close(fd, 0); CPPUNIT_ASSERT(st==0); } }; CPPUNIT_TEST_SUITE_REGISTRATION(OsTest); <|endoftext|>
<commit_before>#include "mitkMovieGenerator.h" #include <GL/gl.h> #ifdef WIN32 #include "mitkMovieGeneratorWin32.h" #endif #ifndef GL_BGR #define GL_BGR GL_BGR_EXT #endif mitk::MovieGenerator::Pointer mitk::MovieGenerator::New() { Pointer smartPtr; MovieGenerator *rawPtr = ::itk::ObjectFactory<MovieGenerator>::Create(); if(rawPtr == NULL) { #ifdef WIN32 MovieGeneratorWin32::Pointer wp = MovieGeneratorWin32::New(); return wp; //rawPtr = (MovieGenerator*)MovieGeneratorWin32::New(); #endif } smartPtr = rawPtr; rawPtr->UnRegister(); return smartPtr; } bool mitk::MovieGenerator::WriteMovie() { bool ok = false; if (m_stepper) { m_stepper->First(); ok = InitGenerator(); if (!ok) return false; int imgSize = 3 * m_width * m_height; printf( "Video size = %i x %i\n", m_width, m_height ); GLbyte *data = new GLbyte[imgSize]; for (int i=0; i<m_stepper->GetSteps(); i++) { if (m_renderer) m_renderer->MakeCurrent(); glReadPixels( 0, 0, m_width, m_height, GL_BGR, GL_UNSIGNED_BYTE, (void*)data ); AddFrame( data ); m_stepper->Next(); } ok = TerminateGenerator(); delete[] data; } return ok; }<commit_msg>FIX: Crash under Linux<commit_after>#include "mitkMovieGenerator.h" #include <GL/gl.h> #ifdef WIN32 #include "mitkMovieGeneratorWin32.h" #endif #ifndef GL_BGR #define GL_BGR GL_BGR_EXT #endif mitk::MovieGenerator::Pointer mitk::MovieGenerator::New() { Pointer smartPtr; MovieGenerator *rawPtr = ::itk::ObjectFactory<MovieGenerator>::Create(); if(rawPtr == NULL) { #ifdef WIN32 MovieGeneratorWin32::Pointer wp = MovieGeneratorWin32::New(); return wp; #endif } smartPtr = rawPtr; if(rawPtr != NULL) rawPtr->UnRegister(); return smartPtr; } bool mitk::MovieGenerator::WriteMovie() { bool ok = false; if (m_stepper) { m_stepper->First(); ok = InitGenerator(); if (!ok) return false; int imgSize = 3 * m_width * m_height; printf( "Video size = %i x %i\n", m_width, m_height ); GLbyte *data = new GLbyte[imgSize]; for (int i=0; i<m_stepper->GetSteps(); i++) { if (m_renderer) m_renderer->MakeCurrent(); glReadPixels( 0, 0, m_width, m_height, GL_BGR, GL_UNSIGNED_BYTE, (void*)data ); AddFrame( data ); m_stepper->Next(); } ok = TerminateGenerator(); delete[] data; } return ok; }<|endoftext|>
<commit_before> #include "AudioData.h" #include "WavParser.h" #include "AudioPlaybackStream.h" #include "AudioStreamBuffer.h" #include "AudioMixer.h" #include "EngineTrack.h" #include "EngineSample.h" #include "Initializer.h" #include "OALWrapper/OAL_Funcs.h" #include "SDL_timer.h" #include <iostream> #include <vector> #ifdef _WIN32 #include <direct.h> #else #include <unistd.h> #endif int main( int argc, char *argv[] ) { // fix up working directory { char temp[128] = {}; const char *dir = getcwd(temp, sizeof(temp)); const char *bin_pos = strstr(dir, "bin"); const char *build_pos = strstr(dir, "build"); if (bin_pos) { chdir(".."); } else if (build_pos) { chdir("../.."); } } // OAL_SetupLogging(true,eOAL_LogOutput_File,eOAL_LogVerbose_High); cOAL_Init_Params oal_parms; oal_parms.mlStreamingBufferSize = 8192; if (OAL_Init(oal_parms)==false) { printf ("Failed - Check your OpenAL installation\n"); return 0; } else { printf ("Success\n"); } AudioMixer<16> mixer; std::vector<std::unique_ptr<AudioStreamBuffer>> streamBuffers; std::unique_ptr<EngineTrack> ambientRain(Initializer::InitializeTrack("tracks/ambient_rain.track")); if (!ambientRain) { return -1; } for (auto &sample : ambientRain->getSamples()) { const AudioSample *audioSample = sample.getSample(); streamBuffers.emplace_back(new AudioStreamBuffer(audioSample->getBitsPerSample())); streamBuffers.back()->PushSamples(audioSample->getSamples(), audioSample->getNumSamples()); mixer.ConnectInputStream(streamBuffers.back().get()); } AudioStreamBuffer mixerOutput(16, true); mixer.ConnectOutputStream(&mixerOutput); mixer.Mix(); AudioPlaybackStream stream(16); stream.SetInputStream(&mixerOutput); stream.InitStream(1, 44100, AL_FORMAT_MONO16); while (stream.IsPlaying()) { if (mixerOutput.GetNumSamples() <= oal_parms.mlStreamingBufferSize) { for (int i = 0; i < (int)streamBuffers.size(); ++i) { const AudioSample *audioSample = ambientRain->GetEngineSample(i).getSample(); streamBuffers[i]->PushSamples(audioSample->getSamples(), audioSample->getNumSamples()); std::cout << streamBuffers[i]->GetNumSamples() << std::endl; } mixer.Mix(); } else { SDL_Delay(10); } // sleep if you want } stream.DestroyStream(); OAL_Close(); return 0; } <commit_msg>made input buffers push samples independently to prevent long samples from building up large buffers<commit_after> #include "AudioData.h" #include "WavParser.h" #include "AudioPlaybackStream.h" #include "AudioStreamBuffer.h" #include "AudioMixer.h" #include "EngineTrack.h" #include "EngineSample.h" #include "Initializer.h" #include "OALWrapper/OAL_Funcs.h" #include "SDL_timer.h" #include <iostream> #include <vector> #ifdef _WIN32 #include <direct.h> #else #include <unistd.h> #endif int main( int argc, char *argv[] ) { // fix up working directory { char temp[128] = {}; const char *dir = getcwd(temp, sizeof(temp)); const char *bin_pos = strstr(dir, "bin"); const char *build_pos = strstr(dir, "build"); if (bin_pos) { chdir(".."); } else if (build_pos) { chdir("../.."); } } // OAL_SetupLogging(true,eOAL_LogOutput_File,eOAL_LogVerbose_High); cOAL_Init_Params oal_parms; oal_parms.mlStreamingBufferSize = 8192; if (OAL_Init(oal_parms)==false) { printf ("Failed - Check your OpenAL installation\n"); return 0; } else { printf ("Success\n"); } AudioMixer<16> mixer; std::vector<std::unique_ptr<AudioStreamBuffer>> streamBuffers; std::unique_ptr<EngineTrack> ambientRain(Initializer::InitializeTrack("tracks/ambient_rain.track")); if (!ambientRain) { return -1; } for (auto &sample : ambientRain->getSamples()) { const AudioSample *audioSample = sample.getSample(); streamBuffers.emplace_back(new AudioStreamBuffer(audioSample->getBitsPerSample())); streamBuffers.back()->PushSamples(audioSample->getSamples(), audioSample->getNumSamples()); mixer.ConnectInputStream(streamBuffers.back().get()); } AudioStreamBuffer mixerOutput(16, true); mixer.ConnectOutputStream(&mixerOutput); mixer.Mix(); AudioPlaybackStream stream(16); stream.SetInputStream(&mixerOutput); stream.InitStream(1, 44100, AL_FORMAT_MONO16); while (stream.IsPlaying()) { for (int i = 0; i < (int)streamBuffers.size(); ++i) { auto &buffer = streamBuffers[i]; if (buffer->GetNumSamples() <= oal_parms.mlStreamingBufferSize) { const auto *audioSample = ambientRain->GetEngineSample(i).getSample(); buffer->PushSamples(audioSample->getSamples(), audioSample->getNumSamples()); std::cout << buffer->GetNumSamples() << std::endl; } } if (mixerOutput.GetNumSamples() <= oal_parms.mlStreamingBufferSize) { mixer.Mix(); std::cout << "mixing" << std::endl; for (auto &buffer : streamBuffers) { std::cout << buffer->GetNumSamples() << std::endl; } } else { SDL_Delay(10); } // sleep if you want } stream.DestroyStream(); OAL_Close(); return 0; } <|endoftext|>
<commit_before>#define CATCH_CONFIG_MAIN #include "catch.hpp" #include "RPNCalc.h" #include "RPNTestHelper.h" using namespace P4_RPNCALC; TEST_CASE("Operation Methods") { RPNTestHelper test; SECTION("Method: clearAll()") { REQUIRE(test.expectedInputOutput("50", "50")); REQUIRE(test.expectedInputOutput("c", "")); REQUIRE(test.expectedInputOutput("50 100 +", "150")); REQUIRE(test.expectedInputOutput("c", "")); REQUIRE(test.expectedInputOutput("50", "50")); REQUIRE(test.expectedInputOutput("C", "")); REQUIRE(test.expectedInputOutput("50 100 +", "150")); REQUIRE(test.expectedInputOutput("C", "")); } SECTION("Method: clearEntry()") { REQUIRE(test.expectedInputOutput("50", "50")); REQUIRE(test.expectedInputOutput("ce", "")); REQUIRE(test.expectedInputOutput("50 100 +", "150")); REQUIRE(test.expectedInputOutput("ce", "")); REQUIRE(test.expectedInputOutput("50 100 + 200", "200")); REQUIRE(test.expectedInputOutput("ce", "150")); REQUIRE(test.expectedInputOutput("ce", "")); REQUIRE(test.expectedInputOutput("50", "50")); REQUIRE(test.expectedInputOutput("CE", "")); REQUIRE(test.expectedInputOutput("50 100 +", "150")); REQUIRE(test.expectedInputOutput("CE", "")); REQUIRE(test.expectedInputOutput("50 100 + 200", "200")); REQUIRE(test.expectedInputOutput("CE", "150")); REQUIRE(test.expectedInputOutput("CE", "")); } SECTION("Method: add()") { REQUIRE(test.expectedInputOutput("3 5 +", "8")); REQUIRE(test.expectedInputOutput("2 4 3 +", "7")); REQUIRE(test.expectedInputOutput("c", "")); REQUIRE(test.expectedInputOutput("3 4 + 6", "6")); REQUIRE(test.expectedInputOutput("4 +", "10")); REQUIRE(test.expectedInputOutput("-12 +", "-2")); REQUIRE(test.expectedInputOutput("5 +", "3")); REQUIRE(test.expectedInputOutput("3 +", "6")); REQUIRE(test.expectedInputOutput("10 100 +", "110")); REQUIRE(test.expectedInputOutput("10 100+", "110")); REQUIRE(test.expectedInputOutput("+", "<<error>>")); } SECTION("Method: combinations of add() & subtract()") { REQUIRE(test.expectedInputOutput("40 50 + 60 -", "30")); REQUIRE(test.expectedInputOutput("40 50 - 60 +", "50")); REQUIRE(test.expectedInputOutput("40 50 60 + -", "-70")); REQUIRE(test.expectedInputOutput("40 50 60 - +", "30")); REQUIRE(test.expectedInputOutput("-40 -50 + 60 -", "-150")); REQUIRE(test.expectedInputOutput("-40 -50 + -60 -", "-30")); REQUIRE(test.expectedInputOutput("-40 -50 - 60 +", "70")); REQUIRE(test.expectedInputOutput("-40 -50 - -60 +", "-50")); } SECTION("Method: subtract()") { REQUIRE(test.expectedInputOutput("5 6 -", "-1")); REQUIRE(test.expectedInputOutput("3 9 4 -", "5")); REQUIRE(test.expectedInputOutput("-", "-2")); REQUIRE(test.expectedInputOutput("c", "")); REQUIRE(test.expectedInputOutput("-1 5 -", "-6")); REQUIRE(test.expectedInputOutput("10 100 -", "-90")); REQUIRE(test.expectedInputOutput("10 100-", "-90")); REQUIRE(test.expectedInputOutput("-", "<<error>>")); } SECTION("Method: multiply()") { REQUIRE(test.expectedInputOutput("3 9 7 2 4 *", "8")); REQUIRE(test.expectedInputOutput("*", "56")); REQUIRE(test.expectedInputOutput("*", "504")); REQUIRE(test.expectedInputOutput("*", "1512")); REQUIRE(test.expectedInputOutput("*", "<<error>>")); REQUIRE(test.expectedInputOutput("c", "")); REQUIRE(test.expectedInputOutput("-4 -6 *", "24")); REQUIRE(test.expectedInputOutput("-2 *", "-48")); REQUIRE(test.expectedInputOutput("10 100 *", "1000")); REQUIRE(test.expectedInputOutput("10 100*", "1000")); } SECTION("Method: divide()") { REQUIRE(test.expectedInputOutput("16 4 2 /", "2")); REQUIRE(test.expectedInputOutput("/", "8")); REQUIRE(test.expectedInputOutput("c", "")); REQUIRE(test.expectedInputOutput("2 5 /", "0.4")); REQUIRE(test.expectedInputOutput("9 3 7 /", "0.428571")); REQUIRE(test.expectedInputOutput("-1 /", "-0.428571")); REQUIRE(test.expectedInputOutput("-1 / ", "0.428571")); REQUIRE(test.expectedInputOutput("100 10 /", "10")); REQUIRE(test.expectedInputOutput("100 10/", "10")); REQUIRE(test.expectedInputOutput("/", "<<error>>")); } SECTION("Method: mod()") { REQUIRE(test.expectedInputOutput("16 8 6 %", "2")); REQUIRE(test.expectedInputOutput("%", "0")); REQUIRE(test.expectedInputOutput("c", "")); REQUIRE(test.expectedInputOutput("%", "<<error>>")); REQUIRE(test.expectedInputOutput("10 1 %", "0")); REQUIRE(test.expectedInputOutput("10 2 %", "0")); REQUIRE(test.expectedInputOutput("10 3 %", "1")); REQUIRE(test.expectedInputOutput("10 4 %", "2")); REQUIRE(test.expectedInputOutput("10 5 %", "0")); REQUIRE(test.expectedInputOutput("10 6 %", "4")); REQUIRE(test.expectedInputOutput("10 7 %", "3")); REQUIRE(test.expectedInputOutput("10 8 %", "2")); REQUIRE(test.expectedInputOutput("10 9 %", "1")); REQUIRE(test.expectedInputOutput("10 10 %", "0")); REQUIRE(test.expectedInputOutput("100 70 %", "30")); REQUIRE(test.expectedInputOutput("100 70%", "30")); } SECTION("Method: exp()") { REQUIRE(test.expectedInputOutput("10 2 ^", "100")); REQUIRE(test.expectedInputOutput("10 2 2 ^", "4")); REQUIRE(test.expectedInputOutput("^", "10000")); REQUIRE(test.expectedInputOutput("-10 2 ^", "100")); REQUIRE(test.expectedInputOutput("-10 3 ^", "-1000")); REQUIRE(test.expectedInputOutput("-10 3^", "-1000")); REQUIRE(test.expectedInputOutput("0^", "1")); REQUIRE(test.expectedInputOutput("^", "<<error>>")); REQUIRE(test.expectedInputOutput("c", "")); REQUIRE(test.expectedInputOutput("100 100^", "1e+200")); } SECTION("Method: neg()") { REQUIRE(test.expectedInputOutput("-1000", "-1000")); REQUIRE(test.expectedInputOutput("M", "1000")); REQUIRE(test.expectedInputOutput("-1000 -1*", "1000")); REQUIRE(test.expectedInputOutput("M", "-1000")); REQUIRE(test.expectedInputOutput("-4/", "-250")); REQUIRE(test.expectedInputOutput("m", "250")); REQUIRE(test.expectedInputOutput("-2*", "-500")); REQUIRE(test.expectedInputOutput("m", "500")); REQUIRE(test.expectedInputOutput("c", "")); REQUIRE(test.expectedInputOutput("m", "<<error>>")); REQUIRE(test.expectedInputOutput("c", "")); REQUIRE(test.expectedInputOutput("M", "<<error>>")); } SECTION("Method: rotateDown()") { REQUIRE(test.expectedInputOutput("100 200", "200")); REQUIRE(test.expectedInputOutput("D", "100")); REQUIRE(test.expectedInputOutput("D", "200")); REQUIRE(test.expectedInputOutput("d", "100")); REQUIRE(test.expectedInputOutput("d", "200")); REQUIRE(test.expectedInputOutput("c", "")); REQUIRE(test.expectedInputOutput("D", "<<error>>")); REQUIRE(test.expectedInputOutput("c", "")); REQUIRE(test.expectedInputOutput("d", "<<error>>")); } SECTION("Method: rotateUp()") { REQUIRE(test.expectedInputOutput("300 500", "500")); REQUIRE(test.expectedInputOutput("U", "300")); REQUIRE(test.expectedInputOutput("U", "500")); REQUIRE(test.expectedInputOutput("u", "300")); REQUIRE(test.expectedInputOutput("u", "500")); REQUIRE(test.expectedInputOutput("c", "")); REQUIRE(test.expectedInputOutput("U", "<<error>>")); REQUIRE(test.expectedInputOutput("c", "")); REQUIRE(test.expectedInputOutput("u", "<<error>>")); } } <commit_msg>Create RPN_UnitTests.cpp<commit_after>#define CATCH_CONFIG_MAIN #include "catch.hpp" #include "RPNCalc.h" #include "RPNTestHelper.h" using namespace P4_RPNCALC; TEST_CASE("Operation Methods") { RPNTestHelper test; SECTION("Method: clearAll()") { REQUIRE(test.expectedInputOutput("50", "50")); REQUIRE(test.expectedInputOutput("c", "")); REQUIRE(test.expectedInputOutput("50 100 +", "150")); REQUIRE(test.expectedInputOutput("c", "")); REQUIRE(test.expectedInputOutput("50 100 + 200", "200")); REQUIRE(test.expectedInputOutput("c", "")); REQUIRE(test.expectedInputOutput("CE", "")); REQUIRE(test.expectedInputOutput("50", "50")); REQUIRE(test.expectedInputOutput("C", "")); REQUIRE(test.expectedInputOutput("50 100 +", "150")); REQUIRE(test.expectedInputOutput("C", "")); REQUIRE(test.expectedInputOutput("50 100 + 200", "200")); REQUIRE(test.expectedInputOutput("C", "")); } SECTION("Method: clearEntry()") { REQUIRE(test.expectedInputOutput("50", "50")); REQUIRE(test.expectedInputOutput("ce", "")); REQUIRE(test.expectedInputOutput("50 100 +", "150")); REQUIRE(test.expectedInputOutput("ce", "")); REQUIRE(test.expectedInputOutput("50 100 + 200", "200")); REQUIRE(test.expectedInputOutput("ce", "150")); REQUIRE(test.expectedInputOutput("ce", "")); REQUIRE(test.expectedInputOutput("50", "50")); REQUIRE(test.expectedInputOutput("CE", "")); REQUIRE(test.expectedInputOutput("50 100 +", "150")); REQUIRE(test.expectedInputOutput("CE", "")); REQUIRE(test.expectedInputOutput("50 100 + 200", "200")); REQUIRE(test.expectedInputOutput("CE", "150")); REQUIRE(test.expectedInputOutput("CE", "")); } SECTION("Method: add()") { REQUIRE(test.expectedInputOutput("3 5 +", "8")); REQUIRE(test.expectedInputOutput("2 4 3 +", "7")); REQUIRE(test.expectedInputOutput("c", "")); REQUIRE(test.expectedInputOutput("3 4 + 6", "6")); REQUIRE(test.expectedInputOutput("4 +", "10")); REQUIRE(test.expectedInputOutput("-12 +", "-2")); REQUIRE(test.expectedInputOutput("5 +", "3")); REQUIRE(test.expectedInputOutput("3 +", "6")); REQUIRE(test.expectedInputOutput("10 100 +", "110")); REQUIRE(test.expectedInputOutput("10 100+", "110")); REQUIRE(test.expectedInputOutput("+", "<<error>>")); } SECTION("Method: combinations of add() & subtract()") { REQUIRE(test.expectedInputOutput("40 50 + 60 -", "30")); REQUIRE(test.expectedInputOutput("40 50 - 60 +", "50")); REQUIRE(test.expectedInputOutput("40 50 60 + -", "-70")); REQUIRE(test.expectedInputOutput("40 50 60 - +", "30")); REQUIRE(test.expectedInputOutput("-40 -50 + 60 -", "-150")); REQUIRE(test.expectedInputOutput("-40 -50 + -60 -", "-30")); REQUIRE(test.expectedInputOutput("-40 -50 - 60 +", "70")); REQUIRE(test.expectedInputOutput("-40 -50 - -60 +", "-50")); } SECTION("Method: subtract()") { REQUIRE(test.expectedInputOutput("5 6 -", "-1")); REQUIRE(test.expectedInputOutput("3 9 4 -", "5")); REQUIRE(test.expectedInputOutput("-", "-2")); REQUIRE(test.expectedInputOutput("c", "")); REQUIRE(test.expectedInputOutput("-1 5 -", "-6")); REQUIRE(test.expectedInputOutput("10 100 -", "-90")); REQUIRE(test.expectedInputOutput("10 100-", "-90")); REQUIRE(test.expectedInputOutput("-", "<<error>>")); } SECTION("Method: multiply()") { REQUIRE(test.expectedInputOutput("3 9 7 2 4 *", "8")); REQUIRE(test.expectedInputOutput("*", "56")); REQUIRE(test.expectedInputOutput("*", "504")); REQUIRE(test.expectedInputOutput("*", "1512")); REQUIRE(test.expectedInputOutput("*", "<<error>>")); REQUIRE(test.expectedInputOutput("c", "")); REQUIRE(test.expectedInputOutput("-4 -6 *", "24")); REQUIRE(test.expectedInputOutput("-2 *", "-48")); REQUIRE(test.expectedInputOutput("10 100 *", "1000")); REQUIRE(test.expectedInputOutput("10 100*", "1000")); } SECTION("Method: divide()") { REQUIRE(test.expectedInputOutput("16 4 2 /", "2")); REQUIRE(test.expectedInputOutput("/", "8")); REQUIRE(test.expectedInputOutput("c", "")); REQUIRE(test.expectedInputOutput("2 5 /", "0.4")); REQUIRE(test.expectedInputOutput("9 3 7 /", "0.428571")); REQUIRE(test.expectedInputOutput("-1 /", "-0.428571")); REQUIRE(test.expectedInputOutput("-1 / ", "0.428571")); REQUIRE(test.expectedInputOutput("100 10 /", "10")); REQUIRE(test.expectedInputOutput("100 10/", "10")); REQUIRE(test.expectedInputOutput("/", "<<error>>")); } SECTION("Method: mod()") { REQUIRE(test.expectedInputOutput("16 8 6 %", "2")); REQUIRE(test.expectedInputOutput("%", "0")); REQUIRE(test.expectedInputOutput("c", "")); REQUIRE(test.expectedInputOutput("%", "<<error>>")); REQUIRE(test.expectedInputOutput("10 1 %", "0")); REQUIRE(test.expectedInputOutput("10 2 %", "0")); REQUIRE(test.expectedInputOutput("10 3 %", "1")); REQUIRE(test.expectedInputOutput("10 4 %", "2")); REQUIRE(test.expectedInputOutput("10 5 %", "0")); REQUIRE(test.expectedInputOutput("10 6 %", "4")); REQUIRE(test.expectedInputOutput("10 7 %", "3")); REQUIRE(test.expectedInputOutput("10 8 %", "2")); REQUIRE(test.expectedInputOutput("10 9 %", "1")); REQUIRE(test.expectedInputOutput("10 10 %", "0")); REQUIRE(test.expectedInputOutput("100 70 %", "30")); REQUIRE(test.expectedInputOutput("100 70%", "30")); } SECTION("Method: exp()") { REQUIRE(test.expectedInputOutput("10 2 ^", "100")); REQUIRE(test.expectedInputOutput("10 2 2 ^", "4")); REQUIRE(test.expectedInputOutput("^", "10000")); REQUIRE(test.expectedInputOutput("-10 2 ^", "100")); REQUIRE(test.expectedInputOutput("-10 3 ^", "-1000")); REQUIRE(test.expectedInputOutput("-10 3^", "-1000")); REQUIRE(test.expectedInputOutput("0^", "1")); REQUIRE(test.expectedInputOutput("^", "<<error>>")); REQUIRE(test.expectedInputOutput("c", "")); REQUIRE(test.expectedInputOutput("100 100^", "1e+200")); } SECTION("Method: neg()") { REQUIRE(test.expectedInputOutput("-1000", "-1000")); REQUIRE(test.expectedInputOutput("M", "1000")); REQUIRE(test.expectedInputOutput("-1000 -1*", "1000")); REQUIRE(test.expectedInputOutput("M", "-1000")); REQUIRE(test.expectedInputOutput("-4/", "-250")); REQUIRE(test.expectedInputOutput("m", "250")); REQUIRE(test.expectedInputOutput("-2*", "-500")); REQUIRE(test.expectedInputOutput("m", "500")); REQUIRE(test.expectedInputOutput("c", "")); REQUIRE(test.expectedInputOutput("m", "<<error>>")); REQUIRE(test.expectedInputOutput("c", "")); REQUIRE(test.expectedInputOutput("M", "<<error>>")); } SECTION("Method: rotateDown()") { REQUIRE(test.expectedInputOutput("100 200", "200")); REQUIRE(test.expectedInputOutput("D", "100")); REQUIRE(test.expectedInputOutput("D", "200")); REQUIRE(test.expectedInputOutput("d", "100")); REQUIRE(test.expectedInputOutput("d", "200")); REQUIRE(test.expectedInputOutput("c", "")); REQUIRE(test.expectedInputOutput("D", "<<error>>")); REQUIRE(test.expectedInputOutput("c", "")); REQUIRE(test.expectedInputOutput("d", "<<error>>")); } SECTION("Method: rotateUp()") { REQUIRE(test.expectedInputOutput("300 500", "500")); REQUIRE(test.expectedInputOutput("U", "300")); REQUIRE(test.expectedInputOutput("U", "500")); REQUIRE(test.expectedInputOutput("u", "300")); REQUIRE(test.expectedInputOutput("u", "500")); REQUIRE(test.expectedInputOutput("c", "")); REQUIRE(test.expectedInputOutput("U", "<<error>>")); REQUIRE(test.expectedInputOutput("c", "")); REQUIRE(test.expectedInputOutput("u", "<<error>>")); } } <|endoftext|>
<commit_before>#include "soundController.h" #include "DataSetting.h" using namespace CocosDenshion; //constructor soundController::soundController() { } soundController::~soundController() {} //preload void soundController::initAudio() { auto audio = SimpleAudioEngine::getInstance(); //opening background audio->setBackgroundMusicVolume(0.5); //audio->preloadBackgroundMusic("sound/opening_back.wav"); //opening audio->preloadEffect("sound/op1_k.mp3"); audio->preloadEffect("sound/op2_k.mp3"); audio->preloadEffect("sound/op3_k.mp3"); audio->preloadEffect("sound/op1_e.mp3"); audio->preloadEffect("sound/op2_e.mp3"); audio->preloadEffect("sound/op3_e.mp3"); //game background audio->preloadBackgroundMusic("sound/game_back.wav"); //puzzle sound audio->preloadEffect("sound/wrong.wav"); //wrong //narations //korea narations audio->preloadEffect("sound/p1_n_k.mp3"); //p1Scene audio->preloadEffect("sound/p2_n_k.mp3"); //p2Scene audio->preloadEffect("sound/p3_n_k.mp3"); //p3Scene audio->preloadEffect("sound/p4_n_k.mp3"); //p4Scene audio->preloadEffect("sound/p5_n_k.mp3"); //p5Scene audio->preloadEffect("sound/p6_n_k.mp3"); //p6Scene //english narations audio->preloadEffect("sound/p1_n_e.mp3"); //p1Scene audio->preloadEffect("sound/p2_n_e.mp3"); //p2Scene audio->preloadEffect("sound/p3_n_e.mp3"); //p3Scene audio->preloadEffect("sound/p4_n_e.mp3"); //p4Scene audio->preloadEffect("sound/p5_n_e.mp3"); //p5Scene audio->preloadEffect("sound/p6_n_e.mp3"); //p6Scene //door open audio->preloadEffect("sound/door.wav"); //door open //end effect audio->preloadEffect("sound/tada.mp3"); //each game finish //correct eff audio->preloadEffect("sound/good_k.mp3"); //good audio->preloadEffect("sound/excellent_k.mp3"); //welldone audio->preloadEffect("sound/good_e.mp3"); //good audio->preloadEffect("sound/excellent_e.mp3"); //welldone //splashScene sound audio->preloadEffect("sound/start_k.mp3"); audio->preloadEffect("sound/start_e.mp3"); //finishing audio->preloadBackgroundMusic("sound/ending.wav"); //ending } void soundController::splashSound() { if (UserDefault::getInstance()->getBoolForKey("sound") == false) return; auto audio = SimpleAudioEngine::getInstance(); isKorea = UserDefault::getInstance()->getBoolForKey("kor"); //stop background sound backgroundSoundStop(); if (isKorea) audio->playEffect("sound/start_k.mp3"); else audio->playEffect("sound/start_e.mp3"); } //puzzle - pick up void soundController::puzzlePickUp() { if (UserDefault::getInstance()->getBoolForKey("sound") == false) return; auto audio = SimpleAudioEngine::getInstance(); //no sound } //puzzle - wrong location void soundController::puzzleWrong() { if (UserDefault::getInstance()->getBoolForKey("sound") == false) return; auto audio = SimpleAudioEngine::getInstance(); audio->playEffect("sound/wrong.wav"); } //puzzle - correct location void soundController::puzzleCorrect() { if (UserDefault::getInstance()->getBoolForKey("sound") == false) return; auto audio = SimpleAudioEngine::getInstance(); isKorea = UserDefault::getInstance()->getBoolForKey("kor"); if (isKorea) {//random good or excellent sound RandomHelper::random_int(0,1) ? audio->playEffect("sound/good_k.mp3") : audio->playEffect("sound/excellent_k.mp3"); } else { RandomHelper::random_int(0, 1) ? audio->playEffect("sound/good_e.mp3") : audio->playEffect("sound/excellent_e.mp3"); } } //game opening scene void soundController::gameOpening(int num) { if (UserDefault::getInstance()->getBoolForKey("sound") == false) return; auto audio = SimpleAudioEngine::getInstance(); isKorea = UserDefault::getInstance()->getBoolForKey("kor"); //opening background sound start //udio->playBackgroundMusic("sound/opening_back.wav", true); switch (num) { case 1: if (isKorea) audio->playEffect("sound/op1_k.mp3"); else audio->playEffect("sound/op1_e.mp3"); break; case 2: if (isKorea) audio->playEffect("sound/op2_k.mp3"); else audio->playEffect("sound/op2_e.mp3"); break; case 3: if (isKorea) audio->playEffect("sound/op3_k.mp3"); else audio->playEffect("sound/op3_e.mp3"); break; default: break; } } void soundController::openingEffectSound(char* soundName) { if (soundName == "monster") {//monster sound SimpleAudioEngine::getInstance()->playEffect("sound/op_monster.mp3"); } else if (soundName == "siren") {//siren sound SimpleAudioEngine::getInstance()->playEffect("sound/op_siren.mp3"); } } void soundController::startGameBackgroundSound() { if (UserDefault::getInstance()->getBoolForKey("sound") == false) return; auto audio = SimpleAudioEngine::getInstance(); audio->playBackgroundMusic("sound/game_back.wav", true); } //game ending scene void soundController::gameEnding() { if (UserDefault::getInstance()->getBoolForKey("sound") == false) return; auto audio = SimpleAudioEngine::getInstance(); audio->playBackgroundMusic("sound/ending.mp3", true); } //puzzle opening door void soundController::doorOpen() { if (UserDefault::getInstance()->getBoolForKey("sound") == false) return; auto audio = SimpleAudioEngine::getInstance(); audio->playEffect("sound/door.wav"); } //puzzle naration void soundController::puzzleNaration(int sceneNum) { if (UserDefault::getInstance()->getBoolForKey("sound") == false) return; auto audio = SimpleAudioEngine::getInstance(); isKorea = UserDefault::getInstance()->getBoolForKey("kor"); startGameBackgroundSound(); switch (sceneNum) { case 1: if (isKorea) audio->playEffect("sound/p1_n_k.mp3"); else audio->playEffect("sound/p1_n_e.mp3"); break; case 2: if (isKorea) audio->playEffect("sound/p2_n_k.mp3"); else audio->playEffect("sound/p2_n_e.mp3"); break; case 3: if (isKorea) audio->playEffect("sound/p3_n_k.mp3"); else audio->playEffect("sound/p3_n_e.mp3"); break; case 4: if (isKorea) audio->playEffect("sound/p4_n_k.mp3"); else audio->playEffect("sound/p4_n_e.mp3"); break; case 5: if (isKorea) audio->playEffect("sound/p5_n_k.mp3"); else audio->playEffect("sound/p5_n_e.mp3"); break; case 6: if (isKorea) audio->playEffect("sound/p6_n_k.mp3"); else audio->playEffect("sound/p6_n_e.mp3"); break; default: break; } } //ending pop up void soundController::popUp() { if (UserDefault::getInstance()->getBoolForKey("sound") == false) return; auto audio = SimpleAudioEngine::getInstance(); audio->playEffect("sound/tada.mp3"); } void soundController::soundStop() { SimpleAudioEngine::getInstance()->stopAllEffects(); } void soundController::backgroundSoundStop() { SimpleAudioEngine::getInstance()->stopBackgroundMusic(); } <commit_msg>soundCotroller filename error fix<commit_after>#include "soundController.h" #include "DataSetting.h" using namespace CocosDenshion; //constructor soundController::soundController() { } soundController::~soundController() {} //preload void soundController::initAudio() { auto audio = SimpleAudioEngine::getInstance(); //opening background audio->setBackgroundMusicVolume(0.5); //audio->preloadBackgroundMusic("sound/opening_back.wav"); //opening audio->preloadEffect("sound/op1_k.mp3"); audio->preloadEffect("sound/op2_k.mp3"); audio->preloadEffect("sound/op3_k.mp3"); audio->preloadEffect("sound/op1_e.mp3"); audio->preloadEffect("sound/op2_e.mp3"); audio->preloadEffect("sound/op3_e.mp3"); //game background audio->preloadBackgroundMusic("sound/game_back.wav"); //puzzle sound audio->preloadEffect("sound/wrong.wav"); //wrong //narations //korea narations audio->preloadEffect("sound/p1_n_k.mp3"); //p1Scene audio->preloadEffect("sound/p2_n_k.mp3"); //p2Scene audio->preloadEffect("sound/p3_n_k.mp3"); //p3Scene audio->preloadEffect("sound/p4_n_k.mp3"); //p4Scene audio->preloadEffect("sound/p5_n_k.mp3"); //p5Scene audio->preloadEffect("sound/p6_n_k.mp3"); //p6Scene //english narations audio->preloadEffect("sound/p1_n_e.mp3"); //p1Scene audio->preloadEffect("sound/p2_n_e.mp3"); //p2Scene audio->preloadEffect("sound/p3_n_e.mp3"); //p3Scene audio->preloadEffect("sound/p4_n_e.mp3"); //p4Scene audio->preloadEffect("sound/p5_n_e.mp3"); //p5Scene audio->preloadEffect("sound/p6_n_e.mp3"); //p6Scene //door open audio->preloadEffect("sound/door.wav"); //door open //end effect audio->preloadEffect("sound/tada.mp3"); //each game finish //correct eff audio->preloadEffect("sound/good_k.mp3"); //good audio->preloadEffect("sound/excellent_k.mp3"); //welldone audio->preloadEffect("sound/good_e.mp3"); //good audio->preloadEffect("sound/excellent_e.mp3"); //welldone //splashScene sound audio->preloadEffect("sound/start_k.mp3"); audio->preloadEffect("sound/start_e.mp3"); //finishing audio->preloadBackgroundMusic("sound/ending.mp3"); //ending } void soundController::splashSound() { if (UserDefault::getInstance()->getBoolForKey("sound") == false) return; auto audio = SimpleAudioEngine::getInstance(); isKorea = UserDefault::getInstance()->getBoolForKey("kor"); //stop background sound backgroundSoundStop(); if (isKorea) audio->playEffect("sound/start_k.mp3"); else audio->playEffect("sound/start_e.mp3"); } //puzzle - pick up void soundController::puzzlePickUp() { if (UserDefault::getInstance()->getBoolForKey("sound") == false) return; auto audio = SimpleAudioEngine::getInstance(); //no sound } //puzzle - wrong location void soundController::puzzleWrong() { if (UserDefault::getInstance()->getBoolForKey("sound") == false) return; auto audio = SimpleAudioEngine::getInstance(); audio->playEffect("sound/wrong.wav"); } //puzzle - correct location void soundController::puzzleCorrect() { if (UserDefault::getInstance()->getBoolForKey("sound") == false) return; auto audio = SimpleAudioEngine::getInstance(); isKorea = UserDefault::getInstance()->getBoolForKey("kor"); if (isKorea) {//random good or excellent sound RandomHelper::random_int(0,1) ? audio->playEffect("sound/good_k.mp3") : audio->playEffect("sound/excellent_k.mp3"); } else { RandomHelper::random_int(0, 1) ? audio->playEffect("sound/good_e.mp3") : audio->playEffect("sound/excellent_e.mp3"); } } //game opening scene void soundController::gameOpening(int num) { if (UserDefault::getInstance()->getBoolForKey("sound") == false) return; auto audio = SimpleAudioEngine::getInstance(); isKorea = UserDefault::getInstance()->getBoolForKey("kor"); //opening background sound start //udio->playBackgroundMusic("sound/opening_back.wav", true); switch (num) { case 1: if (isKorea) audio->playEffect("sound/op1_k.mp3"); else audio->playEffect("sound/op1_e.mp3"); break; case 2: if (isKorea) audio->playEffect("sound/op2_k.mp3"); else audio->playEffect("sound/op2_e.mp3"); break; case 3: if (isKorea) audio->playEffect("sound/op3_k.mp3"); else audio->playEffect("sound/op3_e.mp3"); break; default: break; } } void soundController::openingEffectSound(char* soundName) { if (soundName == "monster") {//monster sound SimpleAudioEngine::getInstance()->playEffect("sound/op_monster.mp3"); } else if (soundName == "siren") {//siren sound SimpleAudioEngine::getInstance()->playEffect("sound/op_siren.mp3"); } } void soundController::startGameBackgroundSound() { if (UserDefault::getInstance()->getBoolForKey("sound") == false) return; auto audio = SimpleAudioEngine::getInstance(); audio->playBackgroundMusic("sound/game_back.wav", true); } //game ending scene void soundController::gameEnding() { if (UserDefault::getInstance()->getBoolForKey("sound") == false) return; auto audio = SimpleAudioEngine::getInstance(); audio->playBackgroundMusic("sound/ending.mp3", true); } //puzzle opening door void soundController::doorOpen() { if (UserDefault::getInstance()->getBoolForKey("sound") == false) return; auto audio = SimpleAudioEngine::getInstance(); audio->playEffect("sound/door.wav"); } //puzzle naration void soundController::puzzleNaration(int sceneNum) { if (UserDefault::getInstance()->getBoolForKey("sound") == false) return; auto audio = SimpleAudioEngine::getInstance(); isKorea = UserDefault::getInstance()->getBoolForKey("kor"); startGameBackgroundSound(); switch (sceneNum) { case 1: if (isKorea) audio->playEffect("sound/p1_n_k.mp3"); else audio->playEffect("sound/p1_n_e.mp3"); break; case 2: if (isKorea) audio->playEffect("sound/p2_n_k.mp3"); else audio->playEffect("sound/p2_n_e.mp3"); break; case 3: if (isKorea) audio->playEffect("sound/p3_n_k.mp3"); else audio->playEffect("sound/p3_n_e.mp3"); break; case 4: if (isKorea) audio->playEffect("sound/p4_n_k.mp3"); else audio->playEffect("sound/p4_n_e.mp3"); break; case 5: if (isKorea) audio->playEffect("sound/p5_n_k.mp3"); else audio->playEffect("sound/p5_n_e.mp3"); break; case 6: if (isKorea) audio->playEffect("sound/p6_n_k.mp3"); else audio->playEffect("sound/p6_n_e.mp3"); break; default: break; } } //ending pop up void soundController::popUp() { if (UserDefault::getInstance()->getBoolForKey("sound") == false) return; auto audio = SimpleAudioEngine::getInstance(); audio->playEffect("sound/tada.mp3"); } void soundController::soundStop() { SimpleAudioEngine::getInstance()->stopAllEffects(); } void soundController::backgroundSoundStop() { SimpleAudioEngine::getInstance()->stopBackgroundMusic(); } <|endoftext|>
<commit_before>/* * Copyright (c) 2009, Intel Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. */ #include <locale.h> #include <glib/gi18n.h> #include <clutter/clutter.h> #include <clutter/x11/clutter-x11.h> #include <gdk/gdkx.h> #include <gtk/gtk.h> #include <mx/mx.h> #include <moblin-panel/mpl-panel-clutter.h> #include <moblin-panel/mpl-panel-common.h> #include "moblin-netbook-netpanel.h" #include "chrome-profile-provider.h" #include <config.h> // chrome header #include "app/app_paths.h" #include "app/resource_bundle.h" #include "base/at_exit.h" #include "base/basictypes.h" #include "base/file_path.h" #include "base/file_util.h" #include "base/i18n/icu_util.h" #include "base/message_loop.h" #include "base/path_service.h" #include "base/scoped_vector.h" #include "base/string_util.h" #include "base/command_line.h" #include "chrome/browser/pref_service.h" #include "chrome/common/pref_names.h" #include "chrome/common/chrome_paths.h" #include "chrome/browser/browser_prefs.h" #include "chrome/browser/profile.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/browser_process_impl.h" #include "chrome/browser/chrome_thread.h" #include "chrome/browser/user_data_manager.h" static void _client_set_size_cb (MplPanelClient *client, guint width, guint height, gpointer userdata) { g_debug (G_STRLOC ": %d %d", width, height); clutter_actor_set_size ((ClutterActor *)userdata, width, height); } static gboolean stage_button_press_event (ClutterStage *stage, ClutterEvent *event, MoblinNetbookNetpanel *netpanel) { moblin_netbook_netpanel_button_press (netpanel); return TRUE; } static gboolean stage_delete_event (ClutterStage *stage, ClutterEvent *event, gpointer* userdata) { MessageLoopForUI::current()->Quit(); return TRUE; } static gboolean standalone = FALSE; static GOptionEntry entries[] = { {"standalone", 's', 0, G_OPTION_ARG_NONE, &standalone, "Do not embed into the mutter-moblin panel", NULL} }; #define CHROME_EXE_PATH "/opt/google/chrome/" #define CHROME_BUNDLE_PATH CHROME_EXE_PATH "/chrome.pak" #define CHROME_LOCALE_PATH CHROME_EXE_PATH "/locales" #define CHROMIUM_EXE_PATH "/usr/lib/chromium-browser/" #define CHROMIUM_BUNDLE_PATH CHROMIUM_EXE_PATH "/chrome.pak" #define CHROMIUM_LOCALE_PATH CHROMIUM_EXE_PATH "/locales" int main (int argc, char **argv) { MplPanelClient *client; ClutterActor *stage; MoblinNetbookNetpanel *netpanel; GOptionContext *context; std::string browser_name; GError *error = NULL; // Init chrome environment variables base::AtExitManager at_exit_manager; CommandLine::Init(argc, argv); CommandLine* cmd_line = CommandLine::ForCurrentProcess(); chrome::RegisterPathProvider(); app::RegisterPathProvider(); if (g_file_test (CHROMIUM_BUNDLE_PATH, G_FILE_TEST_EXISTS) && g_file_test (CHROMIUM_LOCALE_PATH, G_FILE_TEST_EXISTS)) { FilePath bundle_path(CHROMIUM_BUNDLE_PATH); FilePath locale_path(CHROMIUM_LOCALE_PATH); ResourceBundle::InitSharedInstance(L"en-US", bundle_path, locale_path); if (g_file_test(CHROMIUM_EXE_PATH "chrome", G_FILE_TEST_EXISTS)) { browser_name = "google-chrome"; } else { browser_name = "chromium"; } } else { g_warning("Chrome browser is not installed\n"); } g_thread_init(NULL); g_type_init(); gtk_init(&argc, &argv); MessageLoop main_message_loop(MessageLoop::TYPE_UI); scoped_ptr<BrowserProcessImpl> browser_process; browser_process.reset(new BrowserProcessImpl(*cmd_line)); ChromeThread main_thread(ChromeThread::UI, MessageLoop::current()); PrefService* local_state = browser_process->local_state(); local_state->RegisterStringPref(prefs::kApplicationLocale, L""); scoped_ptr<UserDataManager> user_data_manager(UserDataManager::Create()); // Initialize the prefs of the local state. browser::RegisterLocalState(local_state); g_browser_process->SetApplicationLocale("en-US"); // Create the child threads. We need to do this since ChromeThread::PostTask // silently deletes a posted task if the target message loop isn't created. browser_process->db_thread(); browser_process->file_thread(); browser_process->process_launcher_thread(); browser_process->io_thread(); // XXX: have to init chrome profile prover after thread creation // Init chrome profile provider ChromeProfileProvider::GetInstance()->Initialize(browser_name.c_str()); setlocale (LC_ALL, ""); bindtextdomain (GETTEXT_PACKAGE, LOCALEDIR); bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8"); textdomain (GETTEXT_PACKAGE); context = g_option_context_new ("- mutter-moblin myzone panel"); g_option_context_add_main_entries (context, entries, GETTEXT_PACKAGE); g_option_context_add_group (context, clutter_get_option_group_without_init ()); g_option_context_add_group (context, gtk_get_option_group (FALSE)); if (!g_option_context_parse (context, &argc, &argv, &error)) { g_critical (G_STRLOC ": Error parsing option: %s", error->message); g_clear_error (&error); } g_option_context_free (context); MPL_PANEL_CLUTTER_INIT_WITH_GTK (&argc, &argv); mx_texture_cache_load_cache (mx_texture_cache_get_default (), MX_CACHE); mx_style_load_from_file (mx_style_get_default (), THEMEDIR "/panel.css", NULL); if (!standalone) { client = mpl_panel_clutter_new (MPL_PANEL_INTERNET, _("internet"), NULL, "internet-button", TRUE); MPL_PANEL_CLUTTER_SETUP_EVENTS_WITH_GTK (client); stage = mpl_panel_clutter_get_stage (MPL_PANEL_CLUTTER (client)); netpanel = MOBLIN_NETBOOK_NETPANEL (moblin_netbook_netpanel_new ()); moblin_netbook_netpanel_set_browser(netpanel, browser_name.c_str()); ClutterActor *content_pane; ClutterActor *base_pane; ClutterActor *label; base_pane = mx_box_layout_new(); clutter_actor_set_name (base_pane, "base-pane"); mx_box_layout_set_orientation (MX_BOX_LAYOUT (base_pane), MX_ORIENTATION_VERTICAL); clutter_container_add_actor (CLUTTER_CONTAINER (stage), base_pane); label = mx_label_new_with_text (_("Internet")); clutter_actor_set_name (label, "panel-label"); clutter_container_add_actor (CLUTTER_CONTAINER (base_pane), label); content_pane = mx_box_layout_new (); clutter_actor_set_name (content_pane, "pane"); mx_box_layout_set_orientation (MX_BOX_LAYOUT (content_pane), MX_ORIENTATION_VERTICAL); clutter_container_add_actor (CLUTTER_CONTAINER (base_pane), content_pane); clutter_container_child_set (CLUTTER_CONTAINER (base_pane), content_pane, "expand", TRUE, "x-fill", TRUE, "y-fill", TRUE, NULL); clutter_container_add_actor (CLUTTER_CONTAINER (content_pane), CLUTTER_ACTOR (netpanel)); clutter_container_child_set (CLUTTER_CONTAINER (content_pane), CLUTTER_ACTOR (netpanel), "expand", TRUE, "x-fill", TRUE, "y-fill", TRUE, NULL); moblin_netbook_netpanel_set_panel_client (netpanel, client); g_signal_connect (client, "set-size", (GCallback)_client_set_size_cb, base_pane); } else { Window xwin; ClutterActor *content_pane; ClutterActor *base_pane; ClutterActor *label; stage = clutter_stage_get_default (); clutter_actor_realize (stage); xwin = clutter_x11_get_stage_window (CLUTTER_STAGE (stage)); MPL_PANEL_CLUTTER_SETUP_EVENTS_WITH_GTK_FOR_XID (xwin); netpanel = MOBLIN_NETBOOK_NETPANEL (moblin_netbook_netpanel_new ()); moblin_netbook_netpanel_set_browser(netpanel, browser_name.c_str()); base_pane = mx_box_layout_new(); clutter_actor_set_name (base_pane, "base-pane"); mx_box_layout_set_orientation (MX_BOX_LAYOUT (base_pane), MX_ORIENTATION_VERTICAL); clutter_container_add_actor (CLUTTER_CONTAINER (stage), base_pane); label = mx_label_new_with_text (_("Internet")); clutter_actor_set_name (label, "panel-label"); clutter_container_add_actor (CLUTTER_CONTAINER (base_pane), label); content_pane = mx_box_layout_new (); clutter_actor_set_name (content_pane, "pane"); mx_box_layout_set_orientation (MX_BOX_LAYOUT (content_pane), MX_ORIENTATION_VERTICAL); clutter_container_add_actor (CLUTTER_CONTAINER (base_pane), content_pane); clutter_container_child_set (CLUTTER_CONTAINER (base_pane), content_pane, "expand", TRUE, "x-fill", TRUE, "y-fill", TRUE, NULL); clutter_container_add_actor (CLUTTER_CONTAINER (content_pane), CLUTTER_ACTOR (netpanel)); clutter_container_child_set (CLUTTER_CONTAINER (content_pane), CLUTTER_ACTOR (netpanel), "expand", TRUE, "x-fill", TRUE, "y-fill", TRUE, NULL); clutter_actor_set_size (stage, 1016, 500); clutter_actor_set_size (base_pane, 1016, 500); clutter_actor_show (CLUTTER_ACTOR (netpanel)); clutter_actor_show_all (stage); g_signal_connect (stage, "delete-event", (GCallback)stage_delete_event, NULL); } g_signal_connect (stage, "button-press-event", (GCallback)stage_button_press_event, netpanel); // run chromium's message loop MessageLoopForUI::current()->Run(NULL); return 0; } <commit_msg>fix a bug in chrome/chromium dual support patch<commit_after>/* * Copyright (c) 2009, Intel Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. */ #include <locale.h> #include <glib/gi18n.h> #include <clutter/clutter.h> #include <clutter/x11/clutter-x11.h> #include <gdk/gdkx.h> #include <gtk/gtk.h> #include <mx/mx.h> #include <moblin-panel/mpl-panel-clutter.h> #include <moblin-panel/mpl-panel-common.h> #include "moblin-netbook-netpanel.h" #include "chrome-profile-provider.h" #include <config.h> // chrome header #include "app/app_paths.h" #include "app/resource_bundle.h" #include "base/at_exit.h" #include "base/basictypes.h" #include "base/file_path.h" #include "base/file_util.h" #include "base/i18n/icu_util.h" #include "base/message_loop.h" #include "base/path_service.h" #include "base/scoped_vector.h" #include "base/string_util.h" #include "base/command_line.h" #include "chrome/browser/pref_service.h" #include "chrome/common/pref_names.h" #include "chrome/common/chrome_paths.h" #include "chrome/browser/browser_prefs.h" #include "chrome/browser/profile.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/browser_process_impl.h" #include "chrome/browser/chrome_thread.h" #include "chrome/browser/user_data_manager.h" static void _client_set_size_cb (MplPanelClient *client, guint width, guint height, gpointer userdata) { g_debug (G_STRLOC ": %d %d", width, height); clutter_actor_set_size ((ClutterActor *)userdata, width, height); } static gboolean stage_button_press_event (ClutterStage *stage, ClutterEvent *event, MoblinNetbookNetpanel *netpanel) { moblin_netbook_netpanel_button_press (netpanel); return TRUE; } static gboolean stage_delete_event (ClutterStage *stage, ClutterEvent *event, gpointer* userdata) { MessageLoopForUI::current()->Quit(); return TRUE; } static gboolean standalone = FALSE; static GOptionEntry entries[] = { {"standalone", 's', 0, G_OPTION_ARG_NONE, &standalone, "Do not embed into the mutter-moblin panel", NULL} }; #define CHROME_EXE_PATH "/opt/google/chrome/" #define CHROME_BUNDLE_PATH CHROME_EXE_PATH "/chrome.pak" #define CHROME_LOCALE_PATH CHROME_EXE_PATH "/locales" #define CHROMIUM_EXE_PATH "/usr/lib/chromium-browser/" #define CHROMIUM_BUNDLE_PATH CHROMIUM_EXE_PATH "/chrome.pak" #define CHROMIUM_LOCALE_PATH CHROMIUM_EXE_PATH "/locales" int main (int argc, char **argv) { MplPanelClient *client; ClutterActor *stage; MoblinNetbookNetpanel *netpanel; GOptionContext *context; std::string browser_name; GError *error = NULL; // Init chrome environment variables base::AtExitManager at_exit_manager; CommandLine::Init(argc, argv); CommandLine* cmd_line = CommandLine::ForCurrentProcess(); chrome::RegisterPathProvider(); app::RegisterPathProvider(); if (g_file_test (CHROMIUM_BUNDLE_PATH, G_FILE_TEST_EXISTS) && g_file_test (CHROMIUM_LOCALE_PATH, G_FILE_TEST_EXISTS)) { FilePath bundle_path(CHROMIUM_BUNDLE_PATH); FilePath locale_path(CHROMIUM_LOCALE_PATH); ResourceBundle::InitSharedInstance(L"en-US", bundle_path, locale_path); if (g_file_test(CHROME_EXE_PATH "chrome", G_FILE_TEST_EXISTS) == TRUE) { browser_name = "google-chrome"; } else { browser_name = "chromium"; } } else { g_warning("Chrome browser is not installed\n"); } g_thread_init(NULL); g_type_init(); gtk_init(&argc, &argv); MessageLoop main_message_loop(MessageLoop::TYPE_UI); scoped_ptr<BrowserProcessImpl> browser_process; browser_process.reset(new BrowserProcessImpl(*cmd_line)); ChromeThread main_thread(ChromeThread::UI, MessageLoop::current()); PrefService* local_state = browser_process->local_state(); local_state->RegisterStringPref(prefs::kApplicationLocale, L""); scoped_ptr<UserDataManager> user_data_manager(UserDataManager::Create()); // Initialize the prefs of the local state. browser::RegisterLocalState(local_state); g_browser_process->SetApplicationLocale("en-US"); // Create the child threads. We need to do this since ChromeThread::PostTask // silently deletes a posted task if the target message loop isn't created. browser_process->db_thread(); browser_process->file_thread(); browser_process->process_launcher_thread(); browser_process->io_thread(); // XXX: have to init chrome profile prover after thread creation // Init chrome profile provider ChromeProfileProvider::GetInstance()->Initialize(browser_name.c_str()); setlocale (LC_ALL, ""); bindtextdomain (GETTEXT_PACKAGE, LOCALEDIR); bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8"); textdomain (GETTEXT_PACKAGE); context = g_option_context_new ("- mutter-moblin myzone panel"); g_option_context_add_main_entries (context, entries, GETTEXT_PACKAGE); g_option_context_add_group (context, clutter_get_option_group_without_init ()); g_option_context_add_group (context, gtk_get_option_group (FALSE)); if (!g_option_context_parse (context, &argc, &argv, &error)) { g_critical (G_STRLOC ": Error parsing option: %s", error->message); g_clear_error (&error); } g_option_context_free (context); MPL_PANEL_CLUTTER_INIT_WITH_GTK (&argc, &argv); mx_texture_cache_load_cache (mx_texture_cache_get_default (), MX_CACHE); mx_style_load_from_file (mx_style_get_default (), THEMEDIR "/panel.css", NULL); if (!standalone) { client = mpl_panel_clutter_new (MPL_PANEL_INTERNET, _("internet"), NULL, "internet-button", TRUE); MPL_PANEL_CLUTTER_SETUP_EVENTS_WITH_GTK (client); stage = mpl_panel_clutter_get_stage (MPL_PANEL_CLUTTER (client)); netpanel = MOBLIN_NETBOOK_NETPANEL (moblin_netbook_netpanel_new ()); moblin_netbook_netpanel_set_browser(netpanel, browser_name.c_str()); ClutterActor *content_pane; ClutterActor *base_pane; ClutterActor *label; base_pane = mx_box_layout_new(); clutter_actor_set_name (base_pane, "base-pane"); mx_box_layout_set_orientation (MX_BOX_LAYOUT (base_pane), MX_ORIENTATION_VERTICAL); clutter_container_add_actor (CLUTTER_CONTAINER (stage), base_pane); label = mx_label_new_with_text (_("Internet")); clutter_actor_set_name (label, "panel-label"); clutter_container_add_actor (CLUTTER_CONTAINER (base_pane), label); content_pane = mx_box_layout_new (); clutter_actor_set_name (content_pane, "pane"); mx_box_layout_set_orientation (MX_BOX_LAYOUT (content_pane), MX_ORIENTATION_VERTICAL); clutter_container_add_actor (CLUTTER_CONTAINER (base_pane), content_pane); clutter_container_child_set (CLUTTER_CONTAINER (base_pane), content_pane, "expand", TRUE, "x-fill", TRUE, "y-fill", TRUE, NULL); clutter_container_add_actor (CLUTTER_CONTAINER (content_pane), CLUTTER_ACTOR (netpanel)); clutter_container_child_set (CLUTTER_CONTAINER (content_pane), CLUTTER_ACTOR (netpanel), "expand", TRUE, "x-fill", TRUE, "y-fill", TRUE, NULL); moblin_netbook_netpanel_set_panel_client (netpanel, client); g_signal_connect (client, "set-size", (GCallback)_client_set_size_cb, base_pane); } else { Window xwin; ClutterActor *content_pane; ClutterActor *base_pane; ClutterActor *label; stage = clutter_stage_get_default (); clutter_actor_realize (stage); xwin = clutter_x11_get_stage_window (CLUTTER_STAGE (stage)); MPL_PANEL_CLUTTER_SETUP_EVENTS_WITH_GTK_FOR_XID (xwin); netpanel = MOBLIN_NETBOOK_NETPANEL (moblin_netbook_netpanel_new ()); moblin_netbook_netpanel_set_browser(netpanel, browser_name.c_str()); base_pane = mx_box_layout_new(); clutter_actor_set_name (base_pane, "base-pane"); mx_box_layout_set_orientation (MX_BOX_LAYOUT (base_pane), MX_ORIENTATION_VERTICAL); clutter_container_add_actor (CLUTTER_CONTAINER (stage), base_pane); label = mx_label_new_with_text (_("Internet")); clutter_actor_set_name (label, "panel-label"); clutter_container_add_actor (CLUTTER_CONTAINER (base_pane), label); content_pane = mx_box_layout_new (); clutter_actor_set_name (content_pane, "pane"); mx_box_layout_set_orientation (MX_BOX_LAYOUT (content_pane), MX_ORIENTATION_VERTICAL); clutter_container_add_actor (CLUTTER_CONTAINER (base_pane), content_pane); clutter_container_child_set (CLUTTER_CONTAINER (base_pane), content_pane, "expand", TRUE, "x-fill", TRUE, "y-fill", TRUE, NULL); clutter_container_add_actor (CLUTTER_CONTAINER (content_pane), CLUTTER_ACTOR (netpanel)); clutter_container_child_set (CLUTTER_CONTAINER (content_pane), CLUTTER_ACTOR (netpanel), "expand", TRUE, "x-fill", TRUE, "y-fill", TRUE, NULL); clutter_actor_set_size (stage, 1016, 500); clutter_actor_set_size (base_pane, 1016, 500); clutter_actor_show (CLUTTER_ACTOR (netpanel)); clutter_actor_show_all (stage); g_signal_connect (stage, "delete-event", (GCallback)stage_delete_event, NULL); } g_signal_connect (stage, "button-press-event", (GCallback)stage_button_press_event, netpanel); // run chromium's message loop MessageLoopForUI::current()->Run(NULL); return 0; } <|endoftext|>
<commit_before>/* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm.h" #include "SkCanvas.h" #include "SkPath.h" #include "SkGradientShader.h" #include "SkTypeface.h" static SkShader* make_heatGradient(const SkPoint pts[2]) { const SkColor colors[] = { SK_ColorBLACK, SK_ColorBLUE, SK_ColorCYAN, SK_ColorGREEN, SK_ColorYELLOW, SK_ColorRED, SK_ColorWHITE }; const SkColor bw[] = { SK_ColorBLACK, SK_ColorWHITE }; return SkGradientShader::CreateLinear(pts, bw, NULL, SK_ARRAY_COUNT(bw), SkShader::kClamp_TileMode); } static bool setFont(SkPaint* paint, const char name[]) { SkTypeface* tf = SkTypeface::CreateFromName(name, SkTypeface::kNormal); if (tf) { paint->setTypeface(tf)->unref(); return true; } return false; } #ifdef SK_BUILD_FOR_MAC #import <ApplicationServices/ApplicationServices.h> #define BITMAP_INFO_RGB (kCGImageAlphaNoneSkipFirst | kCGBitmapByteOrder32Host) static CGContextRef makeCG(const SkBitmap& bm) { if (SkBitmap::kARGB_8888_Config != bm.config() || NULL == bm.getPixels()) { return NULL; } CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB(); CGContextRef cg = CGBitmapContextCreate(bm.getPixels(), bm.width(), bm.height(), 8, bm.rowBytes(), space, BITMAP_INFO_RGB); CFRelease(space); CGContextSetAllowsFontSubpixelQuantization(cg, false); CGContextSetShouldSubpixelQuantizeFonts(cg, false); return cg; } extern CTFontRef SkTypeface_GetCTFontRef(const SkTypeface* face); static CGFontRef typefaceToCGFont(const SkTypeface* face) { if (NULL == face) { return 0; } CTFontRef ct = SkTypeface_GetCTFontRef(face); return CTFontCopyGraphicsFont(ct, NULL); } static void cgSetPaintForText(CGContextRef cg, const SkPaint& paint) { SkColor c = paint.getColor(); CGFloat rgba[] = { SkColorGetB(c) / 255.0, SkColorGetG(c) / 255.0, SkColorGetR(c) / 255.0, SkColorGetA(c) / 255.0, }; CGContextSetRGBFillColor(cg, rgba[0], rgba[1], rgba[2], rgba[3]); CGContextSetTextDrawingMode(cg, kCGTextFill); CGContextSetFont(cg, typefaceToCGFont(paint.getTypeface())); CGContextSetFontSize(cg, SkScalarToFloat(paint.getTextSize())); CGContextSetAllowsFontSubpixelPositioning(cg, paint.isSubpixelText()); CGContextSetShouldSubpixelPositionFonts(cg, paint.isSubpixelText()); CGContextSetShouldAntialias(cg, paint.isAntiAlias()); CGContextSetShouldSmoothFonts(cg, paint.isLCDRenderText()); } static void cgDrawText(CGContextRef cg, const void* text, size_t len, float x, float y, const SkPaint& paint) { if (cg) { cgSetPaintForText(cg, paint); uint16_t glyphs[200]; int count = paint.textToGlyphs(text, len, glyphs); CGContextShowGlyphsAtPoint(cg, x, y, glyphs, count); } } #endif namespace skiagm { /** Test a set of clipping problems discovered while writing blitAntiRect, and test all the code paths through the clipping blitters. Each region should show as a blue center surrounded by a 2px green border, with no red. */ #define HEIGHT 480 class GammaTextGM : public GM { public: GammaTextGM() { } protected: virtual SkString onShortName() { return SkString("gammatext"); } virtual SkISize onISize() { return make_isize(1024, HEIGHT); } static void drawGrad(SkCanvas* canvas) { SkPoint pts[] = { { 0, 0 }, { 0, SkIntToScalar(HEIGHT) } }; #if 0 const SkColor colors[] = { SK_ColorBLACK, SK_ColorWHITE }; SkShader* s = SkGradientShader::CreateLinear(pts, colors, NULL, 2, SkShader::kClamp_TileMode); #else SkShader* s = make_heatGradient(pts); #endif canvas->clear(SK_ColorRED); SkPaint paint; paint.setShader(s)->unref(); SkRect r = { 0, 0, SkIntToScalar(1024), SkIntToScalar(HEIGHT) }; canvas->drawRect(r, paint); } virtual void onDraw(SkCanvas* canvas) { #ifdef SK_BUILD_FOR_MAC CGContextRef cg = makeCG(canvas->getDevice()->accessBitmap(false)); #endif drawGrad(canvas); const SkColor fg[] = { 0xFFFFFFFF, 0xFFFFFF00, 0xFFFF00FF, 0xFF00FFFF, 0xFFFF0000, 0xFF00FF00, 0xFF0000FF, 0xFF000000, }; const char* text = "Hamburgefons"; size_t len = strlen(text); SkPaint paint; setFont(&paint, "Times"); paint.setTextSize(SkIntToScalar(16)); paint.setAntiAlias(true); paint.setLCDRenderText(true); SkScalar x = SkIntToScalar(10); for (size_t i = 0; i < SK_ARRAY_COUNT(fg); ++i) { paint.setColor(fg[i]); SkScalar y = SkIntToScalar(40); SkScalar stopy = SkIntToScalar(HEIGHT); while (y < stopy) { #if 1 canvas->drawText(text, len, x, y, paint); #else cgDrawText(cg, text, len, x, SkIntToScalar(HEIGHT) - y, paint); #endif y += paint.getTextSize() * 2; } x += SkIntToScalar(1024) / SK_ARRAY_COUNT(fg); } } private: typedef GM INHERITED; }; ////////////////////////////////////////////////////////////////////////////// static GM* MyFactory(void*) { return new GammaTextGM; } static GMRegistry reg(MyFactory); } <commit_msg>Fix some float/scalar/int confusion.<commit_after>/* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm.h" #include "SkCanvas.h" #include "SkPath.h" #include "SkGradientShader.h" #include "SkTypeface.h" static SkShader* make_heatGradient(const SkPoint pts[2]) { const SkColor colors[] = { SK_ColorBLACK, SK_ColorBLUE, SK_ColorCYAN, SK_ColorGREEN, SK_ColorYELLOW, SK_ColorRED, SK_ColorWHITE }; const SkColor bw[] = { SK_ColorBLACK, SK_ColorWHITE }; return SkGradientShader::CreateLinear(pts, bw, NULL, SK_ARRAY_COUNT(bw), SkShader::kClamp_TileMode); } static bool setFont(SkPaint* paint, const char name[]) { SkTypeface* tf = SkTypeface::CreateFromName(name, SkTypeface::kNormal); if (tf) { paint->setTypeface(tf)->unref(); return true; } return false; } #ifdef SK_BUILD_FOR_MAC #import <ApplicationServices/ApplicationServices.h> #define BITMAP_INFO_RGB (kCGImageAlphaNoneSkipFirst | kCGBitmapByteOrder32Host) static CGContextRef makeCG(const SkBitmap& bm) { if (SkBitmap::kARGB_8888_Config != bm.config() || NULL == bm.getPixels()) { return NULL; } CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB(); CGContextRef cg = CGBitmapContextCreate(bm.getPixels(), bm.width(), bm.height(), 8, bm.rowBytes(), space, BITMAP_INFO_RGB); CFRelease(space); CGContextSetAllowsFontSubpixelQuantization(cg, false); CGContextSetShouldSubpixelQuantizeFonts(cg, false); return cg; } extern CTFontRef SkTypeface_GetCTFontRef(const SkTypeface* face); static CGFontRef typefaceToCGFont(const SkTypeface* face) { if (NULL == face) { return 0; } CTFontRef ct = SkTypeface_GetCTFontRef(face); return CTFontCopyGraphicsFont(ct, NULL); } static void cgSetPaintForText(CGContextRef cg, const SkPaint& paint) { SkColor c = paint.getColor(); CGFloat rgba[] = { SkColorGetB(c) / 255.0, SkColorGetG(c) / 255.0, SkColorGetR(c) / 255.0, SkColorGetA(c) / 255.0, }; CGContextSetRGBFillColor(cg, rgba[0], rgba[1], rgba[2], rgba[3]); CGContextSetTextDrawingMode(cg, kCGTextFill); CGContextSetFont(cg, typefaceToCGFont(paint.getTypeface())); CGContextSetFontSize(cg, SkScalarToFloat(paint.getTextSize())); CGContextSetAllowsFontSubpixelPositioning(cg, paint.isSubpixelText()); CGContextSetShouldSubpixelPositionFonts(cg, paint.isSubpixelText()); CGContextSetShouldAntialias(cg, paint.isAntiAlias()); CGContextSetShouldSmoothFonts(cg, paint.isLCDRenderText()); } static void cgDrawText(CGContextRef cg, const void* text, size_t len, float x, float y, const SkPaint& paint) { if (cg) { cgSetPaintForText(cg, paint); uint16_t glyphs[200]; int count = paint.textToGlyphs(text, len, glyphs); CGContextShowGlyphsAtPoint(cg, x, y, glyphs, count); } } #endif namespace skiagm { /** Test a set of clipping problems discovered while writing blitAntiRect, and test all the code paths through the clipping blitters. Each region should show as a blue center surrounded by a 2px green border, with no red. */ #define HEIGHT 480 class GammaTextGM : public GM { public: GammaTextGM() { } protected: virtual SkString onShortName() { return SkString("gammatext"); } virtual SkISize onISize() { return make_isize(1024, HEIGHT); } static void drawGrad(SkCanvas* canvas) { SkPoint pts[] = { { 0, 0 }, { 0, SkIntToScalar(HEIGHT) } }; #if 0 const SkColor colors[] = { SK_ColorBLACK, SK_ColorWHITE }; SkShader* s = SkGradientShader::CreateLinear(pts, colors, NULL, 2, SkShader::kClamp_TileMode); #else SkShader* s = make_heatGradient(pts); #endif canvas->clear(SK_ColorRED); SkPaint paint; paint.setShader(s)->unref(); SkRect r = { 0, 0, SkIntToScalar(1024), SkIntToScalar(HEIGHT) }; canvas->drawRect(r, paint); } virtual void onDraw(SkCanvas* canvas) { #ifdef SK_BUILD_FOR_MAC CGContextRef cg = makeCG(canvas->getDevice()->accessBitmap(false)); #endif drawGrad(canvas); const SkColor fg[] = { 0xFFFFFFFF, 0xFFFFFF00, 0xFFFF00FF, 0xFF00FFFF, 0xFFFF0000, 0xFF00FF00, 0xFF0000FF, 0xFF000000, }; const char* text = "Hamburgefons"; size_t len = strlen(text); SkPaint paint; setFont(&paint, "Times"); paint.setTextSize(SkIntToScalar(16)); paint.setAntiAlias(true); paint.setLCDRenderText(true); SkScalar x = SkIntToScalar(10); for (size_t i = 0; i < SK_ARRAY_COUNT(fg); ++i) { paint.setColor(fg[i]); SkScalar y = SkIntToScalar(40); SkScalar stopy = SkIntToScalar(HEIGHT); while (y < stopy) { #if 1 canvas->drawText(text, len, x, y, paint); #else cgDrawText(cg, text, len, SkScalarToFloat(x), static_cast<float>(HEIGHT) - SkScalarToFloat(y), paint); #endif y += paint.getTextSize() * 2; } x += SkIntToScalar(1024) / SK_ARRAY_COUNT(fg); } } private: typedef GM INHERITED; }; ////////////////////////////////////////////////////////////////////////////// static GM* MyFactory(void*) { return new GammaTextGM; } static GMRegistry reg(MyFactory); } <|endoftext|>
<commit_before> /* * Copyright 2012 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm.h" #include "SkColorPriv.h" #include "SkGeometry.h" #include "SkShader.h" static void tesselate(const SkPath& src, SkPath* dst) { SkPath::Iter iter(src, true); SkPoint pts[4]; SkPath::Verb verb; while ((verb = iter.next(pts)) != SkPath::kDone_Verb) { switch (verb) { case SkPath::kMove_Verb: dst->moveTo(pts[0]); break; case SkPath::kLine_Verb: dst->lineTo(pts[1]); break; case SkPath::kQuad_Verb: { SkPoint p; for (int i = 1; i <= 8; ++i) { SkEvalQuadAt(pts, i / 8.0f, &p, NULL); dst->lineTo(p); } } break; case SkPath::kCubic_Verb: { SkPoint p; for (int i = 1; i <= 8; ++i) { SkEvalCubicAt(pts, i / 8.0f, &p, NULL, NULL); dst->lineTo(p); } } break; } } } static void setFade(SkPaint* paint, bool showGL) { paint->setAlpha(showGL ? 0x66 : 0xFF); } static void setGLFrame(SkPaint* paint) { paint->setColor(0xFFFF0000); paint->setStyle(SkPaint::kStroke_Style); paint->setAntiAlias(true); paint->setStrokeWidth(1.1f); } static void show_mesh(SkCanvas* canvas, const SkRect& r) { SkPaint paint; setGLFrame(&paint); canvas->drawRect(r, paint); canvas->drawLine(r.fLeft, r.fTop, r.fRight, r.fBottom, paint); } static void drawLine(SkCanvas* canvas, const SkPoint& p0, const SkPoint& p1, const SkPaint& paint) { canvas->drawLine(p0.fX, p0.fY, p1.fX, p1.fY, paint); } static void show_mesh(SkCanvas* canvas, const SkPoint pts[], const uint16_t indices[], int count) { SkPaint paint; setGLFrame(&paint); for (int i = 0; i < count - 2; ++i) { drawLine(canvas, pts[indices[i]], pts[indices[i+1]], paint); drawLine(canvas, pts[indices[i+1]], pts[indices[i+2]], paint); drawLine(canvas, pts[indices[i+2]], pts[indices[i]], paint); } } static void show_glframe(SkCanvas* canvas, const SkPath& path) { SkPaint paint; setGLFrame(&paint); canvas->drawPath(path, paint); } static void show_mesh_between(SkCanvas* canvas, const SkPath& p0, const SkPath& p1) { SkPath d0, d1; tesselate(p0, &d0); tesselate(p1, &d1); SkPoint pts0[256*2], pts1[256]; int count = d0.getPoints(pts0, SK_ARRAY_COUNT(pts0)); int count1 = d1.getPoints(pts1, SK_ARRAY_COUNT(pts1)); SkASSERT(count == count1); memcpy(&pts0[count], pts1, count * sizeof(SkPoint)); uint16_t indices[256*6]; uint16_t* ndx = indices; for (int i = 0; i < count; ++i) { *ndx++ = i; *ndx++ = i + count; } *ndx++ = 0; show_mesh(canvas, pts0, indices, ndx - indices); } static void show_fan(SkCanvas* canvas, const SkPath& path, SkScalar cx, SkScalar cy) { SkPaint paint; setGLFrame(&paint); canvas->drawPath(path, paint); SkPoint pts[256]; int count = path.getPoints(pts, SK_ARRAY_COUNT(pts)); for (int i = 0; i < count; ++i) { canvas->drawLine(pts[i].fX, pts[i].fY, cx, cy, paint); } } /////////////////////////////////////////////////////////////////////////////// typedef void (*DrawProc)(SkCanvas* canvas, bool showGL, int flags); static void draw_line(SkCanvas* canvas, bool showGL, int flags) { SkPaint paint; paint.setAntiAlias(true); canvas->drawLine(50, 50, 400, 100, paint); canvas->rotate(40); setFade(&paint, showGL); paint.setStrokeWidth(40); canvas->drawLine(100, 50, 450, 50, paint); if (showGL) { show_mesh(canvas, SkRect::MakeLTRB(100, 50-20, 450, 50+20)); } } static void draw_rect(SkCanvas* canvas, bool showGL, int flags) { SkPaint paint; paint.setAntiAlias(true); SkRect r = SkRect::MakeLTRB(50, 50, 250, 350); setFade(&paint, showGL); canvas->drawRect(r, paint); if (showGL) { show_mesh(canvas, r); } canvas->translate(320, 0); paint.setStyle(SkPaint::kStroke_Style); paint.setStrokeWidth(25); canvas->drawRect(r, paint); if (showGL) { SkScalar rad = paint.getStrokeWidth() / 2; SkPoint pts[8]; r.outset(rad, rad); r.toQuad(&pts[0]); r.inset(rad*2, rad*2); r.toQuad(&pts[4]); const uint16_t indices[] = { 0, 4, 1, 5, 2, 6, 3, 7, 0, 4 }; show_mesh(canvas, pts, indices, SK_ARRAY_COUNT(indices)); } } static void draw_oval(SkCanvas* canvas, bool showGL, int flags) { SkPaint paint; paint.setAntiAlias(true); SkRect r = SkRect::MakeLTRB(50, 50, 250, 350); setFade(&paint, showGL); canvas->drawOval(r, paint); if (showGL) { switch (flags) { case 0: { SkPath path; path.addOval(r); show_glframe(canvas, path); } break; case 1: { SkPath src, dst; src.addOval(r); tesselate(src, &dst); show_fan(canvas, dst, r.centerX(), r.centerY()); } break; } } canvas->translate(320, 0); paint.setStyle(SkPaint::kStroke_Style); paint.setStrokeWidth(25); canvas->drawOval(r, paint); if (showGL) { switch (flags) { case 0: { SkPath path; SkScalar rad = paint.getStrokeWidth() / 2; r.outset(rad, rad); path.addOval(r); r.inset(rad*2, rad*2); path.addOval(r); show_glframe(canvas, path); } break; case 1: { SkPath path0, path1; SkScalar rad = paint.getStrokeWidth() / 2; r.outset(rad, rad); path0.addOval(r); r.inset(rad*2, rad*2); path1.addOval(r); show_mesh_between(canvas, path0, path1); } break; } } } static void draw_image(SkCanvas* canvas, bool showGL, int flags) { SkPaint paint; paint.setAntiAlias(true); canvas->drawLine(10, 10, 400, 30, paint); paint.setStrokeWidth(10); canvas->drawLine(50, 50, 400, 400, paint); } static void draw_text(SkCanvas* canvas, bool showGL, int flags) { SkPaint paint; paint.setAntiAlias(true); canvas->drawLine(10, 10, 400, 30, paint); paint.setStrokeWidth(10); canvas->drawLine(50, 50, 400, 400, paint); } static const struct { DrawProc fProc; const char* fName; } gRec[] = { { draw_line, "Lines" }, { draw_rect, "Rects" }, { draw_oval, "Ovals" }, { draw_image, "Images" }, { draw_text, "Text" }, }; class TalkGM : public skiagm::GM { DrawProc fProc; SkString fName; bool fShowGL; int fFlags; public: TalkGM(int index, bool showGL, int flags = 0) { fProc = gRec[index].fProc; fName.set(gRec[index].fName); if (showGL) { fName.append("-gl"); } fShowGL = showGL; fFlags = flags; } protected: virtual SkString onShortName() { return fName; } virtual SkISize onISize() { return SkISize::Make(640, 480); } virtual void onDraw(SkCanvas* canvas) { SkRect dst = SkRect::MakeWH(canvas->getDevice()->width(), canvas->getDevice()->height()); SkRect src = SkRect::MakeWH(640, 480); SkMatrix matrix; matrix.setRectToRect(src, dst, SkMatrix::kCenter_ScaleToFit); canvas->concat(matrix); fProc(canvas, fShowGL, fFlags); } private: typedef skiagm::GM INHERITED; }; ////////////////////////////////////////////////////////////////////////////// #define GM_CONCAT(X,Y) GM_CONCAT_IMPL(X,Y) #define GM_CONCAT_IMPL(X,Y) X##Y #define FACTORY_NAME GM_CONCAT(Factory, __LINE__) #define REGISTRY_NAME GM_CONCAT(gReg, __LINE__) #define ADD_GM(Class, args) \ static skiagm::GM* FACTORY_NAME(void*) { return new Class args; } \ static skiagm::GMRegistry REGISTRY_NAME(FACTORY_NAME); ADD_GM(TalkGM, (0, false)) ADD_GM(TalkGM, (0, true)) ADD_GM(TalkGM, (1, false)) ADD_GM(TalkGM, (1, true)) ADD_GM(TalkGM, (2, false)) ADD_GM(TalkGM, (2, true)) ADD_GM(TalkGM, (2, true, 1)) ADD_GM(TalkGM, (3, false)) ADD_GM(TalkGM, (3, true)) ADD_GM(TalkGM, (4, false)) ADD_GM(TalkGM, (4, true)) //static GM* MyFactory(void*) { return new TalkGM(0, false); } //static GMRegistry reg(MyFactory); <commit_msg>update<commit_after> /* * Copyright 2012 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm.h" #include "SkColorPriv.h" #include "SkGeometry.h" #include "SkShader.h" static void tesselate(const SkPath& src, SkPath* dst) { SkPath::Iter iter(src, true); SkPoint pts[4]; SkPath::Verb verb; while ((verb = iter.next(pts)) != SkPath::kDone_Verb) { switch (verb) { case SkPath::kMove_Verb: dst->moveTo(pts[0]); break; case SkPath::kLine_Verb: dst->lineTo(pts[1]); break; case SkPath::kQuad_Verb: { SkPoint p; for (int i = 1; i <= 8; ++i) { SkEvalQuadAt(pts, i / 8.0f, &p, NULL); dst->lineTo(p); } } break; case SkPath::kCubic_Verb: { SkPoint p; for (int i = 1; i <= 8; ++i) { SkEvalCubicAt(pts, i / 8.0f, &p, NULL, NULL); dst->lineTo(p); } } break; } } } static void setFade(SkPaint* paint, bool showGL) { paint->setAlpha(showGL ? 0x66 : 0xFF); } static void setGLFrame(SkPaint* paint) { paint->setColor(0xFFFF0000); paint->setStyle(SkPaint::kStroke_Style); paint->setAntiAlias(true); paint->setStrokeWidth(1.1f); } static void show_mesh(SkCanvas* canvas, const SkRect& r) { SkPaint paint; setGLFrame(&paint); canvas->drawRect(r, paint); canvas->drawLine(r.fLeft, r.fTop, r.fRight, r.fBottom, paint); } static void drawLine(SkCanvas* canvas, const SkPoint& p0, const SkPoint& p1, const SkPaint& paint) { canvas->drawLine(p0.fX, p0.fY, p1.fX, p1.fY, paint); } static void show_mesh(SkCanvas* canvas, const SkPoint pts[], const uint16_t indices[], int count) { SkPaint paint; setGLFrame(&paint); for (int i = 0; i < count - 2; ++i) { drawLine(canvas, pts[indices[i]], pts[indices[i+1]], paint); drawLine(canvas, pts[indices[i+1]], pts[indices[i+2]], paint); drawLine(canvas, pts[indices[i+2]], pts[indices[i]], paint); } } static void show_glframe(SkCanvas* canvas, const SkPath& path) { SkPaint paint; setGLFrame(&paint); canvas->drawPath(path, paint); } static void show_mesh_between(SkCanvas* canvas, const SkPath& p0, const SkPath& p1) { SkPath d0, d1; tesselate(p0, &d0); tesselate(p1, &d1); SkPoint pts0[256*2], pts1[256]; int count = d0.getPoints(pts0, SK_ARRAY_COUNT(pts0)); int count1 = d1.getPoints(pts1, SK_ARRAY_COUNT(pts1)); SkASSERT(count == count1); memcpy(&pts0[count], pts1, count * sizeof(SkPoint)); uint16_t indices[256*6]; uint16_t* ndx = indices; for (int i = 0; i < count; ++i) { *ndx++ = i; *ndx++ = i + count; } *ndx++ = 0; show_mesh(canvas, pts0, indices, ndx - indices); } static void show_fan(SkCanvas* canvas, const SkPath& path, SkScalar cx, SkScalar cy) { SkPaint paint; setGLFrame(&paint); canvas->drawPath(path, paint); SkPoint pts[256]; int count = path.getPoints(pts, SK_ARRAY_COUNT(pts)); for (int i = 0; i < count; ++i) { canvas->drawLine(pts[i].fX, pts[i].fY, cx, cy, paint); } } /////////////////////////////////////////////////////////////////////////////// typedef void (*DrawProc)(SkCanvas* canvas, bool showGL, int flags); static void draw_line(SkCanvas* canvas, bool showGL, int flags) { SkPaint paint; paint.setAntiAlias(true); canvas->drawLine(50, 50, 400, 100, paint); canvas->rotate(40); setFade(&paint, showGL); paint.setStrokeWidth(40); canvas->drawLine(100, 50, 450, 50, paint); if (showGL) { show_mesh(canvas, SkRect::MakeLTRB(100, 50-20, 450, 50+20)); } } static void draw_rect(SkCanvas* canvas, bool showGL, int flags) { SkPaint paint; paint.setAntiAlias(true); SkRect r = SkRect::MakeLTRB(50, 70, 250, 370); setFade(&paint, showGL); canvas->drawRect(r, paint); if (showGL) { show_mesh(canvas, r); } canvas->translate(320, 0); paint.setStyle(SkPaint::kStroke_Style); paint.setStrokeWidth(25); canvas->drawRect(r, paint); if (showGL) { SkScalar rad = paint.getStrokeWidth() / 2; SkPoint pts[8]; r.outset(rad, rad); r.toQuad(&pts[0]); r.inset(rad*2, rad*2); r.toQuad(&pts[4]); const uint16_t indices[] = { 0, 4, 1, 5, 2, 6, 3, 7, 0, 4 }; show_mesh(canvas, pts, indices, SK_ARRAY_COUNT(indices)); } } static void draw_oval(SkCanvas* canvas, bool showGL, int flags) { SkPaint paint; paint.setAntiAlias(true); SkRect r = SkRect::MakeLTRB(50, 70, 250, 370); setFade(&paint, showGL); canvas->drawOval(r, paint); if (showGL) { switch (flags) { case 0: { SkPath path; path.addOval(r); show_glframe(canvas, path); } break; case 1: case 2: { SkPath src, dst; src.addOval(r); tesselate(src, &dst); show_fan(canvas, dst, r.centerX(), r.centerY()); } break; } } canvas->translate(320, 0); paint.setStyle(SkPaint::kStroke_Style); paint.setStrokeWidth(25); canvas->drawOval(r, paint); if (showGL) { switch (flags) { case 0: { SkPath path; SkScalar rad = paint.getStrokeWidth() / 2; r.outset(rad, rad); path.addOval(r); r.inset(rad*2, rad*2); path.addOval(r); show_glframe(canvas, path); } break; case 1: { SkPath path0, path1; SkScalar rad = paint.getStrokeWidth() / 2; r.outset(rad, rad); path0.addOval(r); r.inset(rad*2, rad*2); path1.addOval(r); show_mesh_between(canvas, path0, path1); } break; case 2: { SkScalar rad = paint.getStrokeWidth() / 2; r.outset(rad, rad); SkPaint paint; paint.setAlpha(0x33); canvas->drawRect(r, paint); show_mesh(canvas, r); } break; } } } #include "SkImageDecoder.h" static void draw_image(SkCanvas* canvas, bool showGL, int flags) { SkPaint paint; paint.setAntiAlias(true); paint.setFilterBitmap(true); setFade(&paint, showGL); SkBitmap bm; SkImageDecoder::DecodeFile("/skimages/startrek.png", &bm); SkRect r = SkRect::MakeWH(bm.width(), bm.height()); canvas->save(); canvas->translate(30, 30); canvas->scale(0.8f, 0.8f); canvas->drawBitmap(bm, 0, 0, &paint); if (showGL) { show_mesh(canvas, r); } canvas->restore(); canvas->translate(210, 290); canvas->rotate(-35); canvas->drawBitmap(bm, 0, 0, &paint); if (showGL) { show_mesh(canvas, r); } } static void draw_text(SkCanvas* canvas, bool showGL, int flags) { SkPaint paint; paint.setAntiAlias(true); const char text[] = "Graphics at Google"; size_t len = strlen(text); setFade(&paint, showGL); canvas->translate(40, 50); for (int i = 0; i < 10; ++i) { paint.setTextSize(12 + i * 3); canvas->drawText(text, len, 0, 0, paint); if (showGL) { SkRect bounds[256]; SkScalar widths[256]; int count = paint.getTextWidths(text, len, widths, bounds); SkScalar adv = 0; for (int j = 0; j < count; ++j) { bounds[j].offset(adv, 0); show_mesh(canvas, bounds[j]); adv += widths[j]; } } canvas->translate(0, paint.getTextSize() * 3 / 2); } } static const struct { DrawProc fProc; const char* fName; } gRec[] = { { draw_line, "Lines" }, { draw_rect, "Rects" }, { draw_oval, "Ovals" }, { draw_image, "Images" }, { draw_text, "Text" }, }; class TalkGM : public skiagm::GM { DrawProc fProc; SkString fName; bool fShowGL; int fFlags; public: TalkGM(int index, bool showGL, int flags = 0) { fProc = gRec[index].fProc; fName.set(gRec[index].fName); if (showGL) { fName.append("-gl"); } fShowGL = showGL; fFlags = flags; } protected: virtual SkString onShortName() { return fName; } virtual SkISize onISize() { return SkISize::Make(640, 480); } virtual void onDraw(SkCanvas* canvas) { SkRect dst = SkRect::MakeWH(canvas->getDevice()->width(), canvas->getDevice()->height()); SkRect src = SkRect::MakeWH(640, 480); SkMatrix matrix; matrix.setRectToRect(src, dst, SkMatrix::kCenter_ScaleToFit); canvas->concat(matrix); fProc(canvas, fShowGL, fFlags); } private: typedef skiagm::GM INHERITED; }; ////////////////////////////////////////////////////////////////////////////// #define GM_CONCAT(X,Y) GM_CONCAT_IMPL(X,Y) #define GM_CONCAT_IMPL(X,Y) X##Y #define FACTORY_NAME GM_CONCAT(Factory, __LINE__) #define REGISTRY_NAME GM_CONCAT(gReg, __LINE__) #define ADD_GM(Class, args) \ static skiagm::GM* FACTORY_NAME(void*) { return new Class args; } \ static skiagm::GMRegistry REGISTRY_NAME(FACTORY_NAME); ADD_GM(TalkGM, (0, false)) ADD_GM(TalkGM, (0, true)) ADD_GM(TalkGM, (1, false)) ADD_GM(TalkGM, (1, true)) ADD_GM(TalkGM, (2, false)) ADD_GM(TalkGM, (2, true)) ADD_GM(TalkGM, (2, true, 1)) ADD_GM(TalkGM, (2, true, 2)) ADD_GM(TalkGM, (3, false)) ADD_GM(TalkGM, (3, true)) ADD_GM(TalkGM, (4, false)) ADD_GM(TalkGM, (4, true)) //static GM* MyFactory(void*) { return new TalkGM(0, false); } //static GMRegistry reg(MyFactory); <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: opaqitem.hxx,v $ * * $Revision: 1.8 $ * * last change: $Author: kz $ $Date: 2007-05-10 14:20:27 $ * * 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 _SVX_OPAQITEM_HXX #define _SVX_OPAQITEM_HXX // include --------------------------------------------------------------- #ifndef _SFXENUMITEM_HXX //autogen #include <svtools/eitem.hxx> #endif #ifndef INCLUDED_SVXDLLAPI_H #include "svx/svxdllapi.h" #endif class SvXMLUnitConverter; namespace rtl { class OUString; } // class SvxOpaqueItem --------------------------------------------------- /* [Beschreibung] Dieses Item beschreibt eine logische Variable "Undurchsichtig ja oder nein". */ class SVX_DLLPUBLIC SvxOpaqueItem : public SfxBoolItem { public: TYPEINFO(); SvxOpaqueItem( const USHORT nId , const BOOL bOpa = TRUE ); inline SvxOpaqueItem &operator=( const SvxOpaqueItem &rCpy ); // "pure virtual Methoden" vom SfxPoolItem virtual SfxPoolItem* Clone( SfxItemPool *pPool = 0 ) const; virtual SfxPoolItem* Create(SvStream &, USHORT) const; virtual SvStream& Store(SvStream &, USHORT nItemVersion ) const; virtual SfxItemPresentation GetPresentation( SfxItemPresentation ePres, SfxMapUnit eCoreMetric, SfxMapUnit ePresMetric, String &rText, const IntlWrapper * = 0 ) const; }; inline SvxOpaqueItem::SvxOpaqueItem( const USHORT nId, const BOOL bOpa ) : SfxBoolItem( nId, bOpa ) {} inline SvxOpaqueItem &SvxOpaqueItem::operator=( const SvxOpaqueItem &rCpy ) { SetValue( rCpy.GetValue() ); return *this; } #endif <commit_msg>INTEGRATION: CWS changefileheader (1.8.446); FILE MERGED 2008/04/01 15:49:19 thb 1.8.446.3: #i85898# Stripping all external header guards 2008/04/01 12:46:23 thb 1.8.446.2: #i85898# Stripping all external header guards 2008/03/31 14:17:58 rt 1.8.446.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: opaqitem.hxx,v $ * $Revision: 1.9 $ * * 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 _SVX_OPAQITEM_HXX #define _SVX_OPAQITEM_HXX // include --------------------------------------------------------------- #include <svtools/eitem.hxx> #include "svx/svxdllapi.h" class SvXMLUnitConverter; namespace rtl { class OUString; } // class SvxOpaqueItem --------------------------------------------------- /* [Beschreibung] Dieses Item beschreibt eine logische Variable "Undurchsichtig ja oder nein". */ class SVX_DLLPUBLIC SvxOpaqueItem : public SfxBoolItem { public: TYPEINFO(); SvxOpaqueItem( const USHORT nId , const BOOL bOpa = TRUE ); inline SvxOpaqueItem &operator=( const SvxOpaqueItem &rCpy ); // "pure virtual Methoden" vom SfxPoolItem virtual SfxPoolItem* Clone( SfxItemPool *pPool = 0 ) const; virtual SfxPoolItem* Create(SvStream &, USHORT) const; virtual SvStream& Store(SvStream &, USHORT nItemVersion ) const; virtual SfxItemPresentation GetPresentation( SfxItemPresentation ePres, SfxMapUnit eCoreMetric, SfxMapUnit ePresMetric, String &rText, const IntlWrapper * = 0 ) const; }; inline SvxOpaqueItem::SvxOpaqueItem( const USHORT nId, const BOOL bOpa ) : SfxBoolItem( nId, bOpa ) {} inline SvxOpaqueItem &SvxOpaqueItem::operator=( const SvxOpaqueItem &rCpy ) { SetValue( rCpy.GetValue() ); return *this; } #endif <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: unoshcol.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2003-09-19 08:32:11 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SVX_UNOSHGRP_HXX #define _SVX_UNOSHGRP_HXX #ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_ #include <com/sun/star/lang/XComponent.hpp> #endif #ifndef _COM_SUN_STAR_DRAWING_XSHAPES_HPP_ #include <com/sun/star/drawing/XShapes.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _OSL_MUTEX_HXX_ #include <osl/mutex.hxx> #endif #ifndef _CPPUHELPER_INTERFACECONTAINER_HXX_ #include <cppuhelper/interfacecontainer.hxx> #endif #include <cppuhelper/implbase3.hxx> class XShapeList; class SvxShapeCollectionMutex { public: ::osl::Mutex maMutex; }; com::sun::star::uno::Reference< com::sun::star::uno::XInterface > SvxShapeCollection_NewInstance() throw(); /*********************************************************************** * * ***********************************************************************/ class SvxShapeCollection : public ::cppu::WeakAggImplHelper3< ::com::sun::star::drawing::XShapes, ::com::sun::star::lang::XServiceInfo, ::com::sun::star::lang::XComponent >, public SvxShapeCollectionMutex { private: cppu::OInterfaceContainerHelper maShapeContainer; cppu::OBroadcastHelper mrBHelper; virtual void disposing() throw(); public: SvxShapeCollection() throw(); virtual ~SvxShapeCollection() throw(); // XInterface virtual void SAL_CALL release() throw(); // XComponent virtual void SAL_CALL dispose() throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL addEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& aListener ) throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removeEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& aListener ) throw(::com::sun::star::uno::RuntimeException); // XIndexAccess virtual sal_Int32 SAL_CALL getCount() throw(::com::sun::star::uno::RuntimeException) ; virtual ::com::sun::star::uno::Any SAL_CALL getByIndex( sal_Int32 Index ) throw(::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); // XElementAccess virtual ::com::sun::star::uno::Type SAL_CALL getElementType() throw(::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL hasElements() throw(::com::sun::star::uno::RuntimeException); // XShapes virtual void SAL_CALL add( const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape >& xShape ) throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL remove( const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape >& xShape ) throw(::com::sun::star::uno::RuntimeException); // XServiceInfo virtual ::rtl::OUString SAL_CALL getImplementationName() throw(::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw(::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException); static com::sun::star::uno::Sequence< ::rtl::OUString > getSupportedServiceNames_Static(); static ::rtl::OUString getImplementationName_Static(); }; ::com::sun::star::uno::Reference< com::sun::star::uno::XInterface > SAL_CALL SvxShapeCollection_createInstance( const com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& rSMgr ); #endif <commit_msg>INTEGRATION: CWS visibility01 (1.3.518); FILE MERGED 2004/12/06 08:10:56 mnicel 1.3.518.2: Part of symbol visibility markup - #i35758# 2004/11/19 12:54:35 mmeeks 1.3.518.1: Issue number: #i35758# Submitted by: mnicel Reviewed by: mmeeks<commit_after>/************************************************************************* * * $RCSfile: unoshcol.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: kz $ $Date: 2005-01-21 15:50:43 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SVX_UNOSHGRP_HXX #define _SVX_UNOSHGRP_HXX #ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_ #include <com/sun/star/lang/XComponent.hpp> #endif #ifndef _COM_SUN_STAR_DRAWING_XSHAPES_HPP_ #include <com/sun/star/drawing/XShapes.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _OSL_MUTEX_HXX_ #include <osl/mutex.hxx> #endif #ifndef _CPPUHELPER_INTERFACECONTAINER_HXX_ #include <cppuhelper/interfacecontainer.hxx> #endif #include <cppuhelper/implbase3.hxx> #ifndef INCLUDED_SVXDLLAPI_H #include "svx/svxdllapi.h" #endif class XShapeList; class SvxShapeCollectionMutex { public: ::osl::Mutex maMutex; }; SVX_DLLPUBLIC com::sun::star::uno::Reference< com::sun::star::uno::XInterface > SvxShapeCollection_NewInstance() throw(); /*********************************************************************** * * ***********************************************************************/ class SVX_DLLPUBLIC SvxShapeCollection : public ::cppu::WeakAggImplHelper3< ::com::sun::star::drawing::XShapes, ::com::sun::star::lang::XServiceInfo, ::com::sun::star::lang::XComponent >, public SvxShapeCollectionMutex { private: cppu::OInterfaceContainerHelper maShapeContainer; cppu::OBroadcastHelper mrBHelper; SVX_DLLPRIVATE virtual void disposing() throw(); public: SvxShapeCollection() throw(); virtual ~SvxShapeCollection() throw(); // XInterface virtual void SAL_CALL release() throw(); // XComponent virtual void SAL_CALL dispose() throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL addEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& aListener ) throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removeEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& aListener ) throw(::com::sun::star::uno::RuntimeException); // XIndexAccess virtual sal_Int32 SAL_CALL getCount() throw(::com::sun::star::uno::RuntimeException) ; virtual ::com::sun::star::uno::Any SAL_CALL getByIndex( sal_Int32 Index ) throw(::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); // XElementAccess virtual ::com::sun::star::uno::Type SAL_CALL getElementType() throw(::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL hasElements() throw(::com::sun::star::uno::RuntimeException); // XShapes virtual void SAL_CALL add( const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape >& xShape ) throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL remove( const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape >& xShape ) throw(::com::sun::star::uno::RuntimeException); // XServiceInfo virtual ::rtl::OUString SAL_CALL getImplementationName() throw(::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw(::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException); static com::sun::star::uno::Sequence< ::rtl::OUString > getSupportedServiceNames_Static(); static ::rtl::OUString getImplementationName_Static(); }; ::com::sun::star::uno::Reference< com::sun::star::uno::XInterface > SAL_CALL SvxShapeCollection_createInstance( const com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& rSMgr ); #endif <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: printdata.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-09 02:05:30 $ * * 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 _SW_PRINTDATA_HXX #define _SW_PRINTDATA_HXX #ifndef _SAL_TYPES_H_ #include <sal/types.h> #endif #ifndef _RTL_USTRING_ #include <rtl/ustring> #endif struct SwPrintData { sal_Bool bPrintGraphic, bPrintTable, bPrintDraw, bPrintControl, bPrintPageBackground, bPrintBlackFont, bPrintLeftPage, bPrintRightPage, bPrintReverse, bPrintProspect, bPrintSingleJobs, bPaperFromSetup, bModified; sal_Int16 nPrintPostIts; rtl::OUString sFaxName; SwPrintData() { bPrintGraphic = bPrintTable = bPrintDraw = bPrintControl = bPrintLeftPage = bPrintRightPage = bPrintPageBackground = sal_True; bPaperFromSetup = bPrintReverse = bPrintProspect = bPrintSingleJobs = bModified = bPrintBlackFont = sal_False; nPrintPostIts = 0; } sal_Bool operator==(const SwPrintData& rData)const { return bPrintGraphic == rData.bPrintGraphic && bPrintTable == rData.bPrintTable && bPrintDraw == rData.bPrintDraw && bPrintControl == rData.bPrintControl && bPrintPageBackground== rData.bPrintPageBackground&& bPrintBlackFont == rData.bPrintBlackFont && bPrintLeftPage == rData.bPrintLeftPage && bPrintRightPage == rData.bPrintRightPage && bPrintReverse == rData.bPrintReverse && bPrintProspect == rData.bPrintProspect && bPrintSingleJobs == rData.bPrintSingleJobs && bPaperFromSetup == rData.bPaperFromSetup && nPrintPostIts == rData.nPrintPostIts && sFaxName == rData.sFaxName; } sal_Bool IsPrintGraphic() const { return bPrintGraphic; } sal_Bool IsPrintTable() const { return bPrintTable; } sal_Bool IsPrintDraw() const { return bPrintDraw; } sal_Bool IsPrintControl() const { return bPrintControl; } sal_Bool IsPrintLeftPage() const { return bPrintLeftPage; } sal_Bool IsPrintRightPage() const { return bPrintRightPage; } sal_Bool IsPrintReverse() const { return bPrintReverse; } sal_Bool IsPaperFromSetup() const { return bPaperFromSetup; } sal_Bool IsPrintProspect() const { return bPrintProspect; } sal_Bool IsPrintPageBackground() const { return bPrintPageBackground; } sal_Bool IsPrintBlackFont() const { return bPrintBlackFont;} sal_Bool IsPrintSingleJobs() const { return bPrintSingleJobs;} sal_Int16 GetPrintPostIts() const { return nPrintPostIts; } const rtl::OUString GetFaxName() const{return sFaxName;} void SetPrintGraphic ( sal_Bool b ) { doSetModified(); bPrintGraphic = b;} void SetPrintTable ( sal_Bool b ) { doSetModified(); bPrintTable = b;} void SetPrintDraw ( sal_Bool b ) { doSetModified(); bPrintDraw = b;} void SetPrintControl ( sal_Bool b ) { doSetModified(); bPrintControl = b; } void SetPrintLeftPage ( sal_Bool b ) { doSetModified(); bPrintLeftPage = b;} void SetPrintRightPage( sal_Bool b ) { doSetModified(); bPrintRightPage = b;} void SetPrintReverse ( sal_Bool b ) { doSetModified(); bPrintReverse = b;} void SetPaperFromSetup( sal_Bool b ) { doSetModified(); bPaperFromSetup = b;} void SetPrintPostIts ( sal_Int16 n){ doSetModified(); nPrintPostIts = n; } void SetPrintProspect ( sal_Bool b ) { doSetModified(); bPrintProspect = b; } void SetPrintPageBackground(sal_Bool b){ doSetModified(); bPrintPageBackground = b;} void SetPrintBlackFont(sal_Bool b){ doSetModified(); bPrintBlackFont = b;} void SetPrintSingleJobs(sal_Bool b){ doSetModified(); bPrintSingleJobs = b;} void SetFaxName(const rtl::OUString& rSet){sFaxName = rSet;} virtual void doSetModified () { bModified = sal_True;} sal_Bool WasModified () { return bModified; } }; #endif //_SW_PRINTDATA_HXX <commit_msg>INTEGRATION: CWS emptypage (1.3.152); FILE MERGED 2005/12/13 15:27:09 fme 1.3.152.1: #b6354161# Feature - Print empty pages<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: printdata.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: obo $ $Date: 2005-12-21 15:09:55 $ * * 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 _SW_PRINTDATA_HXX #define _SW_PRINTDATA_HXX #ifndef _SAL_TYPES_H_ #include <sal/types.h> #endif #ifndef _RTL_USTRING_ #include <rtl/ustring> #endif struct SwPrintData { sal_Bool bPrintGraphic, bPrintTable, bPrintDraw, bPrintControl, bPrintPageBackground, bPrintBlackFont, bPrintLeftPage, bPrintRightPage, bPrintReverse, bPrintProspect, bPrintSingleJobs, bPaperFromSetup, // --> FME 2005-12-13 #b6354161# Print empty pages bPrintEmptyPages, // <-- bModified; sal_Int16 nPrintPostIts; rtl::OUString sFaxName; SwPrintData() { bPrintGraphic = bPrintTable = bPrintDraw = bPrintControl = bPrintLeftPage = bPrintRightPage = bPrintPageBackground = bPrintEmptyPages = sal_True; bPaperFromSetup = bPrintReverse = bPrintProspect = bPrintSingleJobs = bModified = bPrintBlackFont = sal_False; nPrintPostIts = 0; } sal_Bool operator==(const SwPrintData& rData)const { return bPrintGraphic == rData.bPrintGraphic && bPrintTable == rData.bPrintTable && bPrintDraw == rData.bPrintDraw && bPrintControl == rData.bPrintControl && bPrintPageBackground== rData.bPrintPageBackground&& bPrintBlackFont == rData.bPrintBlackFont && bPrintLeftPage == rData.bPrintLeftPage && bPrintRightPage == rData.bPrintRightPage && bPrintReverse == rData.bPrintReverse && bPrintProspect == rData.bPrintProspect && bPrintSingleJobs == rData.bPrintSingleJobs && bPaperFromSetup == rData.bPaperFromSetup && bPrintEmptyPages == rData.bPrintEmptyPages && nPrintPostIts == rData.nPrintPostIts && sFaxName == rData.sFaxName; } sal_Bool IsPrintGraphic() const { return bPrintGraphic; } sal_Bool IsPrintTable() const { return bPrintTable; } sal_Bool IsPrintDraw() const { return bPrintDraw; } sal_Bool IsPrintControl() const { return bPrintControl; } sal_Bool IsPrintLeftPage() const { return bPrintLeftPage; } sal_Bool IsPrintRightPage() const { return bPrintRightPage; } sal_Bool IsPrintReverse() const { return bPrintReverse; } sal_Bool IsPaperFromSetup() const { return bPaperFromSetup; } sal_Bool IsPrintEmptyPages() const{ return bPrintEmptyPages; } sal_Bool IsPrintProspect() const { return bPrintProspect; } sal_Bool IsPrintPageBackground() const { return bPrintPageBackground; } sal_Bool IsPrintBlackFont() const { return bPrintBlackFont;} sal_Bool IsPrintSingleJobs() const { return bPrintSingleJobs;} sal_Int16 GetPrintPostIts() const { return nPrintPostIts; } const rtl::OUString GetFaxName() const{return sFaxName;} void SetPrintGraphic ( sal_Bool b ) { doSetModified(); bPrintGraphic = b;} void SetPrintTable ( sal_Bool b ) { doSetModified(); bPrintTable = b;} void SetPrintDraw ( sal_Bool b ) { doSetModified(); bPrintDraw = b;} void SetPrintControl ( sal_Bool b ) { doSetModified(); bPrintControl = b; } void SetPrintLeftPage ( sal_Bool b ) { doSetModified(); bPrintLeftPage = b;} void SetPrintRightPage( sal_Bool b ) { doSetModified(); bPrintRightPage = b;} void SetPrintReverse ( sal_Bool b ) { doSetModified(); bPrintReverse = b;} void SetPaperFromSetup( sal_Bool b ) { doSetModified(); bPaperFromSetup = b;} void SetPrintEmptyPages(sal_Bool b ) { doSetModified(); bPrintEmptyPages = b;} void SetPrintPostIts ( sal_Int16 n){ doSetModified(); nPrintPostIts = n; } void SetPrintProspect ( sal_Bool b ) { doSetModified(); bPrintProspect = b; } void SetPrintPageBackground(sal_Bool b){ doSetModified(); bPrintPageBackground = b;} void SetPrintBlackFont(sal_Bool b){ doSetModified(); bPrintBlackFont = b;} void SetPrintSingleJobs(sal_Bool b){ doSetModified(); bPrintSingleJobs = b;} void SetFaxName(const rtl::OUString& rSet){sFaxName = rSet;} virtual void doSetModified () { bModified = sal_True;} sal_Bool WasModified () { return bModified; } }; #endif //_SW_PRINTDATA_HXX <|endoftext|>
<commit_before> #include "base.h" namespace sgraph{ void sgmanager::pause() { this->pause_threads_lock.lock(); this->pause_threads = true; this->pause_threads_lock.unlock(); //for (std::tuple<>) } void sgmanager::start() { this->pause_threads_lock.lock(); this->pause_threads = false; this->pause_threads_lock.unlock(); this->_pause_threads_finished.notify_all(); //for (std::tuple<>) } void sgmanager::stop() { this->pause_threads_lock.lock(); this->pause_threads = false; this->active=false; this->pause_threads_lock.unlock(); this->_pause_threads_finished.notify_all(); for (auto it: this->actordict) { it.second->leave(); } for (auto it: this->actordict) { it.second->join(); } } bool sgmanager::interrupt_thread(sgactor *actor) { std::unique_lock<std::mutex> lck (this->pause_threads_lock); if (this->pause_threads) { this->_pause_threads_finished.wait(lck); } return this->active; } void sgmanager::updateStreamspec(const std::string &name, sgstreamspec* obj) { this->streamdict.at(name).reset(obj); } std::vector<sgraph::sgstreamspec*> sgmanager::getStreamspecs(const std::vector<std::string> &streamnames) { std::vector<sgstreamspec*> ret; for (std::string elem: streamnames) { if (this->streamdict.count(elem)==0) { throw(MissingStreamException(elem)); } ret.push_back(this->streamdict.at(elem).get()); } return ret; } std::vector<sgactor*> sgmanager::getActors(const std::vector<std::string> &actornames) { std::vector<sgactor*> ret; for (std::string elem: actornames) { if (this->actordict.count(elem)==0) { throw(MissingActorException(elem)); } ret.push_back(this->actordict.at(elem).get()); } return ret; } void sgmanager::addActor(const std::string &name, sgactor *actor, const std::vector<std::string> &streamnamesin, const std::vector<std::string> &streamnamesout) { for (std::string elem: streamnamesin) { if (this->streamdict.count(elem)==0) { throw(MissingStreamException(elem)); } } for (std::string elem: streamnamesout) { if (this->streamdict.count(elem)==1) { throw(NameCollisionException("Outputstream: \""+elem+"\" already exists")); } this->streamdict[elem] = std::shared_ptr<sgstreamspec>(0); //must be initialised in enter } if (this->actordict.count(name)==1) { throw(NameCollisionException("Actor: \""+name+"\" already exists")); } actor->init(name, this, streamnamesin, streamnamesout); this->actordict[name] = std::shared_ptr<sgactor>(actor); } void sgstreamspec::updateStream(sgstream* streamob) { this->protaccess.lock(); if (interests>0) { std::unique_lock<std::mutex> lck(this->protaccess, std::adopt_lock); this->reading_finished.wait(lck); } this->stream = std::shared_ptr<sgstream> (streamob); updating_finished.notify_all(); this->protaccess.unlock(); } std::shared_ptr<sgstream> sgstreamspec::getStream(int64_t blockingtime) { std::shared_ptr<sgstream> ret; this->protaccess.lock(); std::unique_lock<std::mutex> lck(this->protaccess, std::adopt_lock); if (blockingtime==-1) { this->updating_finished.wait(lck); }else if (blockingtime>0) { if (this->updating_finished.wait_for(lck, std::chrono::nanoseconds(blockingtime)) == std::cv_status::timeout) { return std::shared_ptr<sgstream> (0); } } ret = this->stream; this->reading_finished.notify_one(); this->protaccess.unlock(); return ret; } sgactor::sgactor(double freq, int64_t blockingtime) { this->blockingtime = blockingtime; this->time_sleep = std::chrono::nanoseconds((int64_t)(1000000.0L/freq)); this->time_previous = std::chrono::steady_clock::now(); } void sgactor::join() { if (this->intern_thread) { this->intern_thread->join(); delete this->intern_thread; } } std::shared_ptr<sgstream> getStreamhelper(sgstreamspec *t, int64_t blockingtime) { return t->getStream(blockingtime); } std::vector<std::shared_ptr<sgstream>> sgactor::getStreams() { this->_tretgetStreams.clear(); this->_thandlesgetStreams.clear(); //std::vector<auto> handles; for (sgstreamspec* elem: this->streamsin) { if (elem==0) { throw(UninitializedStreamException()); } _thandlesgetStreams.push_back(std::async(std::launch::async, getStreamhelper, elem, this->blockingtime)); } for (std::future<std::shared_ptr<sgstream>> &elem: _thandlesgetStreams) { elem.wait(); _tretgetStreams.push_back(elem.get()); } return _tretgetStreams; } void sgactor::step(){ this->active=this->manager->interrupt_thread(this); if (!this->active) { return; } auto tstart = std::chrono::steady_clock::now(); auto tosleep = this->time_sleep-(tstart-this->time_previous); std::this_thread::sleep_for(std::chrono::duration_cast<std::chrono::nanoseconds> (tosleep)); this->run(this->getStreams()); this->time_previous = std::chrono::steady_clock::now(); //this->transform(sgactor, std::forward(sgactor)); }; void sgactor::init(const std::string &name, sgmanager *manager, const std::vector<std::string> &streamnamesin, const std::vector<std::string> &streamnamesout) { this->name = name; this->manager = manager; this->owned_instreams.insert(streamnamesin.begin(),streamnamesin.end()); this->owned_outstreams.insert(streamnamesout.begin(),streamnamesout.end()); this->streamsin = manager->getStreamspecs(streamnamesin); this->_tretgetStreams = std::vector<std::shared_ptr<sgstream>> (this->streamsin.size()); this->_thandlesgetStreams = std::vector<std::future<std::shared_ptr<sgstream>>> (this->streamsin.size()); this->enter(this->streamsin, streamnamesout); this->streamsout = manager->getStreamspecs(streamnamesout); } } <commit_msg>nano is smaller than a 1000000 second<commit_after> #include "base.h" namespace sgraph{ void sgmanager::pause() { this->pause_threads_lock.lock(); this->pause_threads = true; this->pause_threads_lock.unlock(); //for (std::tuple<>) } void sgmanager::start() { this->pause_threads_lock.lock(); this->pause_threads = false; this->pause_threads_lock.unlock(); this->_pause_threads_finished.notify_all(); //for (std::tuple<>) } void sgmanager::stop() { this->pause_threads_lock.lock(); this->pause_threads = false; this->active=false; this->pause_threads_lock.unlock(); this->_pause_threads_finished.notify_all(); for (auto it: this->actordict) { it.second->leave(); } for (auto it: this->actordict) { it.second->join(); } } bool sgmanager::interrupt_thread(sgactor *actor) { std::unique_lock<std::mutex> lck (this->pause_threads_lock); if (this->pause_threads) { this->_pause_threads_finished.wait(lck); } return this->active; } void sgmanager::updateStreamspec(const std::string &name, sgstreamspec* obj) { this->streamdict.at(name).reset(obj); } std::vector<sgraph::sgstreamspec*> sgmanager::getStreamspecs(const std::vector<std::string> &streamnames) { std::vector<sgstreamspec*> ret; for (std::string elem: streamnames) { if (this->streamdict.count(elem)==0) { throw(MissingStreamException(elem)); } ret.push_back(this->streamdict.at(elem).get()); } return ret; } std::vector<sgactor*> sgmanager::getActors(const std::vector<std::string> &actornames) { std::vector<sgactor*> ret; for (std::string elem: actornames) { if (this->actordict.count(elem)==0) { throw(MissingActorException(elem)); } ret.push_back(this->actordict.at(elem).get()); } return ret; } void sgmanager::addActor(const std::string &name, sgactor *actor, const std::vector<std::string> &streamnamesin, const std::vector<std::string> &streamnamesout) { for (std::string elem: streamnamesin) { if (this->streamdict.count(elem)==0) { throw(MissingStreamException(elem)); } } for (std::string elem: streamnamesout) { if (this->streamdict.count(elem)==1) { throw(NameCollisionException("Outputstream: \""+elem+"\" already exists")); } this->streamdict[elem] = std::shared_ptr<sgstreamspec>(0); //must be initialised in enter } if (this->actordict.count(name)==1) { throw(NameCollisionException("Actor: \""+name+"\" already exists")); } actor->init(name, this, streamnamesin, streamnamesout); this->actordict[name] = std::shared_ptr<sgactor>(actor); } void sgstreamspec::updateStream(sgstream* streamob) { this->protaccess.lock(); if (interests>0) { std::unique_lock<std::mutex> lck(this->protaccess, std::adopt_lock); this->reading_finished.wait(lck); } this->stream = std::shared_ptr<sgstream> (streamob); updating_finished.notify_all(); this->protaccess.unlock(); } std::shared_ptr<sgstream> sgstreamspec::getStream(int64_t blockingtime) { std::shared_ptr<sgstream> ret; this->protaccess.lock(); std::unique_lock<std::mutex> lck(this->protaccess, std::adopt_lock); if (blockingtime==-1) { this->updating_finished.wait(lck); }else if (blockingtime>0) { if (this->updating_finished.wait_for(lck, std::chrono::nanoseconds(blockingtime)) == std::cv_status::timeout) { return std::shared_ptr<sgstream> (0); } } ret = this->stream; this->reading_finished.notify_one(); this->protaccess.unlock(); return ret; } sgactor::sgactor(double freq, int64_t blockingtime) { this->blockingtime = blockingtime; this->time_sleep = std::chrono::nanoseconds((int64_t)(1000000000.0L/freq)); this->time_previous = std::chrono::steady_clock::now(); } void sgactor::join() { if (this->intern_thread) { this->intern_thread->join(); delete this->intern_thread; } } std::shared_ptr<sgstream> getStreamhelper(sgstreamspec *t, int64_t blockingtime) { return t->getStream(blockingtime); } std::vector<std::shared_ptr<sgstream>> sgactor::getStreams() { this->_tretgetStreams.clear(); this->_thandlesgetStreams.clear(); //std::vector<auto> handles; for (sgstreamspec* elem: this->streamsin) { if (elem==0) { throw(UninitializedStreamException()); } _thandlesgetStreams.push_back(std::async(std::launch::async, getStreamhelper, elem, this->blockingtime)); } for (std::future<std::shared_ptr<sgstream>> &elem: _thandlesgetStreams) { elem.wait(); _tretgetStreams.push_back(elem.get()); } return _tretgetStreams; } void sgactor::step(){ this->active=this->manager->interrupt_thread(this); if (!this->active) { return; } auto tstart = std::chrono::steady_clock::now(); auto tosleep = this->time_sleep-(tstart-this->time_previous); std::this_thread::sleep_for(std::chrono::duration_cast<std::chrono::nanoseconds> (tosleep)); this->run(this->getStreams()); this->time_previous = std::chrono::steady_clock::now(); //this->transform(sgactor, std::forward(sgactor)); }; void sgactor::init(const std::string &name, sgmanager *manager, const std::vector<std::string> &streamnamesin, const std::vector<std::string> &streamnamesout) { this->name = name; this->manager = manager; this->owned_instreams.insert(streamnamesin.begin(),streamnamesin.end()); this->owned_outstreams.insert(streamnamesout.begin(),streamnamesout.end()); this->streamsin = manager->getStreamspecs(streamnamesin); this->_tretgetStreams = std::vector<std::shared_ptr<sgstream>> (this->streamsin.size()); this->_thandlesgetStreams = std::vector<std::future<std::shared_ptr<sgstream>>> (this->streamsin.size()); this->enter(this->streamsin, streamnamesout); this->streamsout = manager->getStreamspecs(streamnamesout); } } <|endoftext|>
<commit_before>// Import daughters of track with given label. Reve::TrackList* kine_daughter_tracks(Int_t label, Reve::TrackList* cont = 0) { using namespace Reve; gSystem->IgnoreSignal(kSigSegmentationViolation, true); if (label < 0) { Warning("kine_daughter_tracks", "label not set."); return 0; } //Bool_t create_cont; //create_cont = cont ? 0:1; AliRunLoader* rl = Alieve::Event::AssertRunLoader(); rl->LoadKinematics(); AliStack* stack = rl->Stack(); TParticle* p = stack->Particle(label); if (p->GetNDaughters()) { if (cont == 0) { printf("create container \n"); cont = new TrackList(Form("%d kine_daughter_tracks %d", p->GetNDaughters(), label)); Reve::TrackRnrStyle* rnrStyle = cont->GetRnrStyle(); // !!! Watch the '-', apparently different sign convention then for ESD. rnrStyle->SetMagField( - gAlice->Field()->SolenoidField() ); char tooltip[1000]; sprintf(tooltip,"%d, mother %d", p->GetNDaughters(), label); cont->SetTitle(tooltip); cont->SelectByPt(0, 100); rnrStyle->fColor = 8; rnrStyle->fMaxOrbs = 8; gReve->AddRenderElement(cont); } for (int d=p->GetFirstDaughter(); d>0 && d<=p->GetLastDaughter(); ++d) { TParticle* dp = stack->Particle(d); Track* track = new Reve::Track(dp, d, cont->GetRnrStyle()); char form[1000]; sprintf(form,"%s [%d]", dp->GetName(), d); track->SetName(form); gReve->AddRenderElement(cont, track); } cont->UpdateItems(); // update list tree cont->MakeTracks(); cont->MakeMarkers(); gReve->Redraw3D(); return cont; } else { printf("Particle %d does not have daughters.", label); return 0; } } <commit_msg>Set path marks in track container.<commit_after>// Import daughters of track with given label. Reve::TrackList* kine_daughter_tracks(Int_t label, Reve::TrackList* cont = 0) { using namespace Reve; gSystem->IgnoreSignal(kSigSegmentationViolation, true); if (label < 0) { Warning("kine_daughter_tracks", "label not set."); return 0; } AliRunLoader* rl = Alieve::Event::AssertRunLoader(); rl->LoadKinematics(); AliStack* stack = rl->Stack(); TParticle* p = stack->Particle(label); if (p->GetNDaughters()) { if (cont == 0) { cont = new TrackList(Form("%d kine_daughter_tracks %d", p->GetNDaughters(), label)); Reve::TrackRnrStyle* rnrStyle = cont->GetRnrStyle(); // !!! Watch the '-', apparently different sign convention then for ESD. rnrStyle->SetMagField( - gAlice->Field()->SolenoidField() ); char tooltip[1000]; sprintf(tooltip,"%d, mother %d", p->GetNDaughters(), label); cont->SetTitle(tooltip); cont->SelectByPt(0, 100); cont->SetEditPathMarks(kTRUE); rnrStyle->fColor = 8; rnrStyle->fMaxOrbs = 8; gReve->AddRenderElement(cont); } for (int d=p->GetFirstDaughter(); d>0 && d<=p->GetLastDaughter(); ++d) { TParticle* dp = stack->Particle(d); Track* track = new Reve::Track(dp, d, cont->GetRnrStyle()); char form[1000]; sprintf(form,"%s [%d]", dp->GetName(), d); track->SetName(form); gReve->AddRenderElement(cont, track); } // set path marks if(cont->GetEditPathMarks()) { Alieve::KineTools kt; rl->LoadTrackRefs(); kt.SetPathMarks(cont,stack, rl->TreeTR()); } cont->UpdateItems(); // update list tree cont->MakeTracks(); cont->MakeMarkers(); gReve->Redraw3D(); return cont; } else { Warning("kine_daughters_tracks", Form("Particle %d does not have daughters %d.", label)); return 0; } } <|endoftext|>
<commit_before>/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ // -*- c++ -*- #include <faiss/IVFlib.h> #include <memory> #include <faiss/IndexPreTransform.h> #include <faiss/impl/FaissAssert.h> #include <faiss/MetaIndexes.h> namespace faiss { namespace ivflib { void check_compatible_for_merge (const Index * index0, const Index * index1) { const faiss::IndexPreTransform *pt0 = dynamic_cast<const faiss::IndexPreTransform *>(index0); if (pt0) { const faiss::IndexPreTransform *pt1 = dynamic_cast<const faiss::IndexPreTransform *>(index1); FAISS_THROW_IF_NOT_MSG (pt1, "both indexes should be pretransforms"); FAISS_THROW_IF_NOT (pt0->chain.size() == pt1->chain.size()); for (int i = 0; i < pt0->chain.size(); i++) { FAISS_THROW_IF_NOT (typeid(pt0->chain[i]) == typeid(pt1->chain[i])); } index0 = pt0->index; index1 = pt1->index; } FAISS_THROW_IF_NOT (typeid(index0) == typeid(index1)); FAISS_THROW_IF_NOT (index0->d == index1->d && index0->metric_type == index1->metric_type); const faiss::IndexIVF *ivf0 = dynamic_cast<const faiss::IndexIVF *>(index0); if (ivf0) { const faiss::IndexIVF *ivf1 = dynamic_cast<const faiss::IndexIVF *>(index1); FAISS_THROW_IF_NOT (ivf1); ivf0->check_compatible_for_merge (*ivf1); } // TODO: check as thoroughfully for other index types } const IndexIVF * try_extract_index_ivf (const Index * index) { if (auto *pt = dynamic_cast<const IndexPreTransform *>(index)) { index = pt->index; } if (auto *idmap = dynamic_cast<const IndexIDMap *>(index)) { index = idmap->index; } if (auto *idmap = dynamic_cast<const IndexIDMap2 *>(index)) { index = idmap->index; } auto *ivf = dynamic_cast<const IndexIVF *>(index); return ivf; } IndexIVF * try_extract_index_ivf (Index * index) { return const_cast<IndexIVF*> (try_extract_index_ivf ((const Index*)(index))); } const IndexIVF * extract_index_ivf (const Index * index) { const IndexIVF *ivf = try_extract_index_ivf (index); FAISS_THROW_IF_NOT (ivf); return ivf; } IndexIVF * extract_index_ivf (Index * index) { return const_cast<IndexIVF*> (extract_index_ivf ((const Index*)(index))); } void merge_into(faiss::Index *index0, faiss::Index *index1, bool shift_ids) { check_compatible_for_merge (index0, index1); IndexIVF * ivf0 = extract_index_ivf (index0); IndexIVF * ivf1 = extract_index_ivf (index1); ivf0->merge_from (*ivf1, shift_ids ? ivf0->ntotal : 0); // useful for IndexPreTransform index0->ntotal = ivf0->ntotal; index1->ntotal = ivf1->ntotal; } void search_centroid(faiss::Index *index, const float* x, int n, idx_t* centroid_ids) { std::unique_ptr<float[]> del; if (auto index_pre = dynamic_cast<faiss::IndexPreTransform*>(index)) { x = index_pre->apply_chain(n, x); del.reset((float*)x); index = index_pre->index; } faiss::IndexIVF* index_ivf = dynamic_cast<faiss::IndexIVF*>(index); assert(index_ivf); index_ivf->quantizer->assign(n, x, centroid_ids); } void search_and_return_centroids(faiss::Index *index, size_t n, const float* xin, long k, float *distances, idx_t* labels, idx_t* query_centroid_ids, idx_t* result_centroid_ids) { const float *x = xin; std::unique_ptr<float []> del; if (auto index_pre = dynamic_cast<faiss::IndexPreTransform*>(index)) { x = index_pre->apply_chain(n, x); del.reset((float*)x); index = index_pre->index; } faiss::IndexIVF* index_ivf = dynamic_cast<faiss::IndexIVF*>(index); assert(index_ivf); size_t nprobe = index_ivf->nprobe; std::vector<idx_t> cent_nos (n * nprobe); std::vector<float> cent_dis (n * nprobe); index_ivf->quantizer->search( n, x, nprobe, cent_dis.data(), cent_nos.data()); if (query_centroid_ids) { for (size_t i = 0; i < n; i++) query_centroid_ids[i] = cent_nos[i * nprobe]; } index_ivf->search_preassigned (n, x, k, cent_nos.data(), cent_dis.data(), distances, labels, true); for (size_t i = 0; i < n * k; i++) { idx_t label = labels[i]; if (label < 0) { if (result_centroid_ids) result_centroid_ids[i] = -1; } else { long list_no = lo_listno (label); long list_index = lo_offset (label); if (result_centroid_ids) result_centroid_ids[i] = list_no; labels[i] = index_ivf->invlists->get_single_id(list_no, list_index); } } } SlidingIndexWindow::SlidingIndexWindow (Index *index): index (index) { n_slice = 0; IndexIVF* index_ivf = const_cast<IndexIVF*>(extract_index_ivf (index)); ils = dynamic_cast<ArrayInvertedLists *> (index_ivf->invlists); nlist = ils->nlist; FAISS_THROW_IF_NOT_MSG (ils, "only supports indexes with ArrayInvertedLists"); sizes.resize(nlist); } template<class T> static void shift_and_add (std::vector<T> & dst, size_t remove, const std::vector<T> & src) { if (remove > 0) memmove (dst.data(), dst.data() + remove, (dst.size() - remove) * sizeof (T)); size_t insert_point = dst.size() - remove; dst.resize (insert_point + src.size()); memcpy (dst.data() + insert_point, src.data (), src.size() * sizeof(T)); } template<class T> static void remove_from_begin (std::vector<T> & v, size_t remove) { if (remove > 0) v.erase (v.begin(), v.begin() + remove); } void SlidingIndexWindow::step(const Index *sub_index, bool remove_oldest) { FAISS_THROW_IF_NOT_MSG (!remove_oldest || n_slice > 0, "cannot remove slice: there is none"); const ArrayInvertedLists *ils2 = nullptr; if(sub_index) { check_compatible_for_merge (index, sub_index); ils2 = dynamic_cast<const ArrayInvertedLists*>( extract_index_ivf (sub_index)->invlists); FAISS_THROW_IF_NOT_MSG (ils2, "supports only ArrayInvertedLists"); } IndexIVF *index_ivf = extract_index_ivf (index); if (remove_oldest && ils2) { for (int i = 0; i < nlist; i++) { std::vector<size_t> & sizesi = sizes[i]; size_t amount_to_remove = sizesi[0]; index_ivf->ntotal += ils2->ids[i].size() - amount_to_remove; shift_and_add (ils->ids[i], amount_to_remove, ils2->ids[i]); shift_and_add (ils->codes[i], amount_to_remove * ils->code_size, ils2->codes[i]); for (int j = 0; j + 1 < n_slice; j++) { sizesi[j] = sizesi[j + 1] - amount_to_remove; } sizesi[n_slice - 1] = ils->ids[i].size(); } } else if (ils2) { for (int i = 0; i < nlist; i++) { index_ivf->ntotal += ils2->ids[i].size(); shift_and_add (ils->ids[i], 0, ils2->ids[i]); shift_and_add (ils->codes[i], 0, ils2->codes[i]); sizes[i].push_back(ils->ids[i].size()); } n_slice++; } else if (remove_oldest) { for (int i = 0; i < nlist; i++) { size_t amount_to_remove = sizes[i][0]; index_ivf->ntotal -= amount_to_remove; remove_from_begin (ils->ids[i], amount_to_remove); remove_from_begin (ils->codes[i], amount_to_remove * ils->code_size); for (int j = 0; j + 1 < n_slice; j++) { sizes[i][j] = sizes[i][j + 1] - amount_to_remove; } sizes[i].pop_back (); } n_slice--; } else { FAISS_THROW_MSG ("nothing to do???"); } index->ntotal = index_ivf->ntotal; } // Get a subset of inverted lists [i0, i1). Works on IndexIVF's and // IndexIVF's embedded in a IndexPreTransform ArrayInvertedLists * get_invlist_range (const Index *index, long i0, long i1) { const IndexIVF *ivf = extract_index_ivf (index); FAISS_THROW_IF_NOT (0 <= i0 && i0 <= i1 && i1 <= ivf->nlist); const InvertedLists *src = ivf->invlists; ArrayInvertedLists * il = new ArrayInvertedLists(i1 - i0, src->code_size); for (long i = i0; i < i1; i++) { il->add_entries(i - i0, src->list_size(i), InvertedLists::ScopedIds (src, i).get(), InvertedLists::ScopedCodes (src, i).get()); } return il; } void set_invlist_range (Index *index, long i0, long i1, ArrayInvertedLists * src) { IndexIVF *ivf = extract_index_ivf (index); FAISS_THROW_IF_NOT (0 <= i0 && i0 <= i1 && i1 <= ivf->nlist); ArrayInvertedLists *dst = dynamic_cast<ArrayInvertedLists *>(ivf->invlists); FAISS_THROW_IF_NOT_MSG (dst, "only ArrayInvertedLists supported"); FAISS_THROW_IF_NOT (src->nlist == i1 - i0 && dst->code_size == src->code_size); size_t ntotal = index->ntotal; for (long i = i0 ; i < i1; i++) { ntotal -= dst->list_size (i); ntotal += src->list_size (i - i0); std::swap (src->codes[i - i0], dst->codes[i]); std::swap (src->ids[i - i0], dst->ids[i]); } ivf->ntotal = index->ntotal = ntotal; } void search_with_parameters (const Index *index, idx_t n, const float *x, idx_t k, float *distances, idx_t *labels, IVFSearchParameters *params, size_t *nb_dis_ptr) { FAISS_THROW_IF_NOT (params); const float *prev_x = x; ScopeDeleter<float> del; if (auto ip = dynamic_cast<const IndexPreTransform *> (index)) { x = ip->apply_chain (n, x); if (x != prev_x) { del.set(x); } index = ip->index; } std::vector<idx_t> Iq(params->nprobe * n); std::vector<float> Dq(params->nprobe * n); const IndexIVF *index_ivf = dynamic_cast<const IndexIVF *>(index); FAISS_THROW_IF_NOT (index_ivf); index_ivf->quantizer->search(n, x, params->nprobe, Dq.data(), Iq.data()); if (nb_dis_ptr) { size_t nb_dis = 0; const InvertedLists *il = index_ivf->invlists; for (idx_t i = 0; i < n * params->nprobe; i++) { if (Iq[i] >= 0) { nb_dis += il->list_size(Iq[i]); } } *nb_dis_ptr = nb_dis; } index_ivf->search_preassigned(n, x, k, Iq.data(), Dq.data(), distances, labels, false, params); } } } // namespace faiss::ivflib <commit_msg>fix ivflib (#1410)<commit_after>/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ // -*- c++ -*- #include <faiss/IVFlib.h> #include <memory> #include <faiss/IndexPreTransform.h> #include <faiss/impl/FaissAssert.h> #include <faiss/MetaIndexes.h> namespace faiss { namespace ivflib { void check_compatible_for_merge (const Index * index0, const Index * index1) { const faiss::IndexPreTransform *pt0 = dynamic_cast<const faiss::IndexPreTransform *>(index0); if (pt0) { const faiss::IndexPreTransform *pt1 = dynamic_cast<const faiss::IndexPreTransform *>(index1); FAISS_THROW_IF_NOT_MSG (pt1, "both indexes should be pretransforms"); FAISS_THROW_IF_NOT (pt0->chain.size() == pt1->chain.size()); for (int i = 0; i < pt0->chain.size(); i++) { FAISS_THROW_IF_NOT (typeid(pt0->chain[i]) == typeid(pt1->chain[i])); } index0 = pt0->index; index1 = pt1->index; } FAISS_THROW_IF_NOT (typeid(index0) == typeid(index1)); FAISS_THROW_IF_NOT (index0->d == index1->d && index0->metric_type == index1->metric_type); const faiss::IndexIVF *ivf0 = dynamic_cast<const faiss::IndexIVF *>(index0); if (ivf0) { const faiss::IndexIVF *ivf1 = dynamic_cast<const faiss::IndexIVF *>(index1); FAISS_THROW_IF_NOT (ivf1); ivf0->check_compatible_for_merge (*ivf1); } // TODO: check as thoroughfully for other index types } const IndexIVF * try_extract_index_ivf (const Index * index) { if (auto *pt = dynamic_cast<const IndexPreTransform *>(index)) { index = pt->index; } if (auto *idmap = dynamic_cast<const IndexIDMap *>(index)) { index = idmap->index; } if (auto *idmap = dynamic_cast<const IndexIDMap2 *>(index)) { index = idmap->index; } auto *ivf = dynamic_cast<const IndexIVF *>(index); return ivf; } IndexIVF * try_extract_index_ivf (Index * index) { return const_cast<IndexIVF*> (try_extract_index_ivf ((const Index*)(index))); } const IndexIVF * extract_index_ivf (const Index * index) { const IndexIVF *ivf = try_extract_index_ivf (index); FAISS_THROW_IF_NOT (ivf); return ivf; } IndexIVF * extract_index_ivf (Index * index) { return const_cast<IndexIVF*> (extract_index_ivf ((const Index*)(index))); } void merge_into(faiss::Index *index0, faiss::Index *index1, bool shift_ids) { check_compatible_for_merge (index0, index1); IndexIVF * ivf0 = extract_index_ivf (index0); IndexIVF * ivf1 = extract_index_ivf (index1); ivf0->merge_from (*ivf1, shift_ids ? ivf0->ntotal : 0); // useful for IndexPreTransform index0->ntotal = ivf0->ntotal; index1->ntotal = ivf1->ntotal; } void search_centroid(faiss::Index *index, const float* x, int n, idx_t* centroid_ids) { std::unique_ptr<float[]> del; if (auto index_pre = dynamic_cast<faiss::IndexPreTransform*>(index)) { x = index_pre->apply_chain(n, x); del.reset((float*)x); index = index_pre->index; } faiss::IndexIVF* index_ivf = dynamic_cast<faiss::IndexIVF*>(index); assert(index_ivf); index_ivf->quantizer->assign(n, x, centroid_ids); } void search_and_return_centroids(faiss::Index *index, size_t n, const float* xin, long k, float *distances, idx_t* labels, idx_t* query_centroid_ids, idx_t* result_centroid_ids) { const float *x = xin; std::unique_ptr<float []> del; if (auto index_pre = dynamic_cast<faiss::IndexPreTransform*>(index)) { x = index_pre->apply_chain(n, x); del.reset((float*)x); index = index_pre->index; } faiss::IndexIVF* index_ivf = dynamic_cast<faiss::IndexIVF*>(index); assert(index_ivf); size_t nprobe = index_ivf->nprobe; std::vector<idx_t> cent_nos (n * nprobe); std::vector<float> cent_dis (n * nprobe); index_ivf->quantizer->search( n, x, nprobe, cent_dis.data(), cent_nos.data()); if (query_centroid_ids) { for (size_t i = 0; i < n; i++) query_centroid_ids[i] = cent_nos[i * nprobe]; } index_ivf->search_preassigned (n, x, k, cent_nos.data(), cent_dis.data(), distances, labels, true); for (size_t i = 0; i < n * k; i++) { idx_t label = labels[i]; if (label < 0) { if (result_centroid_ids) result_centroid_ids[i] = -1; } else { long list_no = lo_listno (label); long list_index = lo_offset (label); if (result_centroid_ids) result_centroid_ids[i] = list_no; labels[i] = index_ivf->invlists->get_single_id(list_no, list_index); } } } SlidingIndexWindow::SlidingIndexWindow (Index *index): index (index) { n_slice = 0; IndexIVF* index_ivf = const_cast<IndexIVF*>(extract_index_ivf (index)); ils = dynamic_cast<ArrayInvertedLists *> (index_ivf->invlists); FAISS_THROW_IF_NOT_MSG (ils, "only supports indexes with ArrayInvertedLists"); nlist = ils->nlist; sizes.resize(nlist); } template<class T> static void shift_and_add (std::vector<T> & dst, size_t remove, const std::vector<T> & src) { if (remove > 0) memmove (dst.data(), dst.data() + remove, (dst.size() - remove) * sizeof (T)); size_t insert_point = dst.size() - remove; dst.resize (insert_point + src.size()); memcpy (dst.data() + insert_point, src.data (), src.size() * sizeof(T)); } template<class T> static void remove_from_begin (std::vector<T> & v, size_t remove) { if (remove > 0) v.erase (v.begin(), v.begin() + remove); } void SlidingIndexWindow::step(const Index *sub_index, bool remove_oldest) { FAISS_THROW_IF_NOT_MSG (!remove_oldest || n_slice > 0, "cannot remove slice: there is none"); const ArrayInvertedLists *ils2 = nullptr; if(sub_index) { check_compatible_for_merge (index, sub_index); ils2 = dynamic_cast<const ArrayInvertedLists*>( extract_index_ivf (sub_index)->invlists); FAISS_THROW_IF_NOT_MSG (ils2, "supports only ArrayInvertedLists"); } IndexIVF *index_ivf = extract_index_ivf (index); if (remove_oldest && ils2) { for (int i = 0; i < nlist; i++) { std::vector<size_t> & sizesi = sizes[i]; size_t amount_to_remove = sizesi[0]; index_ivf->ntotal += ils2->ids[i].size() - amount_to_remove; shift_and_add (ils->ids[i], amount_to_remove, ils2->ids[i]); shift_and_add (ils->codes[i], amount_to_remove * ils->code_size, ils2->codes[i]); for (int j = 0; j + 1 < n_slice; j++) { sizesi[j] = sizesi[j + 1] - amount_to_remove; } sizesi[n_slice - 1] = ils->ids[i].size(); } } else if (ils2) { for (int i = 0; i < nlist; i++) { index_ivf->ntotal += ils2->ids[i].size(); shift_and_add (ils->ids[i], 0, ils2->ids[i]); shift_and_add (ils->codes[i], 0, ils2->codes[i]); sizes[i].push_back(ils->ids[i].size()); } n_slice++; } else if (remove_oldest) { for (int i = 0; i < nlist; i++) { size_t amount_to_remove = sizes[i][0]; index_ivf->ntotal -= amount_to_remove; remove_from_begin (ils->ids[i], amount_to_remove); remove_from_begin (ils->codes[i], amount_to_remove * ils->code_size); for (int j = 0; j + 1 < n_slice; j++) { sizes[i][j] = sizes[i][j + 1] - amount_to_remove; } sizes[i].pop_back (); } n_slice--; } else { FAISS_THROW_MSG ("nothing to do???"); } index->ntotal = index_ivf->ntotal; } // Get a subset of inverted lists [i0, i1). Works on IndexIVF's and // IndexIVF's embedded in a IndexPreTransform ArrayInvertedLists * get_invlist_range (const Index *index, long i0, long i1) { const IndexIVF *ivf = extract_index_ivf (index); FAISS_THROW_IF_NOT (0 <= i0 && i0 <= i1 && i1 <= ivf->nlist); const InvertedLists *src = ivf->invlists; ArrayInvertedLists * il = new ArrayInvertedLists(i1 - i0, src->code_size); for (long i = i0; i < i1; i++) { il->add_entries(i - i0, src->list_size(i), InvertedLists::ScopedIds (src, i).get(), InvertedLists::ScopedCodes (src, i).get()); } return il; } void set_invlist_range (Index *index, long i0, long i1, ArrayInvertedLists * src) { IndexIVF *ivf = extract_index_ivf (index); FAISS_THROW_IF_NOT (0 <= i0 && i0 <= i1 && i1 <= ivf->nlist); ArrayInvertedLists *dst = dynamic_cast<ArrayInvertedLists *>(ivf->invlists); FAISS_THROW_IF_NOT_MSG (dst, "only ArrayInvertedLists supported"); FAISS_THROW_IF_NOT (src->nlist == i1 - i0 && dst->code_size == src->code_size); size_t ntotal = index->ntotal; for (long i = i0 ; i < i1; i++) { ntotal -= dst->list_size (i); ntotal += src->list_size (i - i0); std::swap (src->codes[i - i0], dst->codes[i]); std::swap (src->ids[i - i0], dst->ids[i]); } ivf->ntotal = index->ntotal = ntotal; } void search_with_parameters (const Index *index, idx_t n, const float *x, idx_t k, float *distances, idx_t *labels, IVFSearchParameters *params, size_t *nb_dis_ptr) { FAISS_THROW_IF_NOT (params); const float *prev_x = x; ScopeDeleter<float> del; if (auto ip = dynamic_cast<const IndexPreTransform *> (index)) { x = ip->apply_chain (n, x); if (x != prev_x) { del.set(x); } index = ip->index; } std::vector<idx_t> Iq(params->nprobe * n); std::vector<float> Dq(params->nprobe * n); const IndexIVF *index_ivf = dynamic_cast<const IndexIVF *>(index); FAISS_THROW_IF_NOT (index_ivf); index_ivf->quantizer->search(n, x, params->nprobe, Dq.data(), Iq.data()); if (nb_dis_ptr) { size_t nb_dis = 0; const InvertedLists *il = index_ivf->invlists; for (idx_t i = 0; i < n * params->nprobe; i++) { if (Iq[i] >= 0) { nb_dis += il->list_size(Iq[i]); } } *nb_dis_ptr = nb_dis; } index_ivf->search_preassigned(n, x, k, Iq.data(), Dq.data(), distances, labels, false, params); } } } // namespace faiss::ivflib <|endoftext|>
<commit_before>// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "media/midi/midi_manager_mac.h" #include <iostream> #include <string> #include "base/debug/trace_event.h" #include "base/strings/string_number_conversions.h" #include "base/strings/sys_string_conversions.h" #include <CoreAudio/HostTime.h> using base::IntToString; using base::SysCFStringRefToUTF8; using std::string; // NB: System MIDI types are pointer types in 32-bit and integer types in // 64-bit. Therefore, the initialization is the simplest one that satisfies both // (if possible). namespace media { MIDIManager* MIDIManager::Create() { return new MIDIManagerMac(); } MIDIManagerMac::MIDIManagerMac() : midi_client_(0), coremidi_input_(0), coremidi_output_(0), packet_list_(NULL), midi_packet_(NULL) { } bool MIDIManagerMac::Initialize() { TRACE_EVENT0("midi", "MIDIManagerMac::Initialize"); // CoreMIDI registration. midi_client_ = 0; OSStatus result = MIDIClientCreate( CFSTR("Google Chrome"), NULL, NULL, &midi_client_); if (result != noErr) return false; coremidi_input_ = 0; // Create input and output port. result = MIDIInputPortCreate( midi_client_, CFSTR("MIDI Input"), ReadMidiDispatch, this, &coremidi_input_); if (result != noErr) return false; result = MIDIOutputPortCreate( midi_client_, CFSTR("MIDI Output"), &coremidi_output_); if (result != noErr) return false; int destination_count = MIDIGetNumberOfDestinations(); destinations_.reserve(destination_count); for (int i = 0; i < destination_count ; i++) { MIDIEndpointRef destination = MIDIGetDestination(i); // Keep track of all destinations (known as outputs by the Web MIDI API). // Cache to avoid any possible overhead in calling MIDIGetDestination(). destinations_[i] = destination; MIDIPortInfo info = GetPortInfoFromEndpoint(destination); AddOutputPort(info); } // Open connections from all sources. int source_count = MIDIGetNumberOfSources(); for (int i = 0; i < source_count; ++i) { // Receive from all sources. MIDIEndpointRef src = MIDIGetSource(i); MIDIPortConnectSource(coremidi_input_, src, reinterpret_cast<void*>(src)); // Keep track of all sources (known as inputs in Web MIDI API terminology). source_map_[src] = i; MIDIPortInfo info = GetPortInfoFromEndpoint(src); AddInputPort(info); } // TODO(crogers): Fix the memory management here! packet_list_ = reinterpret_cast<MIDIPacketList*>(midi_buffer_); midi_packet_ = MIDIPacketListInit(packet_list_); return true; } MIDIManagerMac::~MIDIManagerMac() { if (coremidi_input_) MIDIPortDispose(coremidi_input_); if (coremidi_output_) MIDIPortDispose(coremidi_output_); } void MIDIManagerMac::ReadMidiDispatch(const MIDIPacketList* packet_list, void* read_proc_refcon, void* src_conn_refcon) { MIDIManagerMac* manager = static_cast<MIDIManagerMac*>(read_proc_refcon); #if __LP64__ MIDIEndpointRef source = reinterpret_cast<uintptr_t>(src_conn_refcon); #else MIDIEndpointRef source = static_cast<MIDIEndpointRef>(src_conn_refcon); #endif // Dispatch to class method. manager->ReadMidi(source, packet_list); } void MIDIManagerMac::ReadMidi(MIDIEndpointRef source, const MIDIPacketList* packet_list) { // Lookup the port index based on the source. SourceMap::iterator j = source_map_.find(source); if (j == source_map_.end()) return; int port_index = source_map_[source]; // Go through each packet and process separately. for(size_t i = 0; i < packet_list->numPackets; i++) { // Each packet contains MIDI data for one or more messages (like note-on). const MIDIPacket &packet = packet_list->packet[i]; double timestamp_seconds = MIDITimeStampToSeconds(packet.timeStamp); ReceiveMIDIData( port_index, packet.data, packet.length, timestamp_seconds); } } void MIDIManagerMac::SendMIDIData(MIDIManagerClient* client, int port_index, const uint8* data, size_t length, double timestamp) { // System Exclusive has already been filtered. MIDITimeStamp coremidi_timestamp = SecondsToMIDITimeStamp(timestamp); midi_packet_ = MIDIPacketListAdd( packet_list_, kMaxPacketListSize, midi_packet_, coremidi_timestamp, length, data); // Lookup the destination based on the port index. // TODO(crogers): re-factor |port_index| to use unsigned // to avoid the need for this check. if (port_index < 0 || static_cast<size_t>(port_index) >= destinations_.size()) return; MIDIEndpointRef destination = destinations_[port_index]; MIDISend(coremidi_output_, destination, packet_list_); // Re-initialize for next time. midi_packet_ = MIDIPacketListInit(packet_list_); client->AccumulateMIDIBytesSent(length); } MIDIPortInfo MIDIManagerMac::GetPortInfoFromEndpoint( MIDIEndpointRef endpoint) { SInt32 id_number = 0; MIDIObjectGetIntegerProperty(endpoint, kMIDIPropertyUniqueID, &id_number); string id = IntToString(id_number); CFStringRef manufacturer_ref = NULL; MIDIObjectGetStringProperty( endpoint, kMIDIPropertyManufacturer, &manufacturer_ref); string manufacturer = SysCFStringRefToUTF8(manufacturer_ref); CFStringRef name_ref = NULL; MIDIObjectGetStringProperty(endpoint, kMIDIPropertyName, &name_ref); string name = SysCFStringRefToUTF8(name_ref); SInt32 version_number = 0; MIDIObjectGetIntegerProperty( endpoint, kMIDIPropertyDriverVersion, &version_number); string version = IntToString(version_number); return MIDIPortInfo(id, manufacturer, name, version); } double MIDIManagerMac::MIDITimeStampToSeconds(MIDITimeStamp timestamp) { UInt64 nanoseconds = AudioConvertHostTimeToNanos(timestamp); return static_cast<double>(nanoseconds) / 1.0e9; } MIDITimeStamp MIDIManagerMac::SecondsToMIDITimeStamp(double seconds) { UInt64 nanos = UInt64(seconds * 1.0e9); return AudioConvertNanosToHostTime(nanos); } } // namespace media <commit_msg>Web MIDI: bug fix to make send operations work<commit_after>// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "media/midi/midi_manager_mac.h" #include <iostream> #include <string> #include "base/debug/trace_event.h" #include "base/strings/string_number_conversions.h" #include "base/strings/sys_string_conversions.h" #include <CoreAudio/HostTime.h> using base::IntToString; using base::SysCFStringRefToUTF8; using std::string; // NB: System MIDI types are pointer types in 32-bit and integer types in // 64-bit. Therefore, the initialization is the simplest one that satisfies both // (if possible). namespace media { MIDIManager* MIDIManager::Create() { return new MIDIManagerMac(); } MIDIManagerMac::MIDIManagerMac() : midi_client_(0), coremidi_input_(0), coremidi_output_(0), packet_list_(NULL), midi_packet_(NULL) { } bool MIDIManagerMac::Initialize() { TRACE_EVENT0("midi", "MIDIManagerMac::Initialize"); // CoreMIDI registration. midi_client_ = 0; OSStatus result = MIDIClientCreate( CFSTR("Google Chrome"), NULL, NULL, &midi_client_); if (result != noErr) return false; coremidi_input_ = 0; // Create input and output port. result = MIDIInputPortCreate( midi_client_, CFSTR("MIDI Input"), ReadMidiDispatch, this, &coremidi_input_); if (result != noErr) return false; result = MIDIOutputPortCreate( midi_client_, CFSTR("MIDI Output"), &coremidi_output_); if (result != noErr) return false; int destination_count = MIDIGetNumberOfDestinations(); destinations_.resize(destination_count); for (int i = 0; i < destination_count ; i++) { MIDIEndpointRef destination = MIDIGetDestination(i); // Keep track of all destinations (known as outputs by the Web MIDI API). // Cache to avoid any possible overhead in calling MIDIGetDestination(). destinations_[i] = destination; MIDIPortInfo info = GetPortInfoFromEndpoint(destination); AddOutputPort(info); } // Open connections from all sources. int source_count = MIDIGetNumberOfSources(); for (int i = 0; i < source_count; ++i) { // Receive from all sources. MIDIEndpointRef src = MIDIGetSource(i); MIDIPortConnectSource(coremidi_input_, src, reinterpret_cast<void*>(src)); // Keep track of all sources (known as inputs in Web MIDI API terminology). source_map_[src] = i; MIDIPortInfo info = GetPortInfoFromEndpoint(src); AddInputPort(info); } // TODO(crogers): Fix the memory management here! packet_list_ = reinterpret_cast<MIDIPacketList*>(midi_buffer_); midi_packet_ = MIDIPacketListInit(packet_list_); return true; } MIDIManagerMac::~MIDIManagerMac() { if (coremidi_input_) MIDIPortDispose(coremidi_input_); if (coremidi_output_) MIDIPortDispose(coremidi_output_); } void MIDIManagerMac::ReadMidiDispatch(const MIDIPacketList* packet_list, void* read_proc_refcon, void* src_conn_refcon) { MIDIManagerMac* manager = static_cast<MIDIManagerMac*>(read_proc_refcon); #if __LP64__ MIDIEndpointRef source = reinterpret_cast<uintptr_t>(src_conn_refcon); #else MIDIEndpointRef source = static_cast<MIDIEndpointRef>(src_conn_refcon); #endif // Dispatch to class method. manager->ReadMidi(source, packet_list); } void MIDIManagerMac::ReadMidi(MIDIEndpointRef source, const MIDIPacketList* packet_list) { // Lookup the port index based on the source. SourceMap::iterator j = source_map_.find(source); if (j == source_map_.end()) return; int port_index = source_map_[source]; // Go through each packet and process separately. for(size_t i = 0; i < packet_list->numPackets; i++) { // Each packet contains MIDI data for one or more messages (like note-on). const MIDIPacket &packet = packet_list->packet[i]; double timestamp_seconds = MIDITimeStampToSeconds(packet.timeStamp); ReceiveMIDIData( port_index, packet.data, packet.length, timestamp_seconds); } } void MIDIManagerMac::SendMIDIData(MIDIManagerClient* client, int port_index, const uint8* data, size_t length, double timestamp) { // System Exclusive has already been filtered. MIDITimeStamp coremidi_timestamp = SecondsToMIDITimeStamp(timestamp); midi_packet_ = MIDIPacketListAdd( packet_list_, kMaxPacketListSize, midi_packet_, coremidi_timestamp, length, data); // Lookup the destination based on the port index. // TODO(crogers): re-factor |port_index| to use unsigned // to avoid the need for this check. if (port_index < 0 || static_cast<size_t>(port_index) >= destinations_.size()) return; MIDIEndpointRef destination = destinations_[port_index]; MIDISend(coremidi_output_, destination, packet_list_); // Re-initialize for next time. midi_packet_ = MIDIPacketListInit(packet_list_); client->AccumulateMIDIBytesSent(length); } MIDIPortInfo MIDIManagerMac::GetPortInfoFromEndpoint( MIDIEndpointRef endpoint) { SInt32 id_number = 0; MIDIObjectGetIntegerProperty(endpoint, kMIDIPropertyUniqueID, &id_number); string id = IntToString(id_number); CFStringRef manufacturer_ref = NULL; MIDIObjectGetStringProperty( endpoint, kMIDIPropertyManufacturer, &manufacturer_ref); string manufacturer = SysCFStringRefToUTF8(manufacturer_ref); CFStringRef name_ref = NULL; MIDIObjectGetStringProperty(endpoint, kMIDIPropertyName, &name_ref); string name = SysCFStringRefToUTF8(name_ref); SInt32 version_number = 0; MIDIObjectGetIntegerProperty( endpoint, kMIDIPropertyDriverVersion, &version_number); string version = IntToString(version_number); return MIDIPortInfo(id, manufacturer, name, version); } double MIDIManagerMac::MIDITimeStampToSeconds(MIDITimeStamp timestamp) { UInt64 nanoseconds = AudioConvertHostTimeToNanos(timestamp); return static_cast<double>(nanoseconds) / 1.0e9; } MIDITimeStamp MIDIManagerMac::SecondsToMIDITimeStamp(double seconds) { UInt64 nanos = UInt64(seconds * 1.0e9); return AudioConvertNanosToHostTime(nanos); } } // namespace media <|endoftext|>
<commit_before>//===-- CodeGen/AsmPrinter/DwarfException.cpp - Dwarf Exception Impl ------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file contains support for writing DWARF exception info into asm files. // //===----------------------------------------------------------------------===// #include "DwarfException.h" #include "llvm/Module.h" #include "llvm/CodeGen/AsmPrinter.h" #include "llvm/CodeGen/MachineModuleInfo.h" #include "llvm/CodeGen/MachineFrameInfo.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/MachineLocation.h" #include "llvm/MC/MCAsmInfo.h" #include "llvm/MC/MCContext.h" #include "llvm/MC/MCExpr.h" #include "llvm/MC/MCSection.h" #include "llvm/MC/MCStreamer.h" #include "llvm/MC/MCSymbol.h" #include "llvm/Target/Mangler.h" #include "llvm/Target/TargetData.h" #include "llvm/Target/TargetFrameLowering.h" #include "llvm/Target/TargetLoweringObjectFile.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetOptions.h" #include "llvm/Target/TargetRegisterInfo.h" #include "llvm/Support/Dwarf.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/FormattedStream.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/Twine.h" using namespace llvm; DwarfCFIException::DwarfCFIException(AsmPrinter *A) : DwarfException(A), shouldEmitPersonality(false), shouldEmitLSDA(false), shouldEmitMoves(false) {} DwarfCFIException::~DwarfCFIException() {} /// EndModule - Emit all exception information that should come after the /// content. void DwarfCFIException::EndModule() { if (moveTypeModule == AsmPrinter::CFI_M_Debug) Asm->OutStreamer.EmitCFISections(false, true); if (!Asm->MAI->isExceptionHandlingDwarf()) return; const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering(); unsigned PerEncoding = TLOF.getPersonalityEncoding(); if ((PerEncoding & 0x70) != dwarf::DW_EH_PE_pcrel) return; // Emit references to all used personality functions bool AtLeastOne = false; const std::vector<const Function*> &Personalities = MMI->getPersonalities(); for (size_t i = 0, e = Personalities.size(); i != e; ++i) { if (!Personalities[i]) continue; MCSymbol *Sym = Asm->Mang->getSymbol(Personalities[i]); TLOF.emitPersonalityValue(Asm->OutStreamer, Asm->TM, Sym); AtLeastOne = true; } if (AtLeastOne && !TLOF.isFunctionEHFrameSymbolPrivate()) { // This is a temporary hack to keep sections in the same order they // were before. This lets us produce bit identical outputs while // transitioning to CFI. Asm->OutStreamer.SwitchSection(TLOF.getEHFrameSection()); } } /// BeginFunction - Gather pre-function exception information. Assumes it's /// being emitted immediately after the function entry point. void DwarfCFIException::BeginFunction(const MachineFunction *MF) { shouldEmitMoves = shouldEmitPersonality = shouldEmitLSDA = false; // If any landing pads survive, we need an EH table. bool hasLandingPads = !MMI->getLandingPads().empty(); // See if we need frame move info. AsmPrinter::CFIMoveType MoveType = Asm->needsCFIMoves(); if (MoveType == AsmPrinter::CFI_M_EH || (MoveType == AsmPrinter::CFI_M_Debug && moveTypeModule == AsmPrinter::CFI_M_None)) moveTypeModule = MoveType; shouldEmitMoves = MoveType != AsmPrinter::CFI_M_None; const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering(); unsigned PerEncoding = TLOF.getPersonalityEncoding(); const Function *Per = MMI->getPersonalities()[MMI->getPersonalityIndex()]; shouldEmitPersonality = hasLandingPads && PerEncoding != dwarf::DW_EH_PE_omit && Per; unsigned LSDAEncoding = TLOF.getLSDAEncoding(); shouldEmitLSDA = shouldEmitPersonality && LSDAEncoding != dwarf::DW_EH_PE_omit; if (!shouldEmitPersonality && !shouldEmitMoves) return; Asm->OutStreamer.EmitCFIStartProc(); // Indicate personality routine, if any. if (!shouldEmitPersonality) return; const MCSymbol *Sym = TLOF.getCFIPersonalitySymbol(Per, Asm->Mang, MMI); Asm->OutStreamer.EmitCFIPersonality(Sym, PerEncoding); Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("eh_func_begin", Asm->getFunctionNumber())); // Provide LSDA information. if (!shouldEmitLSDA) return; Asm->OutStreamer.EmitCFILsda(Asm->GetTempSymbol("exception", Asm->getFunctionNumber()), LSDAEncoding); } /// EndFunction - Gather and emit post-function exception information. /// void DwarfCFIException::EndFunction() { if (!shouldEmitPersonality && !shouldEmitMoves) return; Asm->OutStreamer.EmitCFIEndProc(); Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("eh_func_end", Asm->getFunctionNumber())); // Map all labels and get rid of any dead landing pads. MMI->TidyLandingPads(); if (shouldEmitPersonality) EmitExceptionTable(); } <commit_msg>Initialize moveTypeModule.<commit_after>//===-- CodeGen/AsmPrinter/DwarfException.cpp - Dwarf Exception Impl ------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file contains support for writing DWARF exception info into asm files. // //===----------------------------------------------------------------------===// #include "DwarfException.h" #include "llvm/Module.h" #include "llvm/CodeGen/AsmPrinter.h" #include "llvm/CodeGen/MachineModuleInfo.h" #include "llvm/CodeGen/MachineFrameInfo.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/MachineLocation.h" #include "llvm/MC/MCAsmInfo.h" #include "llvm/MC/MCContext.h" #include "llvm/MC/MCExpr.h" #include "llvm/MC/MCSection.h" #include "llvm/MC/MCStreamer.h" #include "llvm/MC/MCSymbol.h" #include "llvm/Target/Mangler.h" #include "llvm/Target/TargetData.h" #include "llvm/Target/TargetFrameLowering.h" #include "llvm/Target/TargetLoweringObjectFile.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetOptions.h" #include "llvm/Target/TargetRegisterInfo.h" #include "llvm/Support/Dwarf.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/FormattedStream.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/Twine.h" using namespace llvm; DwarfCFIException::DwarfCFIException(AsmPrinter *A) : DwarfException(A), shouldEmitPersonality(false), shouldEmitLSDA(false), shouldEmitMoves(false), moveTypeModule(AsmPrinter::CFI_M_None) {} DwarfCFIException::~DwarfCFIException() {} /// EndModule - Emit all exception information that should come after the /// content. void DwarfCFIException::EndModule() { if (moveTypeModule == AsmPrinter::CFI_M_Debug) Asm->OutStreamer.EmitCFISections(false, true); if (!Asm->MAI->isExceptionHandlingDwarf()) return; const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering(); unsigned PerEncoding = TLOF.getPersonalityEncoding(); if ((PerEncoding & 0x70) != dwarf::DW_EH_PE_pcrel) return; // Emit references to all used personality functions bool AtLeastOne = false; const std::vector<const Function*> &Personalities = MMI->getPersonalities(); for (size_t i = 0, e = Personalities.size(); i != e; ++i) { if (!Personalities[i]) continue; MCSymbol *Sym = Asm->Mang->getSymbol(Personalities[i]); TLOF.emitPersonalityValue(Asm->OutStreamer, Asm->TM, Sym); AtLeastOne = true; } if (AtLeastOne && !TLOF.isFunctionEHFrameSymbolPrivate()) { // This is a temporary hack to keep sections in the same order they // were before. This lets us produce bit identical outputs while // transitioning to CFI. Asm->OutStreamer.SwitchSection(TLOF.getEHFrameSection()); } } /// BeginFunction - Gather pre-function exception information. Assumes it's /// being emitted immediately after the function entry point. void DwarfCFIException::BeginFunction(const MachineFunction *MF) { shouldEmitMoves = shouldEmitPersonality = shouldEmitLSDA = false; // If any landing pads survive, we need an EH table. bool hasLandingPads = !MMI->getLandingPads().empty(); // See if we need frame move info. AsmPrinter::CFIMoveType MoveType = Asm->needsCFIMoves(); if (MoveType == AsmPrinter::CFI_M_EH || (MoveType == AsmPrinter::CFI_M_Debug && moveTypeModule == AsmPrinter::CFI_M_None)) moveTypeModule = MoveType; shouldEmitMoves = MoveType != AsmPrinter::CFI_M_None; const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering(); unsigned PerEncoding = TLOF.getPersonalityEncoding(); const Function *Per = MMI->getPersonalities()[MMI->getPersonalityIndex()]; shouldEmitPersonality = hasLandingPads && PerEncoding != dwarf::DW_EH_PE_omit && Per; unsigned LSDAEncoding = TLOF.getLSDAEncoding(); shouldEmitLSDA = shouldEmitPersonality && LSDAEncoding != dwarf::DW_EH_PE_omit; if (!shouldEmitPersonality && !shouldEmitMoves) return; Asm->OutStreamer.EmitCFIStartProc(); // Indicate personality routine, if any. if (!shouldEmitPersonality) return; const MCSymbol *Sym = TLOF.getCFIPersonalitySymbol(Per, Asm->Mang, MMI); Asm->OutStreamer.EmitCFIPersonality(Sym, PerEncoding); Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("eh_func_begin", Asm->getFunctionNumber())); // Provide LSDA information. if (!shouldEmitLSDA) return; Asm->OutStreamer.EmitCFILsda(Asm->GetTempSymbol("exception", Asm->getFunctionNumber()), LSDAEncoding); } /// EndFunction - Gather and emit post-function exception information. /// void DwarfCFIException::EndFunction() { if (!shouldEmitPersonality && !shouldEmitMoves) return; Asm->OutStreamer.EmitCFIEndProc(); Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("eh_func_end", Asm->getFunctionNumber())); // Map all labels and get rid of any dead landing pads. MMI->TidyLandingPads(); if (shouldEmitPersonality) EmitExceptionTable(); } <|endoftext|>
<commit_before>// // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // #include "swift/AST/Builtins.h" #include "swift/SIL/MemAccessUtils.h" #include "swift/SIL/OwnershipUtils.h" #include "swift/SIL/SILBasicBlock.h" #include "swift/SILOptimizer/Utils/CanonicalizeBorrowScope.h" #include "swift/SILOptimizer/Utils/InstOptUtils.h" #include "swift/SILOptimizer/Utils/InstructionDeleter.h" #define DEBUG_TYPE "copy-propagation" using namespace swift; //===----------------------------------------------------------------------===// // MARK: ShrinkBorrowScope //===----------------------------------------------------------------------===// class ShrinkBorrowScope { // The instruction that begins this borrow scope. BeginBorrowInst *introducer; InstructionDeleter &deleter; SmallVectorImpl<CopyValueInst *> &modifiedCopyValueInsts; /// Instructions which are users of the simple (i.e. not reborrowed) extended /// i.e. copied lifetime of the introducer. SmallPtrSet<SILInstruction *, 16> users; /// Deinit barriers that obstruct hoisting end_borrow instructions. llvm::SmallVector<std::pair<SILBasicBlock *, SILInstruction *>> barrierInstructions; /// Blocks above which the borrow scope cannot be hoisted. /// /// Consequently, these blocks must begin with end_borrow %borrow. /// /// Note: These blocks aren't barrier blocks. Rather the borrow scope is /// barred from being hoisted out of them. That could happen because /// one of its predecessors is a barrier block (i.e. has a successor /// which is live) or because one of its predecessors has a terminator /// which is itself a deinit barrier. SmallPtrSet<SILBasicBlock *, 8> barredBlocks; // The list of blocks to look for new points at which to insert end_borrows // in. A block must not be processed if all of its successors have not yet // been. For that reason, it is necessary to allow the same block to be // visited multiple times, at most once for each successor. SmallVector<SILBasicBlock *, 8> worklist; // The instructions from which the shrinking starts, the scope ending // instructions, keyed off the block in which they appear. llvm::SmallDenseMap<SILBasicBlock *, SILInstruction *> startingInstructions; // The end _borrow instructions for this borrow scope that existed before // ShrinkBorrowScope ran and which were not modified. llvm::SmallPtrSet<SILInstruction *, 8> reusedEndBorrowInsts; // Whether ShrinkBorrowScope made any changes to the function. // // It could have made one of the following sorts of changes: // - deleted an end_borrow // - created an end_borrow // - rewrote the operand of an instruction // - ApplySite // - begin_borrow // - copy_value bool madeChange; public: ShrinkBorrowScope(BeginBorrowInst *bbi, InstructionDeleter &deleter, SmallVectorImpl<CopyValueInst *> &modifiedCopyValueInsts) : introducer(bbi), deleter(deleter), modifiedCopyValueInsts(modifiedCopyValueInsts), madeChange(false) {} bool run(); bool populateUsers(); bool initializeWorklist(); void findBarriers(); bool rewrite(); bool createEndBorrow(SILInstruction *insertionPoint); bool isBarrierApply(SILInstruction *instruction) { // For now, treat every apply (that doesn't use the borrowed value) as a // barrier. return isa<ApplySite>(instruction); } bool mayAccessPointer(SILInstruction *instruction) { if (!instruction->mayReadOrWriteMemory()) return false; bool fail = false; visitAccessedAddress(instruction, [&fail](Operand *operand) { auto accessStorage = AccessStorage::compute(operand->get()); if (accessStorage.getKind() != AccessRepresentation::Kind::Unidentified) fail = true; }); return fail; } bool mayLoadWeakOrUnowned(SILInstruction *instruction) { // TODO: It is possible to do better here by looking at the address that is // being loaded. return isa<LoadWeakInst>(instruction) || isa<LoadUnownedInst>(instruction); } bool isDeinitBarrier(SILInstruction *instruction) { return isBarrierApply(instruction) || instruction->maySynchronize() || mayAccessPointer(instruction) || mayLoadWeakOrUnowned(instruction); } bool canReplaceValueWithBorrowee(SILValue value) { while (true) { auto *instruction = value.getDefiningInstruction(); if (!instruction) return false; if (auto *cvi = dyn_cast<CopyValueInst>(instruction)) { value = cvi->getOperand(); continue; } else if (auto *bbi = dyn_cast<BeginBorrowInst>(instruction)) { if (bbi == introducer) { return true; } } return false; } } bool canHoistOverInstruction(SILInstruction *instruction) { return tryHoistOverInstruction(instruction, /*rewrite=*/false); } bool tryHoistOverInstruction(SILInstruction *instruction, bool rewrite = true) { if (instruction == introducer) { return false; } if (users.contains(instruction)) { if (auto *bbi = dyn_cast<BeginBorrowInst>(instruction)) { if (bbi->isLexical() && canReplaceValueWithBorrowee(bbi->getOperand())) { if (rewrite) { auto borrowee = introducer->getOperand(); bbi->setOperand(borrowee); madeChange = true; } return true; } } else if (auto *cvi = dyn_cast<CopyValueInst>(instruction)) { if (canReplaceValueWithBorrowee(cvi->getOperand())) { if (rewrite) { auto borrowee = introducer->getOperand(); cvi->setOperand(borrowee); madeChange = true; modifiedCopyValueInsts.push_back(cvi); } return true; } } return false; } return !isDeinitBarrier(instruction); } }; //===----------------------------------------------------------------------===// // MARK: Rewrite borrow scopes //===----------------------------------------------------------------------===// bool ShrinkBorrowScope::run() { if (!BorrowedValue(introducer).isLocalScope()) return false; if (!populateUsers()) return false; if (!initializeWorklist()) return false; findBarriers(); madeChange |= rewrite(); return madeChange; } bool ShrinkBorrowScope::populateUsers() { SmallVector<Operand *, 16> uses; if (!findExtendedUsesOfSimpleBorrowedValue(BorrowedValue(introducer), &uses)) { // If the value produced by begin_borrow escapes, don't shrink the borrow // scope. return false; } for (auto *use : uses) { auto *user = use->getUser(); users.insert(user); } return true; } bool ShrinkBorrowScope::initializeWorklist() { llvm::SmallVector<SILInstruction *, 16> scopeEndingInsts; BorrowedValue(introducer).getLocalScopeEndingInstructions(scopeEndingInsts); // Form a map of the scopeEndingInsts, keyed off the block they occur in. If // a scope ending instruction is not an end_borrow, bail out. for (auto *instruction : scopeEndingInsts) { if (!isa<EndBorrowInst>(instruction)) return false; auto *block = instruction->getParent(); worklist.push_back(block); startingInstructions[block] = instruction; } return true; } void ShrinkBorrowScope::findBarriers() { // Walk the cfg backwards from the blocks containing scope ending // instructions, visiting only the initial blocks (which contained those // instructions) and those blocks all of whose successors have already been // visited. // // TODO: Handle loops. // Blocks to the top of which the borrow scope has been shrunk. SmallPtrSet<SILBasicBlock *, 8> deadBlocks; auto hasOnlyDeadSuccessors = [&deadBlocks](SILBasicBlock *block) -> bool { return llvm::all_of(block->getSuccessorBlocks(), [=](auto *successor) { return deadBlocks.contains(successor); }); }; while (!worklist.empty()) { auto *block = worklist.pop_back_val(); auto *startingInstruction = startingInstructions.lookup(block); if (!startingInstruction && !hasOnlyDeadSuccessors(block)) { continue; } for (auto *successor : block->getSuccessorBlocks()) { barredBlocks.erase(successor); } // We either have processed all successors of block or else it is a block // which contained one of the original scope-ending instructions. Scan the // block backwards, looking for the first deinit barrier. If we've visited // all successors, start scanning from the terminator. If the block // contained an original scope-ending instruction, start scanning from it. SILInstruction *instruction = startingInstruction ? startingInstruction : block->getTerminator(); if (!startingInstruction) { // That there's no starting instruction means that this this block did not // contain an original introducer. It was added to the worklist later. // At that time, it was checked that this block (along with all that // successor's other predecessors) had a terminator over which the borrow // scope could be shrunk. Shrink it now. bool hoisted = tryHoistOverInstruction(block->getTerminator()); assert(hoisted); (void)hoisted; } SILInstruction *barrier = nullptr; while ((instruction = instruction->getPreviousInstruction())) { if (!tryHoistOverInstruction(instruction)) { barrier = instruction; break; } } if (barrier) { barrierInstructions.push_back({block, barrier}); } else { deadBlocks.insert(block); barredBlocks.insert(block); // If any of block's predecessor has a terminator over which the scope // can't be shrunk, the scope is barred from shrinking out of this block. if (llvm::all_of(block->getPredecessorBlocks(), [&](auto *block) { return canHoistOverInstruction(block->getTerminator()); })) { // Otherwise, add all predecessors to the worklist and attempt to shrink // the borrow scope through them. for (auto *predecessor : block->getPredecessorBlocks()) { worklist.push_back(predecessor); } } } } } bool ShrinkBorrowScope::rewrite() { bool createdBorrow = false; // Insert the new end_borrow instructions that occur after deinit barriers. for (auto pair : barrierInstructions) { auto *insertionPoint = pair.second->getNextInstruction(); createdBorrow |= createEndBorrow(insertionPoint); } // Insert the new end_borrow instructions that occur at the beginning of // blocks which we couldn't hoist out of. for (auto *block : barredBlocks) { auto *insertionPoint = &*block->begin(); createdBorrow |= createEndBorrow(insertionPoint); } if (createdBorrow) { // Remove all the original end_borrow instructions. for (auto pair : startingInstructions) { if (reusedEndBorrowInsts.contains(pair.second)) { continue; } deleter.forceDelete(pair.getSecond()); } } return createdBorrow; } bool ShrinkBorrowScope::createEndBorrow(SILInstruction *insertionPoint) { if (auto *ebi = dyn_cast<EndBorrowInst>(insertionPoint)) { llvm::SmallDenseMap<SILBasicBlock *, SILInstruction *>::iterator location; if ((location = llvm::find_if(startingInstructions, [&](auto pair) -> bool { return pair.second == insertionPoint; })) != startingInstructions.end()) { reusedEndBorrowInsts.insert(location->second); return false; } } auto builder = SILBuilderWithScope(insertionPoint); builder.createEndBorrow( RegularLocation::getAutoGeneratedLocation(insertionPoint->getLoc()), introducer); return true; } bool swift::shrinkBorrowScope( BeginBorrowInst *bbi, InstructionDeleter &deleter, SmallVectorImpl<CopyValueInst *> &modifiedCopyValueInsts) { ShrinkBorrowScope borrowShrinker(bbi, deleter, modifiedCopyValueInsts); return borrowShrinker.run(); } <commit_msg>[ShrinkBorrowScope] Used extract deinit barrier implementation.<commit_after>// // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // #include "swift/AST/Builtins.h" #include "swift/SIL/MemAccessUtils.h" #include "swift/SIL/OwnershipUtils.h" #include "swift/SIL/SILBasicBlock.h" #include "swift/SILOptimizer/Utils/CanonicalizeBorrowScope.h" #include "swift/SILOptimizer/Utils/InstOptUtils.h" #include "swift/SILOptimizer/Utils/InstructionDeleter.h" #define DEBUG_TYPE "copy-propagation" using namespace swift; //===----------------------------------------------------------------------===// // MARK: ShrinkBorrowScope //===----------------------------------------------------------------------===// class ShrinkBorrowScope { // The instruction that begins this borrow scope. BeginBorrowInst *introducer; InstructionDeleter &deleter; SmallVectorImpl<CopyValueInst *> &modifiedCopyValueInsts; /// Instructions which are users of the simple (i.e. not reborrowed) extended /// i.e. copied lifetime of the introducer. SmallPtrSet<SILInstruction *, 16> users; /// Deinit barriers that obstruct hoisting end_borrow instructions. llvm::SmallVector<std::pair<SILBasicBlock *, SILInstruction *>> barrierInstructions; /// Blocks above which the borrow scope cannot be hoisted. /// /// Consequently, these blocks must begin with end_borrow %borrow. /// /// Note: These blocks aren't barrier blocks. Rather the borrow scope is /// barred from being hoisted out of them. That could happen because /// one of its predecessors is a barrier block (i.e. has a successor /// which is live) or because one of its predecessors has a terminator /// which is itself a deinit barrier. SmallPtrSet<SILBasicBlock *, 8> barredBlocks; // The list of blocks to look for new points at which to insert end_borrows // in. A block must not be processed if all of its successors have not yet // been. For that reason, it is necessary to allow the same block to be // visited multiple times, at most once for each successor. SmallVector<SILBasicBlock *, 8> worklist; // The instructions from which the shrinking starts, the scope ending // instructions, keyed off the block in which they appear. llvm::SmallDenseMap<SILBasicBlock *, SILInstruction *> startingInstructions; // The end _borrow instructions for this borrow scope that existed before // ShrinkBorrowScope ran and which were not modified. llvm::SmallPtrSet<SILInstruction *, 8> reusedEndBorrowInsts; // Whether ShrinkBorrowScope made any changes to the function. // // It could have made one of the following sorts of changes: // - deleted an end_borrow // - created an end_borrow // - rewrote the operand of an instruction // - ApplySite // - begin_borrow // - copy_value bool madeChange; public: ShrinkBorrowScope(BeginBorrowInst *bbi, InstructionDeleter &deleter, SmallVectorImpl<CopyValueInst *> &modifiedCopyValueInsts) : introducer(bbi), deleter(deleter), modifiedCopyValueInsts(modifiedCopyValueInsts), madeChange(false) {} bool run(); bool populateUsers(); bool initializeWorklist(); void findBarriers(); bool rewrite(); bool createEndBorrow(SILInstruction *insertionPoint); bool canReplaceValueWithBorrowee(SILValue value) { while (true) { auto *instruction = value.getDefiningInstruction(); if (!instruction) return false; if (auto *cvi = dyn_cast<CopyValueInst>(instruction)) { value = cvi->getOperand(); continue; } else if (auto *bbi = dyn_cast<BeginBorrowInst>(instruction)) { if (bbi == introducer) { return true; } } return false; } } bool canHoistOverInstruction(SILInstruction *instruction) { return tryHoistOverInstruction(instruction, /*rewrite=*/false); } bool tryHoistOverInstruction(SILInstruction *instruction, bool rewrite = true) { if (instruction == introducer) { return false; } if (users.contains(instruction)) { if (auto *bbi = dyn_cast<BeginBorrowInst>(instruction)) { if (bbi->isLexical() && canReplaceValueWithBorrowee(bbi->getOperand())) { if (rewrite) { auto borrowee = introducer->getOperand(); bbi->setOperand(borrowee); madeChange = true; } return true; } } else if (auto *cvi = dyn_cast<CopyValueInst>(instruction)) { if (canReplaceValueWithBorrowee(cvi->getOperand())) { if (rewrite) { auto borrowee = introducer->getOperand(); cvi->setOperand(borrowee); madeChange = true; modifiedCopyValueInsts.push_back(cvi); } return true; } } return false; } return !isDeinitBarrier(instruction); } }; //===----------------------------------------------------------------------===// // MARK: Rewrite borrow scopes //===----------------------------------------------------------------------===// bool ShrinkBorrowScope::run() { if (!BorrowedValue(introducer).isLocalScope()) return false; if (!populateUsers()) return false; if (!initializeWorklist()) return false; findBarriers(); madeChange |= rewrite(); return madeChange; } bool ShrinkBorrowScope::populateUsers() { SmallVector<Operand *, 16> uses; if (!findExtendedUsesOfSimpleBorrowedValue(BorrowedValue(introducer), &uses)) { // If the value produced by begin_borrow escapes, don't shrink the borrow // scope. return false; } for (auto *use : uses) { auto *user = use->getUser(); users.insert(user); } return true; } bool ShrinkBorrowScope::initializeWorklist() { llvm::SmallVector<SILInstruction *, 16> scopeEndingInsts; BorrowedValue(introducer).getLocalScopeEndingInstructions(scopeEndingInsts); // Form a map of the scopeEndingInsts, keyed off the block they occur in. If // a scope ending instruction is not an end_borrow, bail out. for (auto *instruction : scopeEndingInsts) { if (!isa<EndBorrowInst>(instruction)) return false; auto *block = instruction->getParent(); worklist.push_back(block); startingInstructions[block] = instruction; } return true; } void ShrinkBorrowScope::findBarriers() { // Walk the cfg backwards from the blocks containing scope ending // instructions, visiting only the initial blocks (which contained those // instructions) and those blocks all of whose successors have already been // visited. // // TODO: Handle loops. // Blocks to the top of which the borrow scope has been shrunk. SmallPtrSet<SILBasicBlock *, 8> deadBlocks; auto hasOnlyDeadSuccessors = [&deadBlocks](SILBasicBlock *block) -> bool { return llvm::all_of(block->getSuccessorBlocks(), [=](auto *successor) { return deadBlocks.contains(successor); }); }; while (!worklist.empty()) { auto *block = worklist.pop_back_val(); auto *startingInstruction = startingInstructions.lookup(block); if (!startingInstruction && !hasOnlyDeadSuccessors(block)) { continue; } for (auto *successor : block->getSuccessorBlocks()) { barredBlocks.erase(successor); } // We either have processed all successors of block or else it is a block // which contained one of the original scope-ending instructions. Scan the // block backwards, looking for the first deinit barrier. If we've visited // all successors, start scanning from the terminator. If the block // contained an original scope-ending instruction, start scanning from it. SILInstruction *instruction = startingInstruction ? startingInstruction : block->getTerminator(); if (!startingInstruction) { // That there's no starting instruction means that this this block did not // contain an original introducer. It was added to the worklist later. // At that time, it was checked that this block (along with all that // successor's other predecessors) had a terminator over which the borrow // scope could be shrunk. Shrink it now. bool hoisted = tryHoistOverInstruction(block->getTerminator()); assert(hoisted); (void)hoisted; } SILInstruction *barrier = nullptr; while ((instruction = instruction->getPreviousInstruction())) { if (!tryHoistOverInstruction(instruction)) { barrier = instruction; break; } } if (barrier) { barrierInstructions.push_back({block, barrier}); } else { deadBlocks.insert(block); barredBlocks.insert(block); // If any of block's predecessor has a terminator over which the scope // can't be shrunk, the scope is barred from shrinking out of this block. if (llvm::all_of(block->getPredecessorBlocks(), [&](auto *block) { return canHoistOverInstruction(block->getTerminator()); })) { // Otherwise, add all predecessors to the worklist and attempt to shrink // the borrow scope through them. for (auto *predecessor : block->getPredecessorBlocks()) { worklist.push_back(predecessor); } } } } } bool ShrinkBorrowScope::rewrite() { bool createdBorrow = false; // Insert the new end_borrow instructions that occur after deinit barriers. for (auto pair : barrierInstructions) { auto *insertionPoint = pair.second->getNextInstruction(); createdBorrow |= createEndBorrow(insertionPoint); } // Insert the new end_borrow instructions that occur at the beginning of // blocks which we couldn't hoist out of. for (auto *block : barredBlocks) { auto *insertionPoint = &*block->begin(); createdBorrow |= createEndBorrow(insertionPoint); } if (createdBorrow) { // Remove all the original end_borrow instructions. for (auto pair : startingInstructions) { if (reusedEndBorrowInsts.contains(pair.second)) { continue; } deleter.forceDelete(pair.getSecond()); } } return createdBorrow; } bool ShrinkBorrowScope::createEndBorrow(SILInstruction *insertionPoint) { if (auto *ebi = dyn_cast<EndBorrowInst>(insertionPoint)) { llvm::SmallDenseMap<SILBasicBlock *, SILInstruction *>::iterator location; if ((location = llvm::find_if(startingInstructions, [&](auto pair) -> bool { return pair.second == insertionPoint; })) != startingInstructions.end()) { reusedEndBorrowInsts.insert(location->second); return false; } } auto builder = SILBuilderWithScope(insertionPoint); builder.createEndBorrow( RegularLocation::getAutoGeneratedLocation(insertionPoint->getLoc()), introducer); return true; } bool swift::shrinkBorrowScope( BeginBorrowInst *bbi, InstructionDeleter &deleter, SmallVectorImpl<CopyValueInst *> &modifiedCopyValueInsts) { ShrinkBorrowScope borrowShrinker(bbi, deleter, modifiedCopyValueInsts); return borrowShrinker.run(); } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2016 Couchbase, 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. */ #include "ep_bucket.h" #include "bgfetcher.h" #include "ep_engine.h" #include "flusher.h" EPBucket::EPBucket(EventuallyPersistentEngine& theEngine) : KVBucket(theEngine) { } bool EPBucket::initialize() { KVBucket::initialize(); if (!startBgFetcher()) { LOG(EXTENSION_LOG_FATAL, "EPBucket::initialize: Failed to create and start bgFetchers"); return false; } startFlusher(); return true; } void EPBucket::deinitialize() { stopFlusher(); stopBgFetcher(); KVBucket::deinitialize(); } protocol_binary_response_status EPBucket::evictKey(const DocKey& key, uint16_t vbucket, const char** msg, size_t* msg_size) { RCPtr<VBucket> vb = getVBucket(vbucket); if (!vb || (vb->getState() != vbucket_state_active)) { return PROTOCOL_BINARY_RESPONSE_NOT_MY_VBUCKET; } int bucket_num(0); auto lh = vb->ht.getLockedBucket(key, &bucket_num); StoredValue* v = vb->fetchValidValue(lh, key, bucket_num, /*wantDeleted*/ false, /*trackReference*/ false); protocol_binary_response_status rv(PROTOCOL_BINARY_RESPONSE_SUCCESS); *msg_size = 0; if (v) { if (v->isResident()) { if (vb->ht.unlocked_ejectItem(v, eviction_policy)) { *msg = "Ejected."; // Add key to bloom filter incase of full eviction mode if (getItemEvictionPolicy() == FULL_EVICTION) { vb->addToFilter(key); } } else { *msg = "Can't eject: Dirty object."; rv = PROTOCOL_BINARY_RESPONSE_KEY_EEXISTS; } } else { *msg = "Already ejected."; } } else { if (eviction_policy == VALUE_ONLY) { *msg = "Not found."; rv = PROTOCOL_BINARY_RESPONSE_KEY_ENOENT; } else { *msg = "Already ejected."; } } return rv; } void EPBucket::reset() { KVBucket::reset(); // Need to additionally update disk state bool inverse = true; flushAllTaskCtx.delayFlushAll.compare_exchange_strong(inverse, false); // Waking up (notifying) one flusher is good enough for diskFlushAll vbMap.getShard(EP_PRIMARY_SHARD)->getFlusher()->notifyFlushEvent(); } void EPBucket::startFlusher() { for (const auto& shard : vbMap.shards) { shard->getFlusher()->start(); } } void EPBucket::stopFlusher() { for (uint16_t i = 0; i < vbMap.shards.size(); i++) { Flusher* flusher = vbMap.shards[i]->getFlusher(); LOG(EXTENSION_LOG_NOTICE, "Attempting to stop the flusher for " "shard:%" PRIu16, i); bool rv = flusher->stop(stats.forceShutdown); if (rv && !stats.forceShutdown) { flusher->wait(); } } } bool EPBucket::pauseFlusher() { bool rv = true; for (uint16_t i = 0; i < vbMap.shards.size(); i++) { Flusher* flusher = vbMap.shards[i]->getFlusher(); if (!flusher->pause()) { LOG(EXTENSION_LOG_WARNING, "Attempted to pause flusher in state " "[%s], shard = %d", flusher->stateName(), i); rv = false; } } return rv; } bool EPBucket::resumeFlusher() { bool rv = true; for (uint16_t i = 0; i < vbMap.shards.size(); i++) { Flusher* flusher = vbMap.shards[i]->getFlusher(); if (!flusher->resume()) { LOG(EXTENSION_LOG_WARNING, "Attempted to resume flusher in state [%s], " "shard = %d", flusher->stateName(), i); rv = false; } } return rv; } void EPBucket::wakeUpFlusher() { if (stats.diskQueueSize.load() == 0) { for (uint16_t i = 0; i < vbMap.shards.size(); i++) { Flusher *flusher = vbMap.shards[i]->getFlusher(); flusher->wake(); } } } bool EPBucket::startBgFetcher() { for (uint16_t i = 0; i < vbMap.shards.size(); i++) { BgFetcher* bgfetcher = vbMap.shards[i]->getBgFetcher(); if (bgfetcher == NULL) { LOG(EXTENSION_LOG_WARNING, "Failed to start bg fetcher for shard %d", i); return false; } bgfetcher->start(); } return true; } void EPBucket::stopBgFetcher() { for (uint16_t i = 0; i < vbMap.shards.size(); i++) { BgFetcher* bgfetcher = vbMap.shards[i]->getBgFetcher(); if (multiBGFetchEnabled() && bgfetcher->pendingJob()) { LOG(EXTENSION_LOG_WARNING, "Shutting down engine while there are still pending data " "read for shard %d from database storage", i); } LOG(EXTENSION_LOG_NOTICE, "Stopping bg fetcher for shard:%" PRIu16, i); bgfetcher->stop(); } } ENGINE_ERROR_CODE EPBucket::getFileStats(const void* cookie, ADD_STAT add_stat) { const auto numShards = vbMap.getNumShards(); DBFileInfo totalInfo; for (uint16_t shardId = 0; shardId < numShards; shardId++) { const auto dbInfo = getRWUnderlyingByShard(shardId)->getAggrDbFileInfo(); totalInfo.spaceUsed += dbInfo.spaceUsed; totalInfo.fileSize += dbInfo.fileSize; } add_casted_stat("ep_db_data_size", totalInfo.spaceUsed, add_stat, cookie); add_casted_stat("ep_db_file_size", totalInfo.fileSize, add_stat, cookie); return ENGINE_SUCCESS; } ENGINE_ERROR_CODE EPBucket::getPerVBucketDiskStats(const void* cookie, ADD_STAT add_stat) { class DiskStatVisitor : public VBucketVisitor { public: DiskStatVisitor(const void* c, ADD_STAT a) : cookie(c), add_stat(a) { } void visitBucket(RCPtr<VBucket>& vb) override { char buf[32]; uint16_t vbid = vb->getId(); DBFileInfo dbInfo = vb->getShard()->getRWUnderlying()->getDbFileInfo(vbid); try { checked_snprintf(buf, sizeof(buf), "vb_%d:data_size", vbid); add_casted_stat(buf, dbInfo.spaceUsed, add_stat, cookie); checked_snprintf(buf, sizeof(buf), "vb_%d:file_size", vbid); add_casted_stat(buf, dbInfo.fileSize, add_stat, cookie); } catch (std::exception& error) { LOG(EXTENSION_LOG_WARNING, "DiskStatVisitor::visitBucket: Failed to build stat: %s", error.what()); } } private: const void* cookie; ADD_STAT add_stat; }; DiskStatVisitor dsv(cookie, add_stat); visit(dsv); return ENGINE_SUCCESS; } RCPtr<VBucket> EPBucket::makeVBucket( VBucket::id_type id, vbucket_state_t state, KVShard* shard, std::unique_ptr<FailoverTable> table, NewSeqnoCallback newSeqnoCb, vbucket_state_t initState, int64_t lastSeqno, uint64_t lastSnapStart, uint64_t lastSnapEnd, uint64_t purgeSeqno, uint64_t maxCas) { auto flusherCb = std::make_shared<NotifyFlusherCB>(shard); return RCPtr<VBucket>(new VBucket(id, state, stats, engine.getCheckpointConfig(), shard, lastSeqno, lastSnapStart, lastSnapEnd, std::move(table), flusherCb, std::move(newSeqnoCb), engine.getConfiguration(), eviction_policy, initState, purgeSeqno, maxCas)); } <commit_msg>EPBucket: Use range-for loop for Flusher & BGFetcher iteration<commit_after>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2016 Couchbase, 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. */ #include "ep_bucket.h" #include "bgfetcher.h" #include "ep_engine.h" #include "flusher.h" EPBucket::EPBucket(EventuallyPersistentEngine& theEngine) : KVBucket(theEngine) { } bool EPBucket::initialize() { KVBucket::initialize(); if (!startBgFetcher()) { LOG(EXTENSION_LOG_FATAL, "EPBucket::initialize: Failed to create and start bgFetchers"); return false; } startFlusher(); return true; } void EPBucket::deinitialize() { stopFlusher(); stopBgFetcher(); KVBucket::deinitialize(); } protocol_binary_response_status EPBucket::evictKey(const DocKey& key, uint16_t vbucket, const char** msg, size_t* msg_size) { RCPtr<VBucket> vb = getVBucket(vbucket); if (!vb || (vb->getState() != vbucket_state_active)) { return PROTOCOL_BINARY_RESPONSE_NOT_MY_VBUCKET; } int bucket_num(0); auto lh = vb->ht.getLockedBucket(key, &bucket_num); StoredValue* v = vb->fetchValidValue(lh, key, bucket_num, /*wantDeleted*/ false, /*trackReference*/ false); protocol_binary_response_status rv(PROTOCOL_BINARY_RESPONSE_SUCCESS); *msg_size = 0; if (v) { if (v->isResident()) { if (vb->ht.unlocked_ejectItem(v, eviction_policy)) { *msg = "Ejected."; // Add key to bloom filter incase of full eviction mode if (getItemEvictionPolicy() == FULL_EVICTION) { vb->addToFilter(key); } } else { *msg = "Can't eject: Dirty object."; rv = PROTOCOL_BINARY_RESPONSE_KEY_EEXISTS; } } else { *msg = "Already ejected."; } } else { if (eviction_policy == VALUE_ONLY) { *msg = "Not found."; rv = PROTOCOL_BINARY_RESPONSE_KEY_ENOENT; } else { *msg = "Already ejected."; } } return rv; } void EPBucket::reset() { KVBucket::reset(); // Need to additionally update disk state bool inverse = true; flushAllTaskCtx.delayFlushAll.compare_exchange_strong(inverse, false); // Waking up (notifying) one flusher is good enough for diskFlushAll vbMap.getShard(EP_PRIMARY_SHARD)->getFlusher()->notifyFlushEvent(); } void EPBucket::startFlusher() { for (const auto& shard : vbMap.shards) { shard->getFlusher()->start(); } } void EPBucket::stopFlusher() { for (const auto& shard : vbMap.shards) { auto* flusher = shard->getFlusher(); LOG(EXTENSION_LOG_NOTICE, "Attempting to stop the flusher for " "shard:%" PRIu16, shard->getId()); bool rv = flusher->stop(stats.forceShutdown); if (rv && !stats.forceShutdown) { flusher->wait(); } } } bool EPBucket::pauseFlusher() { bool rv = true; for (const auto& shard : vbMap.shards) { auto* flusher = shard->getFlusher(); if (!flusher->pause()) { LOG(EXTENSION_LOG_WARNING, "Attempted to pause flusher in state " "[%s], shard = %d", flusher->stateName(), shard->getId()); rv = false; } } return rv; } bool EPBucket::resumeFlusher() { bool rv = true; for (const auto& shard : vbMap.shards) { auto* flusher = shard->getFlusher(); if (!flusher->resume()) { LOG(EXTENSION_LOG_WARNING, "Attempted to resume flusher in state [%s], " "shard = %" PRIu16, flusher->stateName(), shard->getId()); rv = false; } } return rv; } void EPBucket::wakeUpFlusher() { if (stats.diskQueueSize.load() == 0) { for (const auto& shard : vbMap.shards) { shard->getFlusher()->wake(); } } } bool EPBucket::startBgFetcher() { for (const auto& shard : vbMap.shards) { BgFetcher* bgfetcher = shard->getBgFetcher(); if (bgfetcher == NULL) { LOG(EXTENSION_LOG_WARNING, "Failed to start bg fetcher for shard %" PRIu16, shard->getId()); return false; } bgfetcher->start(); } return true; } void EPBucket::stopBgFetcher() { for (const auto& shard : vbMap.shards) { BgFetcher* bgfetcher = shard->getBgFetcher(); if (multiBGFetchEnabled() && bgfetcher->pendingJob()) { LOG(EXTENSION_LOG_WARNING, "Shutting down engine while there are still pending data " "read for shard %" PRIu16 " from database storage", shard->getId()); } LOG(EXTENSION_LOG_NOTICE, "Stopping bg fetcher for shard:%" PRIu16, shard->getId()); bgfetcher->stop(); } } ENGINE_ERROR_CODE EPBucket::getFileStats(const void* cookie, ADD_STAT add_stat) { const auto numShards = vbMap.getNumShards(); DBFileInfo totalInfo; for (uint16_t shardId = 0; shardId < numShards; shardId++) { const auto dbInfo = getRWUnderlyingByShard(shardId)->getAggrDbFileInfo(); totalInfo.spaceUsed += dbInfo.spaceUsed; totalInfo.fileSize += dbInfo.fileSize; } add_casted_stat("ep_db_data_size", totalInfo.spaceUsed, add_stat, cookie); add_casted_stat("ep_db_file_size", totalInfo.fileSize, add_stat, cookie); return ENGINE_SUCCESS; } ENGINE_ERROR_CODE EPBucket::getPerVBucketDiskStats(const void* cookie, ADD_STAT add_stat) { class DiskStatVisitor : public VBucketVisitor { public: DiskStatVisitor(const void* c, ADD_STAT a) : cookie(c), add_stat(a) { } void visitBucket(RCPtr<VBucket>& vb) override { char buf[32]; uint16_t vbid = vb->getId(); DBFileInfo dbInfo = vb->getShard()->getRWUnderlying()->getDbFileInfo(vbid); try { checked_snprintf(buf, sizeof(buf), "vb_%d:data_size", vbid); add_casted_stat(buf, dbInfo.spaceUsed, add_stat, cookie); checked_snprintf(buf, sizeof(buf), "vb_%d:file_size", vbid); add_casted_stat(buf, dbInfo.fileSize, add_stat, cookie); } catch (std::exception& error) { LOG(EXTENSION_LOG_WARNING, "DiskStatVisitor::visitBucket: Failed to build stat: %s", error.what()); } } private: const void* cookie; ADD_STAT add_stat; }; DiskStatVisitor dsv(cookie, add_stat); visit(dsv); return ENGINE_SUCCESS; } RCPtr<VBucket> EPBucket::makeVBucket( VBucket::id_type id, vbucket_state_t state, KVShard* shard, std::unique_ptr<FailoverTable> table, NewSeqnoCallback newSeqnoCb, vbucket_state_t initState, int64_t lastSeqno, uint64_t lastSnapStart, uint64_t lastSnapEnd, uint64_t purgeSeqno, uint64_t maxCas) { auto flusherCb = std::make_shared<NotifyFlusherCB>(shard); return RCPtr<VBucket>(new VBucket(id, state, stats, engine.getCheckpointConfig(), shard, lastSeqno, lastSnapStart, lastSnapEnd, std::move(table), flusherCb, std::move(newSeqnoCb), engine.getConfiguration(), eviction_policy, initState, purgeSeqno, maxCas)); } <|endoftext|>
<commit_before>// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "gpu/command_buffer/service/async_pixel_transfer_manager_idle.h" #include "base/bind.h" #include "base/debug/trace_event.h" #include "base/lazy_instance.h" #include "base/memory/weak_ptr.h" #include "gpu/command_buffer/service/safe_shared_memory_pool.h" #include "ui/gl/scoped_binders.h" namespace gpu { namespace { base::LazyInstance<SafeSharedMemoryPool> g_safe_shared_memory_pool = LAZY_INSTANCE_INITIALIZER; SafeSharedMemoryPool* safe_shared_memory_pool() { return g_safe_shared_memory_pool.Pointer(); } static uint64 g_next_pixel_transfer_state_id = 1; void PerformNotifyCompletion( AsyncMemoryParams mem_params, ScopedSafeSharedMemory* safe_shared_memory, const AsyncPixelTransferManager::CompletionCallback& callback) { TRACE_EVENT0("gpu", "PerformNotifyCompletion"); AsyncMemoryParams safe_mem_params = mem_params; safe_mem_params.shared_memory = safe_shared_memory->shared_memory(); callback.Run(safe_mem_params); } // TODO(backer): Merge this with Delegate in follow-up CL. It serves no purpose. class AsyncPixelTransferState : public base::SupportsWeakPtr<AsyncPixelTransferState> { public: typedef base::Callback<void(GLuint)> TransferCallback; explicit AsyncPixelTransferState(GLuint texture_id) : id_(g_next_pixel_transfer_state_id++), texture_id_(texture_id), transfer_in_progress_(false) { } virtual ~AsyncPixelTransferState() {} bool TransferIsInProgress() { return transfer_in_progress_; } uint64 id() const { return id_; } void set_transfer_in_progress(bool transfer_in_progress) { transfer_in_progress_ = transfer_in_progress; } void PerformTransfer(const TransferCallback& callback) { DCHECK(texture_id_); DCHECK(transfer_in_progress_); callback.Run(texture_id_); transfer_in_progress_ = false; } private: uint64 id_; GLuint texture_id_; bool transfer_in_progress_; DISALLOW_COPY_AND_ASSIGN(AsyncPixelTransferState); }; } // namespace // Class which handles async pixel transfers in a platform // independent way. class AsyncPixelTransferDelegateIdle : public AsyncPixelTransferDelegate, public base::SupportsWeakPtr<AsyncPixelTransferDelegateIdle> { public: AsyncPixelTransferDelegateIdle( AsyncPixelTransferManagerIdle::SharedState* state, GLuint texture_id); virtual ~AsyncPixelTransferDelegateIdle(); // Implement AsyncPixelTransferDelegate: virtual void AsyncTexImage2D( const AsyncTexImage2DParams& tex_params, const AsyncMemoryParams& mem_params, const base::Closure& bind_callback) OVERRIDE; virtual void AsyncTexSubImage2D( const AsyncTexSubImage2DParams& tex_params, const AsyncMemoryParams& mem_params) OVERRIDE; virtual bool TransferIsInProgress() OVERRIDE; virtual void WaitForTransferCompletion() OVERRIDE; private: void PerformAsyncTexImage2D( AsyncTexImage2DParams tex_params, AsyncMemoryParams mem_params, const base::Closure& bind_callback, ScopedSafeSharedMemory* safe_shared_memory, GLuint texture_id); void PerformAsyncTexSubImage2D( AsyncTexSubImage2DParams tex_params, AsyncMemoryParams mem_params, ScopedSafeSharedMemory* safe_shared_memory, GLuint texture_id); // Safe to hold a raw pointer because SharedState is owned by the Manager // which owns the Delegate. AsyncPixelTransferManagerIdle::SharedState* shared_state_; scoped_ptr<AsyncPixelTransferState> state_; DISALLOW_COPY_AND_ASSIGN(AsyncPixelTransferDelegateIdle); }; AsyncPixelTransferDelegateIdle::AsyncPixelTransferDelegateIdle( AsyncPixelTransferManagerIdle::SharedState* shared_state, GLuint texture_id) : shared_state_(shared_state), state_(new AsyncPixelTransferState(texture_id)) {} AsyncPixelTransferDelegateIdle::~AsyncPixelTransferDelegateIdle() {} void AsyncPixelTransferDelegateIdle::AsyncTexImage2D( const AsyncTexImage2DParams& tex_params, const AsyncMemoryParams& mem_params, const base::Closure& bind_callback) { DCHECK_EQ(static_cast<GLenum>(GL_TEXTURE_2D), tex_params.target); DCHECK(mem_params.shared_memory); DCHECK_LE(mem_params.shm_data_offset + mem_params.shm_data_size, mem_params.shm_size); shared_state_->tasks.push_back(AsyncPixelTransferManagerIdle::Task( state_->id(), base::Bind( &AsyncPixelTransferState::PerformTransfer, state_->AsWeakPtr(), base::Bind( &AsyncPixelTransferDelegateIdle::PerformAsyncTexImage2D, AsWeakPtr(), tex_params, mem_params, bind_callback, base::Owned(new ScopedSafeSharedMemory(safe_shared_memory_pool(), mem_params.shared_memory, mem_params.shm_size)))))); state_->set_transfer_in_progress(true); } void AsyncPixelTransferDelegateIdle::AsyncTexSubImage2D( const AsyncTexSubImage2DParams& tex_params, const AsyncMemoryParams& mem_params) { DCHECK_EQ(static_cast<GLenum>(GL_TEXTURE_2D), tex_params.target); DCHECK(mem_params.shared_memory); DCHECK_LE(mem_params.shm_data_offset + mem_params.shm_data_size, mem_params.shm_size); shared_state_->tasks.push_back(AsyncPixelTransferManagerIdle::Task( state_->id(), base::Bind( &AsyncPixelTransferState::PerformTransfer, state_->AsWeakPtr(), base::Bind( &AsyncPixelTransferDelegateIdle::PerformAsyncTexSubImage2D, AsWeakPtr(), tex_params, mem_params, base::Owned(new ScopedSafeSharedMemory(safe_shared_memory_pool(), mem_params.shared_memory, mem_params.shm_size)))))); state_->set_transfer_in_progress(true); } bool AsyncPixelTransferDelegateIdle::TransferIsInProgress() { return state_->TransferIsInProgress(); } void AsyncPixelTransferDelegateIdle::WaitForTransferCompletion() { for (std::list<AsyncPixelTransferManagerIdle::Task>::iterator iter = shared_state_->tasks.begin(); iter != shared_state_->tasks.end(); ++iter) { if (iter->transfer_id != state_->id()) continue; (*iter).task.Run(); shared_state_->tasks.erase(iter); break; } shared_state_->ProcessNotificationTasks(); } void AsyncPixelTransferDelegateIdle::PerformAsyncTexImage2D( AsyncTexImage2DParams tex_params, AsyncMemoryParams mem_params, const base::Closure& bind_callback, ScopedSafeSharedMemory* safe_shared_memory, GLuint texture_id) { TRACE_EVENT2("gpu", "PerformAsyncTexImage2D", "width", tex_params.width, "height", tex_params.height); void* data = GetAddress(safe_shared_memory, mem_params); gfx::ScopedTextureBinder texture_binder(tex_params.target, texture_id); { TRACE_EVENT0("gpu", "glTexImage2D"); glTexImage2D( tex_params.target, tex_params.level, tex_params.internal_format, tex_params.width, tex_params.height, tex_params.border, tex_params.format, tex_params.type, data); } // The texture is already fully bound so just call it now. bind_callback.Run(); } void AsyncPixelTransferDelegateIdle::PerformAsyncTexSubImage2D( AsyncTexSubImage2DParams tex_params, AsyncMemoryParams mem_params, ScopedSafeSharedMemory* safe_shared_memory, GLuint texture_id) { TRACE_EVENT2("gpu", "PerformAsyncTexSubImage2D", "width", tex_params.width, "height", tex_params.height); void* data = GetAddress(safe_shared_memory, mem_params); base::TimeTicks begin_time(base::TimeTicks::HighResNow()); gfx::ScopedTextureBinder texture_binder(tex_params.target, texture_id); { TRACE_EVENT0("gpu", "glTexSubImage2D"); glTexSubImage2D( tex_params.target, tex_params.level, tex_params.xoffset, tex_params.yoffset, tex_params.width, tex_params.height, tex_params.format, tex_params.type, data); } shared_state_->texture_upload_count++; shared_state_->total_texture_upload_time += base::TimeTicks::HighResNow() - begin_time; } AsyncPixelTransferManagerIdle::Task::Task( uint64 transfer_id, const base::Closure& task) : transfer_id(transfer_id), task(task) { } AsyncPixelTransferManagerIdle::Task::~Task() {} AsyncPixelTransferManagerIdle::SharedState::SharedState() : texture_upload_count(0) {} AsyncPixelTransferManagerIdle::SharedState::~SharedState() {} void AsyncPixelTransferManagerIdle::SharedState::ProcessNotificationTasks() { while (!tasks.empty()) { // Stop when we reach a pixel transfer task. if (tasks.front().transfer_id) return; tasks.front().task.Run(); tasks.pop_front(); } } AsyncPixelTransferManagerIdle::AsyncPixelTransferManagerIdle() : shared_state_() { } AsyncPixelTransferManagerIdle::~AsyncPixelTransferManagerIdle() {} void AsyncPixelTransferManagerIdle::BindCompletedAsyncTransfers() { // Everything is already bound. } void AsyncPixelTransferManagerIdle::AsyncNotifyCompletion( const AsyncMemoryParams& mem_params, const CompletionCallback& callback) { if (shared_state_.tasks.empty()) { callback.Run(mem_params); return; } shared_state_.tasks.push_back( Task(0, // 0 transfer_id for notification tasks. base::Bind( &PerformNotifyCompletion, mem_params, base::Owned(new ScopedSafeSharedMemory(safe_shared_memory_pool(), mem_params.shared_memory, mem_params.shm_size)), callback))); } uint32 AsyncPixelTransferManagerIdle::GetTextureUploadCount() { return shared_state_.texture_upload_count; } base::TimeDelta AsyncPixelTransferManagerIdle::GetTotalTextureUploadTime() { return shared_state_.total_texture_upload_time; } void AsyncPixelTransferManagerIdle::ProcessMorePendingTransfers() { if (shared_state_.tasks.empty()) return; // First task should always be a pixel transfer task. DCHECK(shared_state_.tasks.front().transfer_id); shared_state_.tasks.front().task.Run(); shared_state_.tasks.pop_front(); shared_state_.ProcessNotificationTasks(); } bool AsyncPixelTransferManagerIdle::NeedsProcessMorePendingTransfers() { return !shared_state_.tasks.empty(); } AsyncPixelTransferDelegate* AsyncPixelTransferManagerIdle::CreatePixelTransferDelegateImpl( gles2::TextureRef* ref, const AsyncTexImage2DParams& define_params) { return new AsyncPixelTransferDelegateIdle(&shared_state_, ref->service_id()); } } // namespace gpu <commit_msg>GPU: Eliminate unnecessary State on async idle upload path.<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "gpu/command_buffer/service/async_pixel_transfer_manager_idle.h" #include "base/bind.h" #include "base/debug/trace_event.h" #include "base/lazy_instance.h" #include "base/memory/weak_ptr.h" #include "gpu/command_buffer/service/safe_shared_memory_pool.h" #include "ui/gl/scoped_binders.h" namespace gpu { namespace { base::LazyInstance<SafeSharedMemoryPool> g_safe_shared_memory_pool = LAZY_INSTANCE_INITIALIZER; SafeSharedMemoryPool* safe_shared_memory_pool() { return g_safe_shared_memory_pool.Pointer(); } static uint64 g_next_pixel_transfer_state_id = 1; void PerformNotifyCompletion( AsyncMemoryParams mem_params, ScopedSafeSharedMemory* safe_shared_memory, const AsyncPixelTransferManager::CompletionCallback& callback) { TRACE_EVENT0("gpu", "PerformNotifyCompletion"); AsyncMemoryParams safe_mem_params = mem_params; safe_mem_params.shared_memory = safe_shared_memory->shared_memory(); callback.Run(safe_mem_params); } } // namespace // Class which handles async pixel transfers in a platform // independent way. class AsyncPixelTransferDelegateIdle : public AsyncPixelTransferDelegate, public base::SupportsWeakPtr<AsyncPixelTransferDelegateIdle> { public: AsyncPixelTransferDelegateIdle( AsyncPixelTransferManagerIdle::SharedState* state, GLuint texture_id); virtual ~AsyncPixelTransferDelegateIdle(); // Implement AsyncPixelTransferDelegate: virtual void AsyncTexImage2D( const AsyncTexImage2DParams& tex_params, const AsyncMemoryParams& mem_params, const base::Closure& bind_callback) OVERRIDE; virtual void AsyncTexSubImage2D( const AsyncTexSubImage2DParams& tex_params, const AsyncMemoryParams& mem_params) OVERRIDE; virtual bool TransferIsInProgress() OVERRIDE; virtual void WaitForTransferCompletion() OVERRIDE; private: void PerformAsyncTexImage2D( AsyncTexImage2DParams tex_params, AsyncMemoryParams mem_params, const base::Closure& bind_callback, ScopedSafeSharedMemory* safe_shared_memory); void PerformAsyncTexSubImage2D( AsyncTexSubImage2DParams tex_params, AsyncMemoryParams mem_params, ScopedSafeSharedMemory* safe_shared_memory); uint64 id_; GLuint texture_id_; bool transfer_in_progress_; // Safe to hold a raw pointer because SharedState is owned by the Manager // which owns the Delegate. AsyncPixelTransferManagerIdle::SharedState* shared_state_; DISALLOW_COPY_AND_ASSIGN(AsyncPixelTransferDelegateIdle); }; AsyncPixelTransferDelegateIdle::AsyncPixelTransferDelegateIdle( AsyncPixelTransferManagerIdle::SharedState* shared_state, GLuint texture_id) : id_(g_next_pixel_transfer_state_id++), texture_id_(texture_id), transfer_in_progress_(false), shared_state_(shared_state) {} AsyncPixelTransferDelegateIdle::~AsyncPixelTransferDelegateIdle() {} void AsyncPixelTransferDelegateIdle::AsyncTexImage2D( const AsyncTexImage2DParams& tex_params, const AsyncMemoryParams& mem_params, const base::Closure& bind_callback) { DCHECK_EQ(static_cast<GLenum>(GL_TEXTURE_2D), tex_params.target); DCHECK(mem_params.shared_memory); DCHECK_LE(mem_params.shm_data_offset + mem_params.shm_data_size, mem_params.shm_size); shared_state_->tasks.push_back(AsyncPixelTransferManagerIdle::Task( id_, base::Bind( &AsyncPixelTransferDelegateIdle::PerformAsyncTexImage2D, AsWeakPtr(), tex_params, mem_params, bind_callback, base::Owned(new ScopedSafeSharedMemory(safe_shared_memory_pool(), mem_params.shared_memory, mem_params.shm_size))))); transfer_in_progress_ = true; } void AsyncPixelTransferDelegateIdle::AsyncTexSubImage2D( const AsyncTexSubImage2DParams& tex_params, const AsyncMemoryParams& mem_params) { DCHECK_EQ(static_cast<GLenum>(GL_TEXTURE_2D), tex_params.target); DCHECK(mem_params.shared_memory); DCHECK_LE(mem_params.shm_data_offset + mem_params.shm_data_size, mem_params.shm_size); shared_state_->tasks.push_back(AsyncPixelTransferManagerIdle::Task( id_, base::Bind( &AsyncPixelTransferDelegateIdle::PerformAsyncTexSubImage2D, AsWeakPtr(), tex_params, mem_params, base::Owned(new ScopedSafeSharedMemory(safe_shared_memory_pool(), mem_params.shared_memory, mem_params.shm_size))))); transfer_in_progress_ = true; } bool AsyncPixelTransferDelegateIdle::TransferIsInProgress() { return transfer_in_progress_; } void AsyncPixelTransferDelegateIdle::WaitForTransferCompletion() { for (std::list<AsyncPixelTransferManagerIdle::Task>::iterator iter = shared_state_->tasks.begin(); iter != shared_state_->tasks.end(); ++iter) { if (iter->transfer_id != id_) continue; (*iter).task.Run(); shared_state_->tasks.erase(iter); break; } shared_state_->ProcessNotificationTasks(); } void AsyncPixelTransferDelegateIdle::PerformAsyncTexImage2D( AsyncTexImage2DParams tex_params, AsyncMemoryParams mem_params, const base::Closure& bind_callback, ScopedSafeSharedMemory* safe_shared_memory) { TRACE_EVENT2("gpu", "PerformAsyncTexImage2D", "width", tex_params.width, "height", tex_params.height); void* data = GetAddress(safe_shared_memory, mem_params); gfx::ScopedTextureBinder texture_binder(tex_params.target, texture_id_); { TRACE_EVENT0("gpu", "glTexImage2D"); glTexImage2D( tex_params.target, tex_params.level, tex_params.internal_format, tex_params.width, tex_params.height, tex_params.border, tex_params.format, tex_params.type, data); } transfer_in_progress_ = false; // The texture is already fully bound so just call it now. bind_callback.Run(); } void AsyncPixelTransferDelegateIdle::PerformAsyncTexSubImage2D( AsyncTexSubImage2DParams tex_params, AsyncMemoryParams mem_params, ScopedSafeSharedMemory* safe_shared_memory) { TRACE_EVENT2("gpu", "PerformAsyncTexSubImage2D", "width", tex_params.width, "height", tex_params.height); void* data = GetAddress(safe_shared_memory, mem_params); base::TimeTicks begin_time(base::TimeTicks::HighResNow()); gfx::ScopedTextureBinder texture_binder(tex_params.target, texture_id_); { TRACE_EVENT0("gpu", "glTexSubImage2D"); glTexSubImage2D( tex_params.target, tex_params.level, tex_params.xoffset, tex_params.yoffset, tex_params.width, tex_params.height, tex_params.format, tex_params.type, data); } transfer_in_progress_ = false; shared_state_->texture_upload_count++; shared_state_->total_texture_upload_time += base::TimeTicks::HighResNow() - begin_time; } AsyncPixelTransferManagerIdle::Task::Task( uint64 transfer_id, const base::Closure& task) : transfer_id(transfer_id), task(task) { } AsyncPixelTransferManagerIdle::Task::~Task() {} AsyncPixelTransferManagerIdle::SharedState::SharedState() : texture_upload_count(0) {} AsyncPixelTransferManagerIdle::SharedState::~SharedState() {} void AsyncPixelTransferManagerIdle::SharedState::ProcessNotificationTasks() { while (!tasks.empty()) { // Stop when we reach a pixel transfer task. if (tasks.front().transfer_id) return; tasks.front().task.Run(); tasks.pop_front(); } } AsyncPixelTransferManagerIdle::AsyncPixelTransferManagerIdle() : shared_state_() { } AsyncPixelTransferManagerIdle::~AsyncPixelTransferManagerIdle() {} void AsyncPixelTransferManagerIdle::BindCompletedAsyncTransfers() { // Everything is already bound. } void AsyncPixelTransferManagerIdle::AsyncNotifyCompletion( const AsyncMemoryParams& mem_params, const CompletionCallback& callback) { if (shared_state_.tasks.empty()) { callback.Run(mem_params); return; } shared_state_.tasks.push_back( Task(0, // 0 transfer_id for notification tasks. base::Bind( &PerformNotifyCompletion, mem_params, base::Owned(new ScopedSafeSharedMemory(safe_shared_memory_pool(), mem_params.shared_memory, mem_params.shm_size)), callback))); } uint32 AsyncPixelTransferManagerIdle::GetTextureUploadCount() { return shared_state_.texture_upload_count; } base::TimeDelta AsyncPixelTransferManagerIdle::GetTotalTextureUploadTime() { return shared_state_.total_texture_upload_time; } void AsyncPixelTransferManagerIdle::ProcessMorePendingTransfers() { if (shared_state_.tasks.empty()) return; // First task should always be a pixel transfer task. DCHECK(shared_state_.tasks.front().transfer_id); shared_state_.tasks.front().task.Run(); shared_state_.tasks.pop_front(); shared_state_.ProcessNotificationTasks(); } bool AsyncPixelTransferManagerIdle::NeedsProcessMorePendingTransfers() { return !shared_state_.tasks.empty(); } AsyncPixelTransferDelegate* AsyncPixelTransferManagerIdle::CreatePixelTransferDelegateImpl( gles2::TextureRef* ref, const AsyncTexImage2DParams& define_params) { return new AsyncPixelTransferDelegateIdle(&shared_state_, ref->service_id()); } } // namespace gpu <|endoftext|>
<commit_before>//===-- IPConstantPropagation.cpp - Propagate constants through calls -----===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This pass implements an _extremely_ simple interprocedural constant // propagation pass. It could certainly be improved in many different ways, // like using a worklist. This pass makes arguments dead, but does not remove // them. The existing dead argument elimination pass should be run after this // to clean up the mess. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "ipconstprop" #include "llvm/Transforms/IPO.h" #include "llvm/Constants.h" #include "llvm/Instructions.h" #include "llvm/Module.h" #include "llvm/Pass.h" #include "llvm/Support/CallSite.h" #include "llvm/Support/Compiler.h" #include "llvm/ADT/Statistic.h" #include "llvm/ADT/SmallVector.h" using namespace llvm; STATISTIC(NumArgumentsProped, "Number of args turned into constants"); STATISTIC(NumReturnValProped, "Number of return values turned into constants"); namespace { /// IPCP - The interprocedural constant propagation pass /// struct VISIBILITY_HIDDEN IPCP : public ModulePass { static char ID; // Pass identification, replacement for typeid IPCP() : ModulePass((intptr_t)&ID) {} bool runOnModule(Module &M); private: bool PropagateConstantsIntoArguments(Function &F); bool PropagateConstantReturn(Function &F); }; char IPCP::ID = 0; RegisterPass<IPCP> X("ipconstprop", "Interprocedural constant propagation"); } ModulePass *llvm::createIPConstantPropagationPass() { return new IPCP(); } bool IPCP::runOnModule(Module &M) { bool Changed = false; bool LocalChange = true; // FIXME: instead of using smart algorithms, we just iterate until we stop // making changes. while (LocalChange) { LocalChange = false; for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) if (!I->isDeclaration()) { // Delete any klingons. I->removeDeadConstantUsers(); if (I->hasInternalLinkage()) LocalChange |= PropagateConstantsIntoArguments(*I); Changed |= PropagateConstantReturn(*I); } Changed |= LocalChange; } return Changed; } /// PropagateConstantsIntoArguments - Look at all uses of the specified /// function. If all uses are direct call sites, and all pass a particular /// constant in for an argument, propagate that constant in as the argument. /// bool IPCP::PropagateConstantsIntoArguments(Function &F) { if (F.arg_empty() || F.use_empty()) return false; // No arguments? Early exit. std::vector<std::pair<Constant*, bool> > ArgumentConstants; ArgumentConstants.resize(F.arg_size()); unsigned NumNonconstant = 0; for (Value::use_iterator I = F.use_begin(), E = F.use_end(); I != E; ++I) if (!isa<Instruction>(*I)) return false; // Used by a non-instruction, do not transform else { CallSite CS = CallSite::get(cast<Instruction>(*I)); if (CS.getInstruction() == 0 || CS.getCalledFunction() != &F) return false; // Not a direct call site? // Check out all of the potentially constant arguments CallSite::arg_iterator AI = CS.arg_begin(); Function::arg_iterator Arg = F.arg_begin(); for (unsigned i = 0, e = ArgumentConstants.size(); i != e; ++i, ++AI, ++Arg) { if (*AI == &F) return false; // Passes the function into itself if (!ArgumentConstants[i].second) { if (Constant *C = dyn_cast<Constant>(*AI)) { if (!ArgumentConstants[i].first) ArgumentConstants[i].first = C; else if (ArgumentConstants[i].first != C) { // Became non-constant ArgumentConstants[i].second = true; ++NumNonconstant; if (NumNonconstant == ArgumentConstants.size()) return false; } } else if (*AI != &*Arg) { // Ignore recursive calls with same arg // This is not a constant argument. Mark the argument as // non-constant. ArgumentConstants[i].second = true; ++NumNonconstant; if (NumNonconstant == ArgumentConstants.size()) return false; } } } } // If we got to this point, there is a constant argument! assert(NumNonconstant != ArgumentConstants.size()); Function::arg_iterator AI = F.arg_begin(); bool MadeChange = false; for (unsigned i = 0, e = ArgumentConstants.size(); i != e; ++i, ++AI) // Do we have a constant argument!? if (!ArgumentConstants[i].second && !AI->use_empty()) { Value *V = ArgumentConstants[i].first; if (V == 0) V = UndefValue::get(AI->getType()); AI->replaceAllUsesWith(V); ++NumArgumentsProped; MadeChange = true; } return MadeChange; } // Check to see if this function returns a constant. If so, replace all callers // that user the return value with the returned valued. If we can replace ALL // callers, bool IPCP::PropagateConstantReturn(Function &F) { if (F.getReturnType() == Type::VoidTy) return false; // No return value. // Check to see if this function returns a constant. SmallVector<Value *,4> RetVals; unsigned N = 0; const StructType *STy = dyn_cast<StructType>(F.getReturnType()); if (STy) N = STy->getNumElements(); else N = 1; for (unsigned i = 0; i < N; ++i) RetVals.push_back(0); for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) { assert (N == RI->getNumOperands() && "Invalid ReturnInst operands!"); for (unsigned i = 0; i < N; ++i) { if (isa<UndefValue>(RI->getOperand(i))) { // Ignore } else if (Constant *C = dyn_cast<Constant>(RI->getOperand(i))) { Value *RV = RetVals[i]; if (RV == 0) RetVals[i] = C; else if (RV != C) return false; // Does not return the same constant. } else { return false; // Does not return a constant. } } } if (N == 1) { if (RetVals[0] == 0) RetVals[0] = UndefValue::get(F.getReturnType()); } else { for (unsigned i = 0; i < N; ++i) { Value *RetVal = RetVals[i]; if (RetVal == 0) RetVals[i] = UndefValue::get(STy->getElementType(i)); } } // If we got here, the function returns a constant value. Loop over all // users, replacing any uses of the return value with the returned constant. bool ReplacedAllUsers = true; bool MadeChange = false; for (Value::use_iterator I = F.use_begin(), E = F.use_end(); I != E; ++I) if (!isa<Instruction>(*I)) ReplacedAllUsers = false; else { CallSite CS = CallSite::get(cast<Instruction>(*I)); if (CS.getInstruction() == 0 || CS.getCalledFunction() != &F) { ReplacedAllUsers = false; } else { Instruction *Call = CS.getInstruction(); if (!Call->use_empty()) { if (N == 1) Call->replaceAllUsesWith(RetVals[0]); else { for(Value::use_iterator CUI = Call->use_begin(), CUE = Call->use_end(); CUI != CUE; ++CUI) { GetResultInst *GR = cast<GetResultInst>(CUI); GR->replaceAllUsesWith(RetVals[GR->getIndex()]); GR->eraseFromParent(); } } MadeChange = true; } } } // If we replace all users with the returned constant, and there can be no // other callers of the function, replace the constant being returned in the // function with an undef value. if (ReplacedAllUsers && F.hasInternalLinkage()) { for (unsigned i = 0; i < N; ++i) { Value *RetVal = RetVals[i]; if (isa<UndefValue>(RetVal)) continue; Value *RV = UndefValue::get(RetVal->getType()); for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) { if (RI->getOperand(i) != RV) { RI->setOperand(i, RV); MadeChange = true; } } } } if (MadeChange) ++NumReturnValProped; return MadeChange; } <commit_msg>Incorporate feedback. - Fix loop nest. - Use RetVals.size() - Check for null return value.<commit_after>//===-- IPConstantPropagation.cpp - Propagate constants through calls -----===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This pass implements an _extremely_ simple interprocedural constant // propagation pass. It could certainly be improved in many different ways, // like using a worklist. This pass makes arguments dead, but does not remove // them. The existing dead argument elimination pass should be run after this // to clean up the mess. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "ipconstprop" #include "llvm/Transforms/IPO.h" #include "llvm/Constants.h" #include "llvm/Instructions.h" #include "llvm/Module.h" #include "llvm/Pass.h" #include "llvm/Support/CallSite.h" #include "llvm/Support/Compiler.h" #include "llvm/ADT/Statistic.h" #include "llvm/ADT/SmallVector.h" using namespace llvm; STATISTIC(NumArgumentsProped, "Number of args turned into constants"); STATISTIC(NumReturnValProped, "Number of return values turned into constants"); namespace { /// IPCP - The interprocedural constant propagation pass /// struct VISIBILITY_HIDDEN IPCP : public ModulePass { static char ID; // Pass identification, replacement for typeid IPCP() : ModulePass((intptr_t)&ID) {} bool runOnModule(Module &M); private: bool PropagateConstantsIntoArguments(Function &F); bool PropagateConstantReturn(Function &F); }; char IPCP::ID = 0; RegisterPass<IPCP> X("ipconstprop", "Interprocedural constant propagation"); } ModulePass *llvm::createIPConstantPropagationPass() { return new IPCP(); } bool IPCP::runOnModule(Module &M) { bool Changed = false; bool LocalChange = true; // FIXME: instead of using smart algorithms, we just iterate until we stop // making changes. while (LocalChange) { LocalChange = false; for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) if (!I->isDeclaration()) { // Delete any klingons. I->removeDeadConstantUsers(); if (I->hasInternalLinkage()) LocalChange |= PropagateConstantsIntoArguments(*I); Changed |= PropagateConstantReturn(*I); } Changed |= LocalChange; } return Changed; } /// PropagateConstantsIntoArguments - Look at all uses of the specified /// function. If all uses are direct call sites, and all pass a particular /// constant in for an argument, propagate that constant in as the argument. /// bool IPCP::PropagateConstantsIntoArguments(Function &F) { if (F.arg_empty() || F.use_empty()) return false; // No arguments? Early exit. std::vector<std::pair<Constant*, bool> > ArgumentConstants; ArgumentConstants.resize(F.arg_size()); unsigned NumNonconstant = 0; for (Value::use_iterator I = F.use_begin(), E = F.use_end(); I != E; ++I) if (!isa<Instruction>(*I)) return false; // Used by a non-instruction, do not transform else { CallSite CS = CallSite::get(cast<Instruction>(*I)); if (CS.getInstruction() == 0 || CS.getCalledFunction() != &F) return false; // Not a direct call site? // Check out all of the potentially constant arguments CallSite::arg_iterator AI = CS.arg_begin(); Function::arg_iterator Arg = F.arg_begin(); for (unsigned i = 0, e = ArgumentConstants.size(); i != e; ++i, ++AI, ++Arg) { if (*AI == &F) return false; // Passes the function into itself if (!ArgumentConstants[i].second) { if (Constant *C = dyn_cast<Constant>(*AI)) { if (!ArgumentConstants[i].first) ArgumentConstants[i].first = C; else if (ArgumentConstants[i].first != C) { // Became non-constant ArgumentConstants[i].second = true; ++NumNonconstant; if (NumNonconstant == ArgumentConstants.size()) return false; } } else if (*AI != &*Arg) { // Ignore recursive calls with same arg // This is not a constant argument. Mark the argument as // non-constant. ArgumentConstants[i].second = true; ++NumNonconstant; if (NumNonconstant == ArgumentConstants.size()) return false; } } } } // If we got to this point, there is a constant argument! assert(NumNonconstant != ArgumentConstants.size()); Function::arg_iterator AI = F.arg_begin(); bool MadeChange = false; for (unsigned i = 0, e = ArgumentConstants.size(); i != e; ++i, ++AI) // Do we have a constant argument!? if (!ArgumentConstants[i].second && !AI->use_empty()) { Value *V = ArgumentConstants[i].first; if (V == 0) V = UndefValue::get(AI->getType()); AI->replaceAllUsesWith(V); ++NumArgumentsProped; MadeChange = true; } return MadeChange; } // Check to see if this function returns a constant. If so, replace all callers // that user the return value with the returned valued. If we can replace ALL // callers, bool IPCP::PropagateConstantReturn(Function &F) { if (F.getReturnType() == Type::VoidTy) return false; // No return value. // Check to see if this function returns a constant. SmallVector<Value *,4> RetVals; const StructType *STy = dyn_cast<StructType>(F.getReturnType()); if (STy) RetVals.assign(STy->getNumElements(), 0); else RetVals.push_back(0); for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) { unsigned RetValsSize = RetVals.size(); assert (RetValsSize == RI->getNumOperands() && "Invalid ReturnInst operands!"); for (unsigned i = 0; i < RetValsSize; ++i) { if (isa<UndefValue>(RI->getOperand(i))) { // Ignore } else if (Constant *C = dyn_cast<Constant>(RI->getOperand(i))) { Value *RV = RetVals[i]; if (RV == 0) RetVals[i] = C; else if (RV != C) return false; // Does not return the same constant. } else { return false; // Does not return a constant. } } } if (STy) { for (unsigned i = 0, e = RetVals.size(); i < e; ++i) if (RetVals[i] == 0) RetVals[i] = UndefValue::get(STy->getElementType(i)); } else { if (RetVals.size() == 1) if (RetVals[0] == 0) RetVals[0] = UndefValue::get(F.getReturnType()); } // If we got here, the function returns a constant value. Loop over all // users, replacing any uses of the return value with the returned constant. bool ReplacedAllUsers = true; bool MadeChange = false; for (Value::use_iterator I = F.use_begin(), E = F.use_end(); I != E; ++I) if (!isa<Instruction>(*I)) ReplacedAllUsers = false; else { CallSite CS = CallSite::get(cast<Instruction>(*I)); if (CS.getInstruction() == 0 || CS.getCalledFunction() != &F) { ReplacedAllUsers = false; } else { Instruction *Call = CS.getInstruction(); if (!Call->use_empty()) { if (RetVals.size() == 1) Call->replaceAllUsesWith(RetVals[0]); else { for(Value::use_iterator CUI = Call->use_begin(), CUE = Call->use_end(); CUI != CUE; ++CUI) { GetResultInst *GR = cast<GetResultInst>(CUI); if (RetVals[GR->getIndex()]) { GR->replaceAllUsesWith(RetVals[GR->getIndex()]); GR->eraseFromParent(); } } } MadeChange = true; } } } // If we replace all users with the returned constant, and there can be no // other callers of the function, replace the constant being returned in the // function with an undef value. if (ReplacedAllUsers && F.hasInternalLinkage()) { for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) { if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) { for (unsigned i = 0, e = RetVals.size(); i < e; ++i) { Value *RetVal = RetVals[i]; if (isa<UndefValue>(RetVal)) continue; Value *RV = UndefValue::get(RetVal->getType()); if (RI->getOperand(i) != RV) { RI->setOperand(i, RV); MadeChange = true; } } } } } if (MadeChange) ++NumReturnValProped; return MadeChange; } <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkSimpleFilterWatcher.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. Portions of this code are covered under the VTK copyright. See VTKCopyright.txt or http://www.kitware.com/VTKCopyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "itkSimpleFilterWatcher.h" namespace itk { SimpleFilterWatcher ::SimpleFilterWatcher(ProcessObject* o, char *comment) { // Initialize state m_Start = 0; m_End = 0; m_Process = o; m_Steps = 0; m_Comment = comment; m_TestAbort = false; #if defined(_COMPILER_VERSION) && (_COMPILER_VERSION == 730) m_Quiet = true; #else m_Quiet = false; #endif // Create a series of commands m_StartFilterCommand = CommandType::New(); m_EndFilterCommand = CommandType::New(); m_ProgressFilterCommand = CommandType::New(); m_IterationFilterCommand = CommandType::New(); m_AbortFilterCommand = CommandType::New(); // Assign the callbacks m_StartFilterCommand->SetCallbackFunction(this, &SimpleFilterWatcher::StartFilter); m_EndFilterCommand->SetCallbackFunction(this, &SimpleFilterWatcher::EndFilter); m_ProgressFilterCommand->SetCallbackFunction(this, &SimpleFilterWatcher::ShowProgress); m_IterationFilterCommand->SetCallbackFunction(this, &SimpleFilterWatcher::ShowIteration); m_AbortFilterCommand->SetCallbackFunction(this, &SimpleFilterWatcher::ShowAbort); // Add the commands as observers m_StartTag = m_Process->AddObserver(StartEvent(), m_StartFilterCommand); m_EndTag = m_Process->AddObserver(EndEvent(), m_EndFilterCommand); m_ProgressTag = m_Process->AddObserver(ProgressEvent(), m_ProgressFilterCommand); m_IterationTag = m_Process->AddObserver(IterationEvent(), m_IterationFilterCommand); m_AbortTag = m_Process->AddObserver(AbortEvent(), m_AbortFilterCommand); } SimpleFilterWatcher ::SimpleFilterWatcher() { // Initialize state m_Start = 0; m_End = 0; m_Steps = 0; m_Comment = "Not watching an object"; m_TestAbort = false; #if defined(_COMPILER_VERSION) && (_COMPILER_VERSION == 730) m_Quiet = true; #else m_Quiet = false; #endif m_Process = 0; } SimpleFilterWatcher ::SimpleFilterWatcher(const SimpleFilterWatcher &watch) { // Remove any observers we have on the old process object if (m_Process) { if (m_StartFilterCommand) { m_Process->RemoveObserver(m_StartTag); } if (m_EndFilterCommand) { m_Process->RemoveObserver(m_EndTag); } if (m_ProgressFilterCommand) { m_Process->RemoveObserver(m_ProgressTag); } if (m_IterationFilterCommand) { m_Process->RemoveObserver(m_IterationTag); } if (m_AbortFilterCommand) { m_Process->RemoveObserver(m_AbortTag); } } // Initialize state m_Start = watch.m_Start; m_End = watch.m_End; m_Process = watch.m_Process; m_Steps = watch.m_Steps; m_Comment = watch.m_Comment; m_TestAbort = watch.m_TestAbort; m_Quiet = watch.m_Quiet; m_StartTag = 0; m_EndTag = 0; m_ProgressTag = 0; m_IterationTag = 0; m_AbortTag = 0; // Create a series of commands if (m_Process) { m_StartFilterCommand = CommandType::New(); m_EndFilterCommand = CommandType::New(); m_ProgressFilterCommand = CommandType::New(); m_IterationFilterCommand = CommandType::New(); m_AbortFilterCommand = CommandType::New(); // Assign the callbacks m_StartFilterCommand->SetCallbackFunction(this, &SimpleFilterWatcher::StartFilter); m_EndFilterCommand->SetCallbackFunction(this, &SimpleFilterWatcher::EndFilter); m_ProgressFilterCommand->SetCallbackFunction(this, &SimpleFilterWatcher::ShowProgress); m_IterationFilterCommand->SetCallbackFunction(this, &SimpleFilterWatcher::ShowIteration); m_AbortFilterCommand->SetCallbackFunction(this, &SimpleFilterWatcher::ShowAbort); // Add the commands as observers m_StartTag = m_Process->AddObserver(StartEvent(), m_StartFilterCommand); m_EndTag = m_Process->AddObserver(EndEvent(), m_EndFilterCommand); m_ProgressTag = m_Process->AddObserver(ProgressEvent(), m_ProgressFilterCommand); m_IterationTag = m_Process->AddObserver(IterationEvent(), m_IterationFilterCommand); m_AbortTag = m_Process->AddObserver(AbortEvent(), m_AbortFilterCommand); } } void SimpleFilterWatcher ::operator=(const SimpleFilterWatcher &watch) { // Remove any observers we have on the old process object if (m_Process) { if (m_StartFilterCommand) { m_Process->RemoveObserver(m_StartTag); } if (m_EndFilterCommand) { m_Process->RemoveObserver(m_EndTag); } if (m_ProgressFilterCommand) { m_Process->RemoveObserver(m_ProgressTag); } if (m_IterationFilterCommand) { m_Process->RemoveObserver(m_IterationTag); } if (m_AbortFilterCommand) { m_Process->RemoveObserver(m_AbortTag); } } // Initialize state m_Start = watch.m_Start; m_End = watch.m_End; m_Process = watch.m_Process; m_Steps = watch.m_Steps; m_Comment = watch.m_Comment; m_TestAbort = watch.m_TestAbort; m_Quiet = watch.m_Quiet; m_StartTag = 0; m_EndTag = 0; m_ProgressTag = 0; m_IterationTag = 0; m_AbortTag = 0; // Create a series of commands if (m_Process) { m_StartFilterCommand = CommandType::New(); m_EndFilterCommand = CommandType::New(); m_ProgressFilterCommand = CommandType::New(); m_IterationFilterCommand = CommandType::New(); m_AbortFilterCommand = CommandType::New(); // Assign the callbacks m_StartFilterCommand->SetCallbackFunction(this, &SimpleFilterWatcher::StartFilter); m_EndFilterCommand->SetCallbackFunction(this, &SimpleFilterWatcher::EndFilter); m_ProgressFilterCommand->SetCallbackFunction(this, &SimpleFilterWatcher::ShowProgress); m_IterationFilterCommand->SetCallbackFunction(this, &SimpleFilterWatcher::ShowIteration); m_AbortFilterCommand->SetCallbackFunction(this, &SimpleFilterWatcher::ShowAbort); // Add the commands as observers m_StartTag = m_Process->AddObserver(StartEvent(), m_StartFilterCommand); m_EndTag = m_Process->AddObserver(EndEvent(), m_EndFilterCommand); m_ProgressTag = m_Process->AddObserver(ProgressEvent(), m_ProgressFilterCommand); m_IterationTag = m_Process->AddObserver(IterationEvent(), m_IterationFilterCommand); m_AbortTag = m_Process->AddObserver(AbortEvent(), m_AbortFilterCommand); } } SimpleFilterWatcher ::~SimpleFilterWatcher() { // Remove any observers we have on the old process object if (m_Process) { if (m_StartFilterCommand) { m_Process->RemoveObserver(m_StartTag); } if (m_EndFilterCommand) { m_Process->RemoveObserver(m_EndTag); } if (m_ProgressFilterCommand) { m_Process->RemoveObserver(m_ProgressTag); } if (m_IterationFilterCommand) { m_Process->RemoveObserver(m_IterationTag); } if (m_AbortFilterCommand) { m_Process->RemoveObserver(m_AbortTag); } } } } // end namespace itk <commit_msg>BUG: Added copy constructor and operator= so filter watcher properly manages commands and observers<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkSimpleFilterWatcher.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. Portions of this code are covered under the VTK copyright. See VTKCopyright.txt or http://www.kitware.com/VTKCopyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "itkSimpleFilterWatcher.h" namespace itk { SimpleFilterWatcher ::SimpleFilterWatcher(ProcessObject* o, char *comment) { // Initialize state m_Start = 0; m_End = 0; m_Process = o; m_Steps = 0; m_Comment = comment; m_TestAbort = false; #if defined(_COMPILER_VERSION) && (_COMPILER_VERSION == 730) m_Quiet = true; #else m_Quiet = false; #endif // Create a series of commands m_StartFilterCommand = CommandType::New(); m_EndFilterCommand = CommandType::New(); m_ProgressFilterCommand = CommandType::New(); m_IterationFilterCommand = CommandType::New(); m_AbortFilterCommand = CommandType::New(); // Assign the callbacks m_StartFilterCommand->SetCallbackFunction(this, &SimpleFilterWatcher::StartFilter); m_EndFilterCommand->SetCallbackFunction(this, &SimpleFilterWatcher::EndFilter); m_ProgressFilterCommand->SetCallbackFunction(this, &SimpleFilterWatcher::ShowProgress); m_IterationFilterCommand->SetCallbackFunction(this, &SimpleFilterWatcher::ShowIteration); m_AbortFilterCommand->SetCallbackFunction(this, &SimpleFilterWatcher::ShowAbort); // Add the commands as observers m_StartTag = m_Process->AddObserver(StartEvent(), m_StartFilterCommand); m_EndTag = m_Process->AddObserver(EndEvent(), m_EndFilterCommand); m_ProgressTag = m_Process->AddObserver(ProgressEvent(), m_ProgressFilterCommand); m_IterationTag = m_Process->AddObserver(IterationEvent(), m_IterationFilterCommand); m_AbortTag = m_Process->AddObserver(AbortEvent(), m_AbortFilterCommand); } SimpleFilterWatcher ::SimpleFilterWatcher() { // Initialize state m_Start = 0; m_End = 0; m_Steps = 0; m_Comment = "Not watching an object"; m_TestAbort = false; #if defined(_COMPILER_VERSION) && (_COMPILER_VERSION == 730) m_Quiet = true; #else m_Quiet = false; #endif m_Process = 0; } SimpleFilterWatcher ::SimpleFilterWatcher(const SimpleFilterWatcher &watch) { // Remove any observers we have on the old process object if (m_Process) { if (m_StartFilterCommand) { m_Process->RemoveObserver(m_StartTag); } if (m_EndFilterCommand) { m_Process->RemoveObserver(m_EndTag); } if (m_ProgressFilterCommand) { m_Process->RemoveObserver(m_ProgressTag); } if (m_IterationFilterCommand) { m_Process->RemoveObserver(m_IterationTag); } if (m_AbortFilterCommand) { m_Process->RemoveObserver(m_AbortTag); } } // Initialize state m_Start = watch.m_Start; m_End = watch.m_End; m_Process = watch.m_Process; m_Steps = watch.m_Steps; m_Comment = watch.m_Comment; m_TestAbort = watch.m_TestAbort; m_Quiet = watch.m_Quiet; m_StartTag = 0; m_EndTag = 0; m_ProgressTag = 0; m_IterationTag = 0; m_AbortTag = 0; // Create a series of commands if (m_Process) { m_StartFilterCommand = CommandType::New(); m_EndFilterCommand = CommandType::New(); m_ProgressFilterCommand = CommandType::New(); m_IterationFilterCommand = CommandType::New(); m_AbortFilterCommand = CommandType::New(); // Assign the callbacks m_StartFilterCommand->SetCallbackFunction(this, &SimpleFilterWatcher::StartFilter); m_EndFilterCommand->SetCallbackFunction(this, &SimpleFilterWatcher::EndFilter); m_ProgressFilterCommand->SetCallbackFunction(this, &SimpleFilterWatcher::ShowProgress); m_IterationFilterCommand->SetCallbackFunction(this, &SimpleFilterWatcher::ShowIteration); m_AbortFilterCommand->SetCallbackFunction(this, &SimpleFilterWatcher::ShowAbort); // Add the commands as observers m_StartTag = m_Process->AddObserver(StartEvent(), m_StartFilterCommand); m_EndTag = m_Process->AddObserver(EndEvent(), m_EndFilterCommand); m_ProgressTag = m_Process->AddObserver(ProgressEvent(), m_ProgressFilterCommand); m_IterationTag = m_Process->AddObserver(IterationEvent(), m_IterationFilterCommand); m_AbortTag = m_Process->AddObserver(AbortEvent(), m_AbortFilterCommand); } } void SimpleFilterWatcher ::operator=(const SimpleFilterWatcher &watch) { // Remove any observers we have on the old process object if (m_Process) { if (m_StartFilterCommand) { m_Process->RemoveObserver(m_StartTag); } if (m_EndFilterCommand) { m_Process->RemoveObserver(m_EndTag); } if (m_ProgressFilterCommand) { m_Process->RemoveObserver(m_ProgressTag); } if (m_IterationFilterCommand) { m_Process->RemoveObserver(m_IterationTag); } if (m_AbortFilterCommand) { m_Process->RemoveObserver(m_AbortTag); } } // Initialize state m_Start = watch.m_Start; m_End = watch.m_End; m_Process = watch.m_Process; m_Steps = watch.m_Steps; m_Comment = watch.m_Comment; m_TestAbort = watch.m_TestAbort; m_Quiet = watch.m_Quiet; m_StartTag = 0; m_EndTag = 0; m_ProgressTag = 0; m_IterationTag = 0; m_AbortTag = 0; // Create a series of commands if (m_Process) { m_StartFilterCommand = CommandType::New(); m_EndFilterCommand = CommandType::New(); m_ProgressFilterCommand = CommandType::New(); m_IterationFilterCommand = CommandType::New(); m_AbortFilterCommand = CommandType::New(); // Assign the callbacks m_StartFilterCommand->SetCallbackFunction(this, &SimpleFilterWatcher::StartFilter); m_EndFilterCommand->SetCallbackFunction(this, &SimpleFilterWatcher::EndFilter); m_ProgressFilterCommand->SetCallbackFunction(this, &SimpleFilterWatcher::ShowProgress); m_IterationFilterCommand->SetCallbackFunction(this, &SimpleFilterWatcher::ShowIteration); m_AbortFilterCommand->SetCallbackFunction(this, &SimpleFilterWatcher::ShowAbort); // Add the commands as observers m_StartTag = m_Process->AddObserver(StartEvent(), m_StartFilterCommand); m_EndTag = m_Process->AddObserver(EndEvent(), m_EndFilterCommand); m_ProgressTag = m_Process->AddObserver(ProgressEvent(), m_ProgressFilterCommand); m_IterationTag = m_Process->AddObserver(IterationEvent(), m_IterationFilterCommand); m_AbortTag = m_Process->AddObserver(AbortEvent(), m_AbortFilterCommand); } } SimpleFilterWatcher ::~SimpleFilterWatcher() { // Remove any observers we have on the old process object if (m_Process) { if (m_StartFilterCommand) { m_Process->RemoveObserver(m_StartTag); } if (m_EndFilterCommand) { m_Process->RemoveObserver(m_EndTag); } if (m_ProgressFilterCommand) { m_Process->RemoveObserver(m_ProgressTag); } if (m_IterationFilterCommand) { m_Process->RemoveObserver(m_IterationTag); } if (m_AbortFilterCommand) { m_Process->RemoveObserver(m_AbortTag); } } } } // end namespace itk <|endoftext|>
<commit_before>/** * This file implements a command line utility to interact * with the `d2` library. */ #include <boost/exception/diagnostic_information.hpp> #include <boost/exception/get_error_info.hpp> #include <boost/filesystem/operations.hpp> #include <boost/format.hpp> #include <boost/lexical_cast.hpp> #include <boost/make_shared.hpp> #include <boost/program_options.hpp> #include <boost/shared_ptr.hpp> #include <cstdlib> // EXIT_FAILURE, EXIT_SUCCESS #include <d2/core/diagnostic.hpp> #include <d2/core/exceptions.hpp> #include <d2/core/filesystem.hpp> #include <d2/core/synchronization_skeleton.hpp> #include <exception> #include <iostream> #include <string> namespace { namespace po = boost::program_options; class Driver { /** * Return a string representation of the data associated to an `ErrorTag`. * * If no data associated to that tag is present in the exception object, * `default_` is returned instead. */ template <typename ErrorTag, typename Exception> static std::string get_error_info(Exception const& e, std::string default_ = "unavailable") { typedef typename ErrorTag::value_type Info; Info const* info = boost::get_error_info<ErrorTag>(e); return info ? boost::lexical_cast<std::string>(*info) : default_; } typedef d2::core::synchronization_skeleton Skeleton; //! Print an error to the standard error stream with a trailing newline. template <typename Printable> static void error(Printable const& p) { std::cerr << "d2: error: " << p << '\n'; } /** * Return a pointer to a `synchronization_skeleton` loaded with the data * found in the repository, or a default initialized `shared_ptr` if * anything goes wrong. */ boost::shared_ptr<Skeleton> create_skeleton() const { if (!boost::filesystem::exists(repo)) { error(repo + " does not exist"); return boost::shared_ptr<Skeleton>(); } try { return boost::make_shared<Skeleton>(repo); } catch (d2::core::filesystem_error const& e) { error("unable to open the repository at " + repo); if (debug) error(boost::diagnostic_information(e)); } catch (d2::EventTypeException const& e) { std::string actual_type = get_error_info<d2::ActualType>(e); std::string expected_type = get_error_info<d2::ExpectedType>(e); error(boost::format( "while building the graphs:\n" " encountered an event of type %1%\n" " while expecting an event of type %2%") % actual_type % expected_type); if (debug) error(boost::diagnostic_information(e)); } catch (d2::UnexpectedReleaseException const& e) { std::string lock = get_error_info<d2::ReleasedLock>(e); std::string thread = get_error_info<d2::ReleasingThread>(e); error(boost::format( "while building the graphs:\n" " lock %1% was unexpectedly released by thread %2%") % lock % thread); if (debug) error(boost::diagnostic_information(e)); } return boost::shared_ptr<Skeleton>(); } bool parse_command_line(int argc, char const* argv[]) { po::variables_map args; po::options_description visible, hidden, all; po::positional_options_description positionals; bool help = false; visible.add_options() ( "help,h", po::bool_switch(&help), "produce help message and exit" )( "analyze", po::bool_switch(&analyze)->default_value(true, "true"), "perform the analysis for deadlocks" )( "stats", po::bool_switch(&stats), "produce statistics about the usage of locks and threads" )( "debug", po::bool_switch(&debug), "enable special debugging output" ) ; hidden.add_options() ( "repo-path", po::value<std::string>(&repo), "path of the repository to examine" ) ; positionals.add("repo-path", 1); all.add(visible).add(hidden); po::command_line_parser parser(argc, argv); try { po::store(parser.options(all).positional(positionals).run(), args); } catch (po::error const& e) { error(e.what()); return false; } po::notify(args); if (help) { std::cout << visible; return false; } if (repo.empty()) { error("missing input directory"); return false; } return true; } std::string repo; bool debug, analyze, stats; static void print_deadlock(d2::core::potential_deadlock const& dl) { std::cout << // 80 columns "\n--------------------------------------------------------------------------------\n"; d2::core::plain_text_explanation(std::cout, dl); std::cout << '\n'; } public: int run(int argc, char const* argv[]) { try { if (!parse_command_line(argc, argv)) return EXIT_FAILURE; boost::shared_ptr<Skeleton> skeleton = create_skeleton(); if (!skeleton) return EXIT_FAILURE; if (analyze) skeleton->on_deadlocks(print_deadlock); if (stats) { std::cout << boost::format( "number of threads: %1%\n" "number of distinct locks: %2%\n") % skeleton->number_of_threads() % skeleton->number_of_locks(); } } catch (std::exception const& e) { error("unknown problem:"); error(boost::diagnostic_information(e)); } return EXIT_SUCCESS; } }; } // end anonymous namespace int main(int argc, char const* argv[]) { Driver driver; return driver.run(argc, argv); } <commit_msg>Change default values of the options in the utility.<commit_after>/** * This file implements a command line utility to interact * with the `d2` library. */ #include <boost/exception/diagnostic_information.hpp> #include <boost/exception/get_error_info.hpp> #include <boost/filesystem/operations.hpp> #include <boost/format.hpp> #include <boost/lexical_cast.hpp> #include <boost/make_shared.hpp> #include <boost/program_options.hpp> #include <boost/shared_ptr.hpp> #include <cstdlib> // EXIT_FAILURE, EXIT_SUCCESS #include <d2/core/diagnostic.hpp> #include <d2/core/exceptions.hpp> #include <d2/core/filesystem.hpp> #include <d2/core/synchronization_skeleton.hpp> #include <exception> #include <iostream> #include <string> namespace { namespace po = boost::program_options; class Driver { /** * Return a string representation of the data associated to an `ErrorTag`. * * If no data associated to that tag is present in the exception object, * `default_` is returned instead. */ template <typename ErrorTag, typename Exception> static std::string get_error_info(Exception const& e, std::string default_ = "unavailable") { typedef typename ErrorTag::value_type Info; Info const* info = boost::get_error_info<ErrorTag>(e); return info ? boost::lexical_cast<std::string>(*info) : default_; } typedef d2::core::synchronization_skeleton Skeleton; //! Print an error to the standard error stream with a trailing newline. template <typename Printable> static void error(Printable const& p) { std::cerr << "d2: error: " << p << '\n'; } /** * Return a pointer to a `synchronization_skeleton` loaded with the data * found in the repository, or a default initialized `shared_ptr` if * anything goes wrong. */ boost::shared_ptr<Skeleton> create_skeleton() const { if (!boost::filesystem::exists(repo)) { error(repo + " does not exist"); return boost::shared_ptr<Skeleton>(); } try { return boost::make_shared<Skeleton>(repo); } catch (d2::core::filesystem_error const& e) { error("unable to open the repository at " + repo); if (debug) error(boost::diagnostic_information(e)); } catch (d2::EventTypeException const& e) { std::string actual_type = get_error_info<d2::ActualType>(e); std::string expected_type = get_error_info<d2::ExpectedType>(e); error(boost::format( "while building the graphs:\n" " encountered an event of type %1%\n" " while expecting an event of type %2%") % actual_type % expected_type); if (debug) error(boost::diagnostic_information(e)); } catch (d2::UnexpectedReleaseException const& e) { std::string lock = get_error_info<d2::ReleasedLock>(e); std::string thread = get_error_info<d2::ReleasingThread>(e); error(boost::format( "while building the graphs:\n" " lock %1% was unexpectedly released by thread %2%") % lock % thread); if (debug) error(boost::diagnostic_information(e)); } return boost::shared_ptr<Skeleton>(); } bool parse_command_line(int argc, char const* argv[]) { po::variables_map args; po::options_description visible, hidden, all; po::positional_options_description positionals; bool help; visible.add_options() ( "help,h", po::bool_switch(&help)->default_value(false, "false"), "produce help message and exit" )( "analyze", // See below; we'll give --analyze its real default value later. po::bool_switch(&analyze)->default_value(false, "enabled by default if --stats is not specified"), "perform the analysis for deadlocks" )( "stats", po::bool_switch(&stats)->default_value(false, "false"), "produce statistics about the usage of locks and threads" )( "debug", po::bool_switch(&debug)->default_value(false, "false"), "enable special debugging output" ) ; hidden.add_options() ( "repo-path", po::value<std::string>(&repo), "path of the repository to examine" ) ; positionals.add("repo-path", 1); all.add(visible).add(hidden); po::command_line_parser parser(argc, argv); try { po::store(parser.options(all).positional(positionals).run(), args); } catch (po::error const& e) { error(e.what()); return false; } po::notify(args); // If neither --stats nor --analyze is specified, --analyze is set // by default. if (!stats && !analyze) analyze = true; if (help) { std::cout << visible; return false; } if (repo.empty()) { error("missing input directory"); return false; } return true; } std::string repo; bool debug, analyze, stats; static void print_deadlock(d2::core::potential_deadlock const& dl) { std::cout << // 80 columns "\n--------------------------------------------------------------------------------\n"; d2::core::plain_text_explanation(std::cout, dl); std::cout << '\n'; } public: int run(int argc, char const* argv[]) { try { if (!parse_command_line(argc, argv)) return EXIT_FAILURE; boost::shared_ptr<Skeleton> skeleton = create_skeleton(); if (!skeleton) return EXIT_FAILURE; if (analyze) skeleton->on_deadlocks(print_deadlock); if (stats) { std::cout << boost::format( "number of threads: %1%\n" "number of distinct locks: %2%\n") % skeleton->number_of_threads() % skeleton->number_of_locks(); } } catch (std::exception const& e) { error("unknown problem:"); error(boost::diagnostic_information(e)); return EXIT_FAILURE; } return EXIT_SUCCESS; } }; } // end anonymous namespace int main(int argc, char const* argv[]) { Driver driver; return driver.run(argc, argv); } <|endoftext|>
<commit_before>/* * BackwardChainer.cc * * Copyright (C) 2014-2017 OpenCog Foundation * * Authors: Misgana Bayetta <misgana.bayetta@gmail.com> October 2014 * William Ma <https://github.com/williampma> * Nil Geisweiller 2016-2017 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <random> #include <boost/range/algorithm/lower_bound.hpp> #include <opencog/util/random.h> #include <opencog/atomutils/FindUtils.h> #include <opencog/atomutils/Substitutor.h> #include <opencog/atomutils/Unify.h> #include <opencog/atomutils/TypeUtils.h> #include <opencog/atoms/pattern/PatternLink.h> #include <opencog/atoms/pattern/BindLink.h> #include <opencog/query/BindLinkAPI.h> #include "BackwardChainer.h" #include "BackwardChainerPMCB.h" #include "UnifyPMCB.h" #include "BCLogger.h" using namespace opencog; BackwardChainer::BackwardChainer(AtomSpace& as, const Handle& rbs, const Handle& target, const Handle& vardecl, const Handle& focus_set, // TODO: // support // focus_set const BITNodeFitness& fitness) : _fcs_maximum_size(2000), _as(as), _configReader(as, rbs), _bit(as, target, vardecl, fitness), _iteration(0), _last_expansion_andbit(nullptr), _rules(_configReader.get_rules()) { } UREConfigReader& BackwardChainer::get_config() { return _configReader; } const UREConfigReader& BackwardChainer::get_config() const { return _configReader; } void BackwardChainer::do_chain() { while (not termination()) { do_step(); } } void BackwardChainer::do_step() { bc_logger().debug("Iteration %d", _iteration); _iteration++; expand_bit(); fulfill_bit(); reduce_bit(); } bool BackwardChainer::termination() { return _configReader.get_maximum_iterations() <= _iteration; } Handle BackwardChainer::get_results() const { HandleSeq results(_results.begin(), _results.end()); return _as.add_link(SET_LINK, results); } void BackwardChainer::expand_bit() { // This is kinda of hack before meta rules are fully supported by // the Rule class. size_t rules_size = _rules.size(); _rules.expand_meta_rules(_as); // If the rule set has changed we need to reset the exhausted // flags. if (rules_size != _rules.size()) { _bit.reset_exhausted_flags(); bc_logger().debug() << "The rule set has gone from " << rules_size << " rules to " << _rules.size() << ". All exhausted flags have been reset."; } // Reset _last_expansion_fcs _last_expansion_andbit = nullptr; if (_bit.empty()) { _last_expansion_andbit = _bit.init(); } else { // Select an FCS (i.e. and-BIT) and expand it AndBIT* andbit = select_expansion_andbit(); LAZY_BC_LOG_DEBUG << "Selected and-BIT for expansion:" << std::endl << andbit->to_string(); expand_bit(*andbit); } } void BackwardChainer::expand_bit(AndBIT& andbit) { // Select leaf BITNode* bitleaf = andbit.select_leaf(); if (bitleaf) { LAZY_BC_LOG_DEBUG << "Selected BIT-node for expansion:" << std::endl << bitleaf->to_string(); } else { bc_logger().debug() << "All BIT-nodes of this and-BIT are exhausted " << "(or possibly fulfilled). Abort expansion."; andbit.exhausted = true; return; } // Build the leaf vardecl from fcs Handle vardecl = andbit.fcs.is_defined() ? filter_vardecl(BindLinkCast(andbit.fcs)->get_vardecl(), bitleaf->body) : Handle::UNDEFINED; // Select a valid rule Rule rule = select_rule(*bitleaf, vardecl); // Add the rule in the _bit.bit_as to make comparing atoms easier // as well as logging more consistent. rule.add(_bit.bit_as); if (not rule.is_valid()) { bc_logger().debug("No valid rule for the selected BIT-node, abort expansion"); return; } LAZY_BC_LOG_DEBUG << "Selected rule for BIT expansion:" << std::endl << rule.to_string(); _last_expansion_andbit = _bit.expand(andbit, *bitleaf, rule); } void BackwardChainer::fulfill_bit() { if (_bit.empty()) { bc_logger().warn("Cannot fulfill an empty BIT!"); return; } // Select an and-BIT for fulfillment const AndBIT* andbit = select_fulfillment_andbit(); if (andbit == nullptr) { bc_logger().debug() << "Cannot fulfill an empty and-BIT. " << "Abort BIT fulfillment"; return; } LAZY_BC_LOG_DEBUG << "Selected and-BIT for fulfillment:" << std::endl << oc_to_string(andbit->fcs); fulfill_fcs(andbit->fcs); } void BackwardChainer::fulfill_fcs(const Handle& fcs) { // Temporary atomspace to not pollute _as with intermediary // results AtomSpace tmp_as(&_as); // Run the FCS and add the results in _as Handle hresult = bindlink(&tmp_as, fcs); HandleSeq results; for (const Handle& result : hresult->getOutgoingSet()) results.push_back(_as.add_atom(result)); LAZY_BC_LOG_DEBUG << "Results:" << std::endl << results; _results.insert(results.begin(), results.end()); } AndBIT* BackwardChainer::select_expansion_andbit() { // Calculate distribution based on a (poor) estimate of the // probablity of a and-BIT within the path of the solution. for (const AndBIT& andbit : _bit.andbits) weights.push_back(operator()(andbit)); // Debug log if (bc_logger().is_debug_enabled()) { OC_ASSERT(weights.size() == _bit.andbits.size()); std::stringstream ss; ss << "Weighted and-BITs:"; for (size_t i = 0; i < weights.size(); i++) ss << std::endl << weights[i] << " " << _bit.andbits[i].fcs->idToString(); bc_logger().debug() << ss.str(); } // Sample andbits according to this distribution std::discrete_distribution<size_t> dist(weights.begin(), weights.end()); return &rand_element(_bit.andbits, dist); } const AndBIT* BackwardChainer::select_fulfillment_andbit() const { return _last_expansion_andbit; } void BackwardChainer::reduce_bit() { // TODO: reset exhausted flags related to the removed and-BITs. // TODO: remove least likely and-BITs // // Remove and-BITs above a certain size. // auto complex_lt = [&](const AndBIT& andbit, size_t max_size) { // return andbit.fcs->size() < max_size; }; // auto it = boost::lower_bound(_bit.andbits, _fcs_maximum_size, complex_lt); // size_t previous_size = _bit.andbits.size(); // _bit.erase(it, _bit.andbits.end()); // if (size_t removed_andbits = previous_size - _bit.andbits.size()) { // LAZY_BC_LOG_DEBUG << "Removed " << removed_andbits // << " overly complex and-BITs from the BIT"; // } } Rule BackwardChainer::select_rule(BITNode& target, const Handle& vardecl) { // The rule is randomly selected amongst the valid ones, with // probability of selection being proportional to its weight. const RuleSet valid_rules = get_valid_rules(target, vardecl); if (valid_rules.empty()) { target.exhausted = true; return Rule(); } // Log all valid rules and their weights if (bc_logger().is_debug_enabled()) { std::stringstream ss; ss << "The following rules are valid:"; for (const Rule& r : valid_rules) ss << std::endl << r.get_name(); LAZY_BC_LOG_DEBUG << ss.str(); } return select_rule(valid_rules); } Rule BackwardChainer::select_rule(const RuleSet& rules) { // Build weight vector to do weighted random selection std::vector<double> weights; for (const Rule& rule : rules) weights.push_back(rule.get_weight()); // No rule exhaustion, sample one according to the distribution std::discrete_distribution<size_t> dist(weights.begin(), weights.end()); return rand_element(rules, dist); } RuleSet BackwardChainer::get_valid_rules(const BITNode& target, const Handle& vardecl) { // Generate all valid rules RuleSet valid_rules; for (const Rule& rule : _rules) { // For now ignore meta rules as they are forwardly applied in // expand_bit() if (rule.is_meta()) continue; RuleSet unified_rules = rule.unify_target(target.body, vardecl); // Insert only rules with positive probability of success RuleSet pos_rules; for (const Rule& rule : unified_rules) { double p = (_bit.is_in(rule, target) ? 0.0 : 1.0) * rule.get_weight(); if (p > 0) pos_rules.insert(rule); } valid_rules.insert(pos_rules.begin(), pos_rules.end()); } return valid_rules; } double BackwardChainer::complexity_factor(const AndBIT& andbit) const { return exp(-_configReader.get_complexity_penalty() * andbit.complexity()); } double BackwardChainer::operator()(const AndBIT& andbit) const { return (andbit.exhausted ? 0.0 : 1.0) * complexity_factor(andbit); } <commit_msg>Log rule weight<commit_after>/* * BackwardChainer.cc * * Copyright (C) 2014-2017 OpenCog Foundation * * Authors: Misgana Bayetta <misgana.bayetta@gmail.com> October 2014 * William Ma <https://github.com/williampma> * Nil Geisweiller 2016-2017 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <random> #include <boost/range/algorithm/lower_bound.hpp> #include <opencog/util/random.h> #include <opencog/atomutils/FindUtils.h> #include <opencog/atomutils/Substitutor.h> #include <opencog/atomutils/Unify.h> #include <opencog/atomutils/TypeUtils.h> #include <opencog/atoms/pattern/PatternLink.h> #include <opencog/atoms/pattern/BindLink.h> #include <opencog/query/BindLinkAPI.h> #include "BackwardChainer.h" #include "BackwardChainerPMCB.h" #include "UnifyPMCB.h" #include "BCLogger.h" using namespace opencog; BackwardChainer::BackwardChainer(AtomSpace& as, const Handle& rbs, const Handle& target, const Handle& vardecl, const Handle& focus_set, // TODO: // support // focus_set const BITNodeFitness& fitness) : _fcs_maximum_size(2000), _as(as), _configReader(as, rbs), _bit(as, target, vardecl, fitness), _iteration(0), _last_expansion_andbit(nullptr), _rules(_configReader.get_rules()) { } UREConfigReader& BackwardChainer::get_config() { return _configReader; } const UREConfigReader& BackwardChainer::get_config() const { return _configReader; } void BackwardChainer::do_chain() { while (not termination()) { do_step(); } } void BackwardChainer::do_step() { bc_logger().debug("Iteration %d", _iteration); _iteration++; expand_bit(); fulfill_bit(); reduce_bit(); } bool BackwardChainer::termination() { return _configReader.get_maximum_iterations() <= _iteration; } Handle BackwardChainer::get_results() const { HandleSeq results(_results.begin(), _results.end()); return _as.add_link(SET_LINK, results); } void BackwardChainer::expand_bit() { // This is kinda of hack before meta rules are fully supported by // the Rule class. size_t rules_size = _rules.size(); _rules.expand_meta_rules(_as); // If the rule set has changed we need to reset the exhausted // flags. if (rules_size != _rules.size()) { _bit.reset_exhausted_flags(); bc_logger().debug() << "The rule set has gone from " << rules_size << " rules to " << _rules.size() << ". All exhausted flags have been reset."; } // Reset _last_expansion_fcs _last_expansion_andbit = nullptr; if (_bit.empty()) { _last_expansion_andbit = _bit.init(); } else { // Select an FCS (i.e. and-BIT) and expand it AndBIT* andbit = select_expansion_andbit(); LAZY_BC_LOG_DEBUG << "Selected and-BIT for expansion:" << std::endl << andbit->to_string(); expand_bit(*andbit); } } void BackwardChainer::expand_bit(AndBIT& andbit) { // Select leaf BITNode* bitleaf = andbit.select_leaf(); if (bitleaf) { LAZY_BC_LOG_DEBUG << "Selected BIT-node for expansion:" << std::endl << bitleaf->to_string(); } else { bc_logger().debug() << "All BIT-nodes of this and-BIT are exhausted " << "(or possibly fulfilled). Abort expansion."; andbit.exhausted = true; return; } // Build the leaf vardecl from fcs Handle vardecl = andbit.fcs.is_defined() ? filter_vardecl(BindLinkCast(andbit.fcs)->get_vardecl(), bitleaf->body) : Handle::UNDEFINED; // Select a valid rule Rule rule = select_rule(*bitleaf, vardecl); // Add the rule in the _bit.bit_as to make comparing atoms easier // as well as logging more consistent. rule.add(_bit.bit_as); if (not rule.is_valid()) { bc_logger().debug("No valid rule for the selected BIT-node, abort expansion"); return; } LAZY_BC_LOG_DEBUG << "Selected rule for BIT expansion:" << std::endl << rule.to_string(); _last_expansion_andbit = _bit.expand(andbit, *bitleaf, rule); } void BackwardChainer::fulfill_bit() { if (_bit.empty()) { bc_logger().warn("Cannot fulfill an empty BIT!"); return; } // Select an and-BIT for fulfillment const AndBIT* andbit = select_fulfillment_andbit(); if (andbit == nullptr) { bc_logger().debug() << "Cannot fulfill an empty and-BIT. " << "Abort BIT fulfillment"; return; } LAZY_BC_LOG_DEBUG << "Selected and-BIT for fulfillment:" << std::endl << oc_to_string(andbit->fcs); fulfill_fcs(andbit->fcs); } void BackwardChainer::fulfill_fcs(const Handle& fcs) { // Temporary atomspace to not pollute _as with intermediary // results AtomSpace tmp_as(&_as); // Run the FCS and add the results in _as Handle hresult = bindlink(&tmp_as, fcs); HandleSeq results; for (const Handle& result : hresult->getOutgoingSet()) results.push_back(_as.add_atom(result)); LAZY_BC_LOG_DEBUG << "Results:" << std::endl << results; _results.insert(results.begin(), results.end()); } AndBIT* BackwardChainer::select_expansion_andbit() { // Calculate distribution based on a (poor) estimate of the // probablity of a and-BIT being within the path of the solution. std::vector<double> weights; for (const AndBIT& andbit : _bit.andbits) weights.push_back(operator()(andbit)); // Debug log if (bc_logger().is_debug_enabled()) { OC_ASSERT(weights.size() == _bit.andbits.size()); std::stringstream ss; ss << "Weighted and-BITs:"; for (size_t i = 0; i < weights.size(); i++) ss << std::endl << weights[i] << " " << _bit.andbits[i].fcs->idToString(); bc_logger().debug() << ss.str(); } // Sample andbits according to this distribution std::discrete_distribution<size_t> dist(weights.begin(), weights.end()); return &rand_element(_bit.andbits, dist); } const AndBIT* BackwardChainer::select_fulfillment_andbit() const { return _last_expansion_andbit; } void BackwardChainer::reduce_bit() { // TODO: reset exhausted flags related to the removed and-BITs. // TODO: remove least likely and-BITs // // Remove and-BITs above a certain size. // auto complex_lt = [&](const AndBIT& andbit, size_t max_size) { // return andbit.fcs->size() < max_size; }; // auto it = boost::lower_bound(_bit.andbits, _fcs_maximum_size, complex_lt); // size_t previous_size = _bit.andbits.size(); // _bit.erase(it, _bit.andbits.end()); // if (size_t removed_andbits = previous_size - _bit.andbits.size()) { // LAZY_BC_LOG_DEBUG << "Removed " << removed_andbits // << " overly complex and-BITs from the BIT"; // } } Rule BackwardChainer::select_rule(BITNode& target, const Handle& vardecl) { // The rule is randomly selected amongst the valid ones, with // probability of selection being proportional to its weight. const RuleSet valid_rules = get_valid_rules(target, vardecl); if (valid_rules.empty()) { target.exhausted = true; return Rule(); } // Log all valid rules and their weights if (bc_logger().is_debug_enabled()) { std::stringstream ss; ss << "The following weighted rules are valid:"; for (const Rule& r : valid_rules) ss << std::endl << r.get_weight() << " " << r.get_name(); LAZY_BC_LOG_DEBUG << ss.str(); } return select_rule(valid_rules); } Rule BackwardChainer::select_rule(const RuleSet& rules) { // Build weight vector to do weighted random selection std::vector<double> weights; for (const Rule& rule : rules) weights.push_back(rule.get_weight()); // No rule exhaustion, sample one according to the distribution std::discrete_distribution<size_t> dist(weights.begin(), weights.end()); return rand_element(rules, dist); } RuleSet BackwardChainer::get_valid_rules(const BITNode& target, const Handle& vardecl) { // Generate all valid rules RuleSet valid_rules; for (const Rule& rule : _rules) { // For now ignore meta rules as they are forwardly applied in // expand_bit() if (rule.is_meta()) continue; RuleSet unified_rules = rule.unify_target(target.body, vardecl); // Insert only rules with positive probability of success RuleSet pos_rules; for (const Rule& rule : unified_rules) { double p = (_bit.is_in(rule, target) ? 0.0 : 1.0) * rule.get_weight(); if (p > 0) pos_rules.insert(rule); } valid_rules.insert(pos_rules.begin(), pos_rules.end()); } return valid_rules; } double BackwardChainer::complexity_factor(const AndBIT& andbit) const { return exp(-_configReader.get_complexity_penalty() * andbit.complexity()); } double BackwardChainer::operator()(const AndBIT& andbit) const { return (andbit.exhausted ? 0.0 : 1.0) * complexity_factor(andbit); } <|endoftext|>
<commit_before>/* * BackwardChainer.cc * * Copyright (C) 2014-2017 OpenCog Foundation * * Authors: Misgana Bayetta <misgana.bayetta@gmail.com> October 2014 * William Ma <https://github.com/williampma> * Nil Geisweiller 2016-2017 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <random> #include <boost/range/algorithm/lower_bound.hpp> #include <opencog/util/random.h> #include <opencog/atomutils/FindUtils.h> #include <opencog/unify/Unify.h> #include <opencog/atomutils/TypeUtils.h> #include <opencog/atoms/pattern/PatternLink.h> #include <opencog/atoms/pattern/BindLink.h> #include <opencog/query/BindLinkAPI.h> #include "BackwardChainer.h" #include "BackwardChainerPMCB.h" #include "../URELogger.h" using namespace opencog; BackwardChainer::BackwardChainer(AtomSpace& as, const Handle& rbs, const Handle& target, const Handle& vardecl, AtomSpace* trace_as, AtomSpace* control_as, const Handle& focus_set, // TODO: // support // focus_set const BITNodeFitness& bitnode_fitness, const AndBITFitness& andbit_fitness) : _as(as), _configReader(as, rbs), _bit(as, target, vardecl, bitnode_fitness), _andbit_fitness(andbit_fitness), _trace_recorder(trace_as), _control(_configReader, _bit, control_as), _rules(_control.rules), _iteration(0), _last_expansion_andbit(nullptr) { // Record the target in the trace atomspace _trace_recorder.target(target); } UREConfig& BackwardChainer::get_config() { return _configReader; } const UREConfig& BackwardChainer::get_config() const { return _configReader; } void BackwardChainer::do_chain() { ure_logger().debug("Start Backward Chaining"); LAZY_URE_LOG_DEBUG << "With rule set:" << std::endl << oc_to_string(_rules); while (not termination()) { do_step(); } LAZY_URE_LOG_DEBUG << "Finished Backward Chaining with solutions:" << std::endl << get_results()->to_string(); } void BackwardChainer::do_step() { _iteration++; ure_logger().debug() << "Iteration " << _iteration << "/" << _configReader.get_maximum_iterations(); expand_bit(); fulfill_bit(); reduce_bit(); } bool BackwardChainer::termination() { return _configReader.get_maximum_iterations() <= _iteration; } Handle BackwardChainer::get_results() const { HandleSeq results(_results.begin(), _results.end()); return _as.add_link(SET_LINK, results); } void BackwardChainer::expand_meta_rules() { // This is kinda of hack before meta rules are fully supported by // the Rule class. size_t rules_size = _rules.size(); _rules.expand_meta_rules(_as); // If the rule set has changed we need to reset the exhausted // flags. if (rules_size != _rules.size()) { _bit.reset_exhausted_flags(); ure_logger().debug() << "The rule set has gone from " << rules_size << " rules to " << _rules.size() << ". All exhausted flags have been reset."; } } void BackwardChainer::expand_bit() { // Expand meta rules, before they are fully supported expand_meta_rules(); // Reset _last_expansion_fcs _last_expansion_andbit = nullptr; if (_bit.empty()) { _last_expansion_andbit = _bit.init(); // Record the initial and-BIT in the trace atomspace _trace_recorder.andbit(*_last_expansion_andbit); } else { // Select an FCS (i.e. and-BIT) and expand it AndBIT* andbit = select_expansion_andbit(); LAZY_URE_LOG_DEBUG << "Selected and-BIT for expansion:" << std::endl << andbit->to_string(); expand_bit(*andbit); } } void BackwardChainer::expand_bit(AndBIT& andbit) { // Select leaf BITNode* bitleaf = andbit.select_leaf(); if (bitleaf) { LAZY_URE_LOG_DEBUG << "Selected BIT-node for expansion:" << std::endl << bitleaf->to_string(); } else { ure_logger().debug() << "All BIT-nodes of this and-BIT are exhausted " << "(or possibly fulfilled). Abort expansion."; andbit.exhausted = true; return; } // Select rule for expansion RuleSelection rule_sel = _control.select_rule(andbit, *bitleaf); Rule rule(rule_sel.first.first); Unify::TypedSubstitution ts(rule_sel.first.second); double prob(rule_sel.second); // Add the rule in the _bit.bit_as to make comparing atoms easier // as well as logging more consistent. rule.add(_bit.bit_as); // Abort expansion if ill rule if (not rule.is_valid()) { ure_logger().debug("No valid rule for the selected BIT-node, " "abort expansion"); return; } else if (rule.has_cycle()) { LAZY_URE_LOG_DEBUG << "The following rule has cycle (some premise " << "equals to conclusion), abort expansion:" << std::endl << rule.to_string(); return; } // Rule seems well, expand LAZY_URE_LOG_DEBUG << "Selected rule, with probability " << prob << " of success for BIT expansion:" << std::endl << rule.to_string(); // Expand andbit. Warning: after this call the reference on andbit // and bitleaf may no longer be valid because the container of // and-BITs might have been resorted. so we keep track of their // bodies for future use. Handle andbit_fcs = andbit.fcs; Handle bitleaf_body = bitleaf->body; _last_expansion_andbit = _bit.expand(andbit, *bitleaf, {rule, ts}, prob); // Record the expansion in the trace atomspace if (_last_expansion_andbit) { _trace_recorder.andbit(*_last_expansion_andbit); _trace_recorder.expansion(andbit_fcs, bitleaf_body, rule, *_last_expansion_andbit); } } void BackwardChainer::fulfill_bit() { if (_bit.empty()) { ure_logger().warn("Cannot fulfill an empty BIT!"); return; } // Select an and-BIT for fulfillment const AndBIT* andbit = select_fulfillment_andbit(); if (andbit == nullptr) { ure_logger().debug() << "Cannot fulfill an empty and-BIT. " << "Abort BIT fulfillment"; return; } LAZY_URE_LOG_DEBUG << "Selected and-BIT for fulfillment (fcs value):" << std::endl << andbit->fcs->id_to_string(); fulfill_fcs(andbit->fcs); } void BackwardChainer::fulfill_fcs(const Handle& fcs) { // Temporary atomspace to not pollute _as with intermediary // results AtomSpace tmp_as(&_as); // Run the FCS and add the results, if any, in _as. // // Warning: since tmp_as is a child of _as, TVs of existing atoms // in _as, that are modified by running fcs will be modified on // _as as well. This can create involontary TVs changes, hopefully // mitigated by the merging the TVs properly (for now the one with // the highest confidence wins). To avoid that side effect, we // could operate on a copy the atomspace, of its zone of focus. Or // alternatively modify some HypotheticalLink wrapping the atoms // of concerns instead of the atoms themselves, and only modify // the atoms if there are existing results to copy back to _as. Handle hresult = bindlink(&tmp_as, fcs); HandleSeq results; for (const Handle& result : hresult->getOutgoingSet()) results.push_back(_as.add_atom(result)); LAZY_URE_LOG_DEBUG << "Results:" << std::endl << results; _results.insert(results.begin(), results.end()); // Record the results in _trace_as for (const Handle& result : results) _trace_recorder.proof(fcs, result); } std::vector<double> BackwardChainer::expansion_anbit_weights() { std::vector<double> weights; for (const AndBIT& andbit : _bit.andbits) weights.push_back(operator()(andbit)); return weights; } AndBIT* BackwardChainer::select_expansion_andbit() { std::vector<double> weights = expansion_anbit_weights(); // Debug log if (ure_logger().is_debug_enabled()) { OC_ASSERT(weights.size() == _bit.andbits.size()); std::stringstream ss; ss << "Weighted and-BITs:"; for (size_t i = 0; i < weights.size(); i++) ss << std::endl << weights[i] << " " << _bit.andbits[i].fcs->id_to_string(); ure_logger().debug() << ss.str(); } // Sample andbits according to this distribution std::discrete_distribution<size_t> dist(weights.begin(), weights.end()); return &rand_element(_bit.andbits, dist); } const AndBIT* BackwardChainer::select_fulfillment_andbit() const { return _last_expansion_andbit; } void BackwardChainer::reduce_bit() { if (0 < _configReader.get_max_bit_size()) { // If the BIT size has reached its maximum, randomly remove // and-BITs so that the BIT size gets back below or equal to // its maximum. while (_configReader.get_max_bit_size() < _bit.size()) { // Randomly select an and-BIT that is unlikely to be used // for the remaining of the inferenceThe and-BITs to remove are // selected so that the least likely and-BITs to be // selected for expansion are removed first. remove_unlikely_expandable_andbit(); } } } void BackwardChainer::remove_unlikely_expandable_andbit() { std::vector<double> weights = expansion_anbit_weights(); std::discrete_distribution<size_t> dist(weights.begin(), weights.end()); std::vector<double> never_expand_probs; // Calculate the probability of never being expanded for the // remainder of the inference, thus (1-p) raised to the power of // _configReader.get_maximum_iterations() - _iteration. This makes // the assumption that the BIT (i.e. its and-BIT population) is // not gonna change from this point on, a false but OK assumption // for now. for (double p : dist.probabilities()) { double remaining_iterations = _configReader.get_maximum_iterations() - _iteration; double nep = std::pow(1 - p, remaining_iterations); never_expand_probs.push_back(nep); } // Fine log if (ure_logger().is_fine_enabled()) { OC_ASSERT(never_expand_probs.size() == _bit.andbits.size()); std::stringstream ss; ss << "Never expand probs and-BITs:"; for (size_t i = 0; i < never_expand_probs.size(); i++) ss << std::endl << never_expand_probs[i] << " " << _bit.andbits[i].fcs->id_to_string(); ure_logger().fine() << ss.str(); } std::discrete_distribution<size_t> never_expand_dist(never_expand_probs.begin(), never_expand_probs.end()); // Pick the and-BIT, remove it from the BIT and remove its // FCS from the bit atomspace. auto it = std::next(_bit.andbits.begin(), never_expand_dist(randGen())); LAZY_URE_LOG_DEBUG << "Remove " << it->fcs->id_to_string() << " from the BIT"; _bit.erase(it); } double BackwardChainer::complexity_factor(const AndBIT& andbit) const { return exp(-_configReader.get_complexity_penalty() * andbit.complexity); } double BackwardChainer::operator()(const AndBIT& andbit) const { return (andbit.exhausted ? 0.0 : 1.0) * _andbit_fitness(andbit) * complexity_factor(andbit); } <commit_msg>Remove crufty includes<commit_after>/* * BackwardChainer.cc * * Copyright (C) 2014-2017 OpenCog Foundation * * Authors: Misgana Bayetta <misgana.bayetta@gmail.com> October 2014 * William Ma <https://github.com/williampma> * Nil Geisweiller 2016-2017 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <opencog/util/random.h> #include <opencog/query/BindLinkAPI.h> #include <opencog/unify/Unify.h> #include "BackwardChainer.h" #include "BackwardChainerPMCB.h" #include "../URELogger.h" using namespace opencog; BackwardChainer::BackwardChainer(AtomSpace& as, const Handle& rbs, const Handle& target, const Handle& vardecl, AtomSpace* trace_as, AtomSpace* control_as, const Handle& focus_set, // TODO: // support // focus_set const BITNodeFitness& bitnode_fitness, const AndBITFitness& andbit_fitness) : _as(as), _configReader(as, rbs), _bit(as, target, vardecl, bitnode_fitness), _andbit_fitness(andbit_fitness), _trace_recorder(trace_as), _control(_configReader, _bit, control_as), _rules(_control.rules), _iteration(0), _last_expansion_andbit(nullptr) { // Record the target in the trace atomspace _trace_recorder.target(target); } UREConfig& BackwardChainer::get_config() { return _configReader; } const UREConfig& BackwardChainer::get_config() const { return _configReader; } void BackwardChainer::do_chain() { ure_logger().debug("Start Backward Chaining"); LAZY_URE_LOG_DEBUG << "With rule set:" << std::endl << oc_to_string(_rules); while (not termination()) { do_step(); } LAZY_URE_LOG_DEBUG << "Finished Backward Chaining with solutions:" << std::endl << get_results()->to_string(); } void BackwardChainer::do_step() { _iteration++; ure_logger().debug() << "Iteration " << _iteration << "/" << _configReader.get_maximum_iterations(); expand_bit(); fulfill_bit(); reduce_bit(); } bool BackwardChainer::termination() { return _configReader.get_maximum_iterations() <= _iteration; } Handle BackwardChainer::get_results() const { HandleSeq results(_results.begin(), _results.end()); return _as.add_link(SET_LINK, results); } void BackwardChainer::expand_meta_rules() { // This is kinda of hack before meta rules are fully supported by // the Rule class. size_t rules_size = _rules.size(); _rules.expand_meta_rules(_as); // If the rule set has changed we need to reset the exhausted // flags. if (rules_size != _rules.size()) { _bit.reset_exhausted_flags(); ure_logger().debug() << "The rule set has gone from " << rules_size << " rules to " << _rules.size() << ". All exhausted flags have been reset."; } } void BackwardChainer::expand_bit() { // Expand meta rules, before they are fully supported expand_meta_rules(); // Reset _last_expansion_fcs _last_expansion_andbit = nullptr; if (_bit.empty()) { _last_expansion_andbit = _bit.init(); // Record the initial and-BIT in the trace atomspace _trace_recorder.andbit(*_last_expansion_andbit); } else { // Select an FCS (i.e. and-BIT) and expand it AndBIT* andbit = select_expansion_andbit(); LAZY_URE_LOG_DEBUG << "Selected and-BIT for expansion:" << std::endl << andbit->to_string(); expand_bit(*andbit); } } void BackwardChainer::expand_bit(AndBIT& andbit) { // Select leaf BITNode* bitleaf = andbit.select_leaf(); if (bitleaf) { LAZY_URE_LOG_DEBUG << "Selected BIT-node for expansion:" << std::endl << bitleaf->to_string(); } else { ure_logger().debug() << "All BIT-nodes of this and-BIT are exhausted " << "(or possibly fulfilled). Abort expansion."; andbit.exhausted = true; return; } // Select rule for expansion RuleSelection rule_sel = _control.select_rule(andbit, *bitleaf); Rule rule(rule_sel.first.first); Unify::TypedSubstitution ts(rule_sel.first.second); double prob(rule_sel.second); // Add the rule in the _bit.bit_as to make comparing atoms easier // as well as logging more consistent. rule.add(_bit.bit_as); // Abort expansion if ill rule if (not rule.is_valid()) { ure_logger().debug("No valid rule for the selected BIT-node, " "abort expansion"); return; } else if (rule.has_cycle()) { LAZY_URE_LOG_DEBUG << "The following rule has cycle (some premise " << "equals to conclusion), abort expansion:" << std::endl << rule.to_string(); return; } // Rule seems well, expand LAZY_URE_LOG_DEBUG << "Selected rule, with probability " << prob << " of success for BIT expansion:" << std::endl << rule.to_string(); // Expand andbit. Warning: after this call the reference on andbit // and bitleaf may no longer be valid because the container of // and-BITs might have been resorted. so we keep track of their // bodies for future use. Handle andbit_fcs = andbit.fcs; Handle bitleaf_body = bitleaf->body; _last_expansion_andbit = _bit.expand(andbit, *bitleaf, {rule, ts}, prob); // Record the expansion in the trace atomspace if (_last_expansion_andbit) { _trace_recorder.andbit(*_last_expansion_andbit); _trace_recorder.expansion(andbit_fcs, bitleaf_body, rule, *_last_expansion_andbit); } } void BackwardChainer::fulfill_bit() { if (_bit.empty()) { ure_logger().warn("Cannot fulfill an empty BIT!"); return; } // Select an and-BIT for fulfillment const AndBIT* andbit = select_fulfillment_andbit(); if (andbit == nullptr) { ure_logger().debug() << "Cannot fulfill an empty and-BIT. " << "Abort BIT fulfillment"; return; } LAZY_URE_LOG_DEBUG << "Selected and-BIT for fulfillment (fcs value):" << std::endl << andbit->fcs->id_to_string(); fulfill_fcs(andbit->fcs); } void BackwardChainer::fulfill_fcs(const Handle& fcs) { // Temporary atomspace to not pollute _as with intermediary // results AtomSpace tmp_as(&_as); // Run the FCS and add the results, if any, in _as. // // Warning: since tmp_as is a child of _as, TVs of existing atoms // in _as, that are modified by running fcs will be modified on // _as as well. This can create involontary TVs changes, hopefully // mitigated by the merging the TVs properly (for now the one with // the highest confidence wins). To avoid that side effect, we // could operate on a copy the atomspace, of its zone of focus. Or // alternatively modify some HypotheticalLink wrapping the atoms // of concerns instead of the atoms themselves, and only modify // the atoms if there are existing results to copy back to _as. Handle hresult = bindlink(&tmp_as, fcs); HandleSeq results; for (const Handle& result : hresult->getOutgoingSet()) results.push_back(_as.add_atom(result)); LAZY_URE_LOG_DEBUG << "Results:" << std::endl << results; _results.insert(results.begin(), results.end()); // Record the results in _trace_as for (const Handle& result : results) _trace_recorder.proof(fcs, result); } std::vector<double> BackwardChainer::expansion_anbit_weights() { std::vector<double> weights; for (const AndBIT& andbit : _bit.andbits) weights.push_back(operator()(andbit)); return weights; } AndBIT* BackwardChainer::select_expansion_andbit() { std::vector<double> weights = expansion_anbit_weights(); // Debug log if (ure_logger().is_debug_enabled()) { OC_ASSERT(weights.size() == _bit.andbits.size()); std::stringstream ss; ss << "Weighted and-BITs:"; for (size_t i = 0; i < weights.size(); i++) ss << std::endl << weights[i] << " " << _bit.andbits[i].fcs->id_to_string(); ure_logger().debug() << ss.str(); } // Sample andbits according to this distribution std::discrete_distribution<size_t> dist(weights.begin(), weights.end()); return &rand_element(_bit.andbits, dist); } const AndBIT* BackwardChainer::select_fulfillment_andbit() const { return _last_expansion_andbit; } void BackwardChainer::reduce_bit() { if (0 < _configReader.get_max_bit_size()) { // If the BIT size has reached its maximum, randomly remove // and-BITs so that the BIT size gets back below or equal to // its maximum. while (_configReader.get_max_bit_size() < _bit.size()) { // Randomly select an and-BIT that is unlikely to be used // for the remaining of the inferenceThe and-BITs to remove are // selected so that the least likely and-BITs to be // selected for expansion are removed first. remove_unlikely_expandable_andbit(); } } } void BackwardChainer::remove_unlikely_expandable_andbit() { std::vector<double> weights = expansion_anbit_weights(); std::discrete_distribution<size_t> dist(weights.begin(), weights.end()); std::vector<double> never_expand_probs; // Calculate the probability of never being expanded for the // remainder of the inference, thus (1-p) raised to the power of // _configReader.get_maximum_iterations() - _iteration. This makes // the assumption that the BIT (i.e. its and-BIT population) is // not gonna change from this point on, a false but OK assumption // for now. for (double p : dist.probabilities()) { double remaining_iterations = _configReader.get_maximum_iterations() - _iteration; double nep = std::pow(1 - p, remaining_iterations); never_expand_probs.push_back(nep); } // Fine log if (ure_logger().is_fine_enabled()) { OC_ASSERT(never_expand_probs.size() == _bit.andbits.size()); std::stringstream ss; ss << "Never expand probs and-BITs:"; for (size_t i = 0; i < never_expand_probs.size(); i++) ss << std::endl << never_expand_probs[i] << " " << _bit.andbits[i].fcs->id_to_string(); ure_logger().fine() << ss.str(); } std::discrete_distribution<size_t> never_expand_dist(never_expand_probs.begin(), never_expand_probs.end()); // Pick the and-BIT, remove it from the BIT and remove its // FCS from the bit atomspace. auto it = std::next(_bit.andbits.begin(), never_expand_dist(randGen())); LAZY_URE_LOG_DEBUG << "Remove " << it->fcs->id_to_string() << " from the BIT"; _bit.erase(it); } double BackwardChainer::complexity_factor(const AndBIT& andbit) const { return exp(-_configReader.get_complexity_penalty() * andbit.complexity); } double BackwardChainer::operator()(const AndBIT& andbit) const { return (andbit.exhausted ? 0.0 : 1.0) * _andbit_fitness(andbit) * complexity_factor(andbit); } <|endoftext|>
<commit_before>// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <vespa/vespalib/testkit/test_kit.h> #include <vespa/eval/eval/tensor_function.h> #include <vespa/eval/instruction/replace_type_function.h> #include <vespa/eval/instruction/fast_rename_optimizer.h> #include <vespa/eval/eval/test/tensor_model.hpp> #include <vespa/eval/eval/test/eval_fixture.h> #include <vespa/vespalib/util/stringfmt.h> #include <vespa/vespalib/util/stash.h> using namespace vespalib; using namespace vespalib::eval; using namespace vespalib::eval::test; using namespace vespalib::eval::tensor_function; const ValueBuilderFactory &prod_factory = FastValueBuilderFactory::get(); EvalFixture::ParamRepo make_params() { return EvalFixture::ParamRepo() .add("x5", spec({x(5)}, N())) .add("x5f", spec(float_cells({x(5)}), N())) .add("x_m", spec({x({"a", "b", "c"})}, N())) .add("xy_mm", spec({x({"a", "b", "c"}),y({"d","e"})}, N())) .add("x5y3", spec({x(5),y(3)}, N())); } EvalFixture::ParamRepo param_repo = make_params(); void verify_optimized(const vespalib::string &expr) { EvalFixture fixture(prod_factory, expr, param_repo, true); EXPECT_EQUAL(fixture.result(), EvalFixture::ref(expr, param_repo)); auto info = fixture.find_all<ReplaceTypeFunction>(); EXPECT_EQUAL(info.size(), 1u); } void verify_not_optimized(const vespalib::string &expr) { EvalFixture fixture(prod_factory, expr, param_repo, true); EXPECT_EQUAL(fixture.result(), EvalFixture::ref(expr, param_repo)); auto info = fixture.find_all<ReplaceTypeFunction>(); EXPECT_TRUE(info.empty()); } TEST("require that non-transposing dense renames are optimized") { TEST_DO(verify_optimized("rename(x5,x,y)")); TEST_DO(verify_optimized("rename(x5,x,a)")); TEST_DO(verify_optimized("rename(x5y3,y,z)")); TEST_DO(verify_optimized("rename(x5y3,x,a)")); TEST_DO(verify_optimized("rename(x5y3,(x,y),(a,b))")); TEST_DO(verify_optimized("rename(x5y3,(x,y),(z,zz))")); TEST_DO(verify_optimized("rename(x5y3,(x,y),(y,z))")); TEST_DO(verify_optimized("rename(x5y3,(y,x),(b,a))")); } TEST("require that transposing dense renames are not optimized") { TEST_DO(verify_not_optimized("rename(x5y3,x,z)")); TEST_DO(verify_not_optimized("rename(x5y3,y,a)")); TEST_DO(verify_not_optimized("rename(x5y3,(x,y),(y,x))")); TEST_DO(verify_not_optimized("rename(x5y3,(x,y),(b,a))")); TEST_DO(verify_not_optimized("rename(x5y3,(y,x),(a,b))")); } TEST("require that non-dense renames may be optimized") { TEST_DO(verify_optimized("rename(x_m,x,y)")); TEST_DO(verify_optimized("rename(xy_mm,(x,y),(a,b))")); TEST_DO(verify_optimized("rename(xy_mm,(x,y),(y,z))")); TEST_DO(verify_not_optimized("rename(xy_mm,(x,y),(b,a))")); TEST_DO(verify_not_optimized("rename(xy_mm,(x,y),(y,x))")); } TEST("require that chained optimized renames are compacted into a single operation") { TEST_DO(verify_optimized("rename(rename(x5,x,y),y,z)")); } TEST("require that optimization works for float cells") { TEST_DO(verify_optimized("rename(x5f,x,y)")); } bool is_stable(const vespalib::string &from_spec, const vespalib::string &to_spec, const std::vector<vespalib::string> &from, const std::vector<vespalib::string> &to) { auto from_type = ValueType::from_spec(from_spec); auto to_type = ValueType::from_spec(to_spec); return FastRenameOptimizer::is_stable_rename(from_type, to_type, from, to); } TEST("require that rename is stable if dimension order is preserved") { EXPECT_TRUE(is_stable("tensor(a{},b{})", "tensor(a{},c{})", {"b"}, {"c"})); EXPECT_TRUE(is_stable("tensor(c[3],d[5])", "tensor(c[3],e[5])", {"d"}, {"e"})); EXPECT_TRUE(is_stable("tensor(a{},b{},c[3],d[5])", "tensor(a{},b{},c[3],e[5])", {"d"}, {"e"})); EXPECT_TRUE(is_stable("tensor(a{},b{},c[3],d[5])", "tensor(e{},f{},g[3],h[5])", {"a", "b", "c", "d"}, {"e", "f", "g", "h"})); } TEST("require that rename is unstable if nontrivial indexed dimensions change order") { EXPECT_FALSE(is_stable("tensor(c[3],d[5])", "tensor(d[5],e[3])", {"c"}, {"e"})); EXPECT_FALSE(is_stable("tensor(c[3],d[5])", "tensor(c[5],d[3])", {"c", "d"}, {"d", "c"})); } TEST("require that rename is unstable if mapped dimensions change order") { EXPECT_FALSE(is_stable("tensor(a{},b{})", "tensor(b{},c{})", {"a"}, {"c"})); EXPECT_FALSE(is_stable("tensor(a{},b{})", "tensor(a{},b{})", {"a", "b"}, {"b", "a"})); } TEST("require that rename can be stable if indexed and mapped dimensions change order") { EXPECT_TRUE(is_stable("tensor(a{},b{},c[3],d[5])", "tensor(a[3],b[5],c{},d{})", {"a", "b", "c", "d"}, {"c", "d", "a", "b"})); EXPECT_TRUE(is_stable("tensor(a{},b{},c[3],d[5])", "tensor(c[3],d[5],e{},f{})", {"a", "b"}, {"e", "f"})); } TEST("require that rename can be stable if trivial dimension is moved") { EXPECT_TRUE(is_stable("tensor(a[1],b{},c[3])", "tensor(b{},bb[1],c[3])", {"a"}, {"bb"})); EXPECT_TRUE(is_stable("tensor(a[1],b{},c[3])", "tensor(b{},c[3],cc[1])", {"a"}, {"cc"})); } TEST_MAIN() { TEST_RUN_ALL(); } <commit_msg>add more unit tests<commit_after>// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <vespa/vespalib/testkit/test_kit.h> #include <vespa/eval/eval/tensor_function.h> #include <vespa/eval/instruction/replace_type_function.h> #include <vespa/eval/instruction/fast_rename_optimizer.h> #include <vespa/eval/eval/test/tensor_model.hpp> #include <vespa/eval/eval/test/eval_fixture.h> #include <vespa/vespalib/util/stringfmt.h> #include <vespa/vespalib/util/stash.h> using namespace vespalib; using namespace vespalib::eval; using namespace vespalib::eval::test; using namespace vespalib::eval::tensor_function; const ValueBuilderFactory &prod_factory = FastValueBuilderFactory::get(); EvalFixture::ParamRepo make_params() { return EvalFixture::ParamRepo() .add("x5", spec({x(5)}, N())) .add("x5f", spec(float_cells({x(5)}), N())) .add("x_m", spec({x({"a", "b", "c"})}, N())) .add("xy_mm", spec({x({"a", "b", "c"}),y({"d","e"})}, N())) .add("x5y3z_m", spec({x(5),y(3),z({"a","b"})}, N())) .add("x5yz_m", spec({x(5),y({"a","b"}),z({"d","e"})}, N())) .add("x5y3", spec({x(5),y(3)}, N())); } EvalFixture::ParamRepo param_repo = make_params(); void verify_optimized(const vespalib::string &expr) { EvalFixture fixture(prod_factory, expr, param_repo, true); EXPECT_EQUAL(fixture.result(), EvalFixture::ref(expr, param_repo)); auto info = fixture.find_all<ReplaceTypeFunction>(); EXPECT_EQUAL(info.size(), 1u); } void verify_not_optimized(const vespalib::string &expr) { EvalFixture fixture(prod_factory, expr, param_repo, true); EXPECT_EQUAL(fixture.result(), EvalFixture::ref(expr, param_repo)); auto info = fixture.find_all<ReplaceTypeFunction>(); EXPECT_TRUE(info.empty()); } TEST("require that non-transposing dense renames are optimized") { TEST_DO(verify_optimized("rename(x5,x,y)")); TEST_DO(verify_optimized("rename(x5,x,a)")); TEST_DO(verify_optimized("rename(x5y3,y,z)")); TEST_DO(verify_optimized("rename(x5y3,x,a)")); TEST_DO(verify_optimized("rename(x5y3,(x,y),(a,b))")); TEST_DO(verify_optimized("rename(x5y3,(x,y),(z,zz))")); TEST_DO(verify_optimized("rename(x5y3,(x,y),(y,z))")); TEST_DO(verify_optimized("rename(x5y3,(y,x),(b,a))")); } TEST("require that transposing dense renames are not optimized") { TEST_DO(verify_not_optimized("rename(x5y3,x,z)")); TEST_DO(verify_not_optimized("rename(x5y3,y,a)")); TEST_DO(verify_not_optimized("rename(x5y3,(x,y),(y,x))")); TEST_DO(verify_not_optimized("rename(x5y3,(x,y),(b,a))")); TEST_DO(verify_not_optimized("rename(x5y3,(y,x),(a,b))")); } TEST("require that non-dense renames may be optimized") { TEST_DO(verify_optimized("rename(x_m,x,y)")); TEST_DO(verify_optimized("rename(xy_mm,(x,y),(a,b))")); TEST_DO(verify_optimized("rename(xy_mm,(x,y),(y,z))")); TEST_DO(verify_not_optimized("rename(xy_mm,(x,y),(b,a))")); TEST_DO(verify_not_optimized("rename(xy_mm,(x,y),(y,x))")); TEST_DO(verify_optimized("rename(x5y3z_m,(z),(a))")); TEST_DO(verify_optimized("rename(x5y3z_m,(x,y,z),(b,c,a))")); TEST_DO(verify_optimized("rename(x5y3z_m,(z),(a))")); TEST_DO(verify_optimized("rename(x5y3z_m,(x,y,z),(b,c,a))")); TEST_DO(verify_not_optimized("rename(x5y3z_m,(y),(a))")); TEST_DO(verify_not_optimized("rename(x5y3z_m,(x,z),(z,x))")); TEST_DO(verify_optimized("rename(x5yz_m,(x,y),(y,x))")); TEST_DO(verify_optimized("rename(x5yz_m,(x,y,z),(c,a,b))")); TEST_DO(verify_optimized("rename(x5yz_m,(y,z),(a,b))")); TEST_DO(verify_not_optimized("rename(x5yz_m,(z),(a))")); TEST_DO(verify_not_optimized("rename(x5yz_m,(y,z),(z,y))")); } TEST("require that chained optimized renames are compacted into a single operation") { TEST_DO(verify_optimized("rename(rename(x5,x,y),y,z)")); } TEST("require that optimization works for float cells") { TEST_DO(verify_optimized("rename(x5f,x,y)")); } bool is_stable(const vespalib::string &from_spec, const vespalib::string &to_spec, const std::vector<vespalib::string> &from, const std::vector<vespalib::string> &to) { auto from_type = ValueType::from_spec(from_spec); auto to_type = ValueType::from_spec(to_spec); return FastRenameOptimizer::is_stable_rename(from_type, to_type, from, to); } TEST("require that rename is stable if dimension order is preserved") { EXPECT_TRUE(is_stable("tensor(a{},b{})", "tensor(a{},c{})", {"b"}, {"c"})); EXPECT_TRUE(is_stable("tensor(c[3],d[5])", "tensor(c[3],e[5])", {"d"}, {"e"})); EXPECT_TRUE(is_stable("tensor(a{},b{},c[3],d[5])", "tensor(a{},b{},c[3],e[5])", {"d"}, {"e"})); EXPECT_TRUE(is_stable("tensor(a{},b{},c[3],d[5])", "tensor(e{},f{},g[3],h[5])", {"a", "b", "c", "d"}, {"e", "f", "g", "h"})); } TEST("require that rename is unstable if nontrivial indexed dimensions change order") { EXPECT_FALSE(is_stable("tensor(c[3],d[5])", "tensor(d[5],e[3])", {"c"}, {"e"})); EXPECT_FALSE(is_stable("tensor(c[3],d[5])", "tensor(c[5],d[3])", {"c", "d"}, {"d", "c"})); } TEST("require that rename is unstable if mapped dimensions change order") { EXPECT_FALSE(is_stable("tensor(a{},b{})", "tensor(b{},c{})", {"a"}, {"c"})); EXPECT_FALSE(is_stable("tensor(a{},b{})", "tensor(a{},b{})", {"a", "b"}, {"b", "a"})); } TEST("require that rename can be stable if indexed and mapped dimensions change order") { EXPECT_TRUE(is_stable("tensor(a{},b{},c[3],d[5])", "tensor(a[3],b[5],c{},d{})", {"a", "b", "c", "d"}, {"c", "d", "a", "b"})); EXPECT_TRUE(is_stable("tensor(a{},b{},c[3],d[5])", "tensor(c[3],d[5],e{},f{})", {"a", "b"}, {"e", "f"})); } TEST("require that rename can be stable if trivial dimension is moved") { EXPECT_TRUE(is_stable("tensor(a[1],b{},c[3])", "tensor(b{},bb[1],c[3])", {"a"}, {"bb"})); EXPECT_TRUE(is_stable("tensor(a[1],b{},c[3])", "tensor(b{},c[3],cc[1])", {"a"}, {"cc"})); } TEST_MAIN() { TEST_RUN_ALL(); } <|endoftext|>
<commit_before>/* WineStuff - library for manipulating WINE prefixes Copyright (C) 2010 Pavel Zinin <pzinin@gmail.com> 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 "prefixcollection.h" PrefixCollection::PrefixCollection (QSqlDatabase database, corelib *lib, PluginWorker *worker, QObject *parent) :QObject(parent) { db = database; wrk = worker; core =lib; loc = QLocale::system().name(); connect (lib, SIGNAL(videoMemoryChanged()), this, SLOT(updateVideoMemory())); } Prefix* PrefixCollection::install(SourceReader *reader, QString file, const QStringList &dvdObj, bool splash) { if (!reader) return 0; if (reader->prefixPath().isEmpty()) return 0; if (reader->name().isEmpty()) return 0; //проверяем Wine if(!reader->checkWine()) return 0; QString cdroot, image; if (dvdObj.count() == 2) { cdroot = dvdObj.at(0); image = dvdObj.at(1); } if (file.isEmpty()) core->client()->selectExe(tr("Select executable file"), file, QDir::currentPath()); if (havePrefix(reader->ID())) { Prefix *prefix (getPrefix(reader->ID())); prefix->runApplication(file, "", splash); //because of 'wine eject' return prefix; } /* Записываем Prefix в базу данныхъ */ QSqlQuery q (db); q.prepare("INSERT INTO Apps (prefix, wineprefix, wine) VALUES (:prefix, :wineprefix, :wine)"); q.bindValue(":prefix", reader->ID()); q.bindValue(":wineprefix", reader->prefixPath()); q.bindValue(":wine", reader->wine()); if (!q.exec()) { core->client()->error(tr("Database error"), tr("Traceback: %1, query: %2").arg(q.lastError().text(), q.lastQuery())); return 0; } foreach (QString locale, reader->locales()) { Name name = reader->nameForLang(locale); q.prepare("INSERT INTO Names (prefix, name, note, lang) VALUES (:prefix, :name, :note, :lang)"); q.bindValue(":prefix", reader->ID()); q.bindValue(":name", name.first); q.bindValue(":note", name.second); q.bindValue(":lang", locale); if (!q.exec()) { core->client()->error(tr("Database error"), tr("Traceback: %1, query: %2").arg(q.lastError().text(), q.lastQuery())); return 0; } } Prefix *pref = reader->prefix(); if (reader->needToSetMemory()) pref->setMemory(); if (!cdroot.isEmpty ()) reader->setDvd(image, cdroot); pref->makefix(); //launch winetricks launchWinetricks(pref, reader->components()); reader->setup(file); return pref; } void PrefixCollection::launchWinetricks(Prefix *prefix, const QStringList &args) { QProcess *p = new QProcess (this); p->setProcessEnvironment(prefix->environment()); qDebug() << "List of components that must be installed: " << args.join(" "); foreach (QString arg, args) { core->runGenericProcess(p, "winetricks -q " + arg, tr("Installing component: %1").arg(arg)); } } QList <Prefix*> PrefixCollection::prefixes() { QList <Prefix*> list; QSqlQuery q(db); q.prepare("SELECT prefix FROM Apps"); if (!q.exec()) { core->client()->error(tr("Database error"), tr("Traceback: %1, query: %2").arg(q.lastError().text(), q.lastQuery())); return list; } while (q.next()) { list.append(getPrefix(q.value(0).toString())); } return list; } Name PrefixCollection::getName(QString locale, QString ID) { Name names; // First of all, check if this locale exists QSqlQuery q(db); q.prepare("SELECT COUNT (id) FROM Names WHERE lang=? AND prefix=?"); q.addBindValue(locale); q.addBindValue(ID); if ((!q.exec()) || (!q.first())) { core->client()->error(tr("Database error"), tr("Traceback: %1, query: %2").arg(q.lastError().text(), q.lastQuery())); return names; } if ((q.value(0).toInt() == 0) && (locale != "C")) { return getName("C", ID); } //получаем name и note q.prepare("SELECT name, note FROM Names WHERE lang=:lang AND prefix=:prid"); q.bindValue(":lang", locale); q.bindValue(":prid", ID); if (!q.exec()) { core->client()->error(tr("Database error"), tr("Traceback: %1, query: %2").arg(q.lastError().text(), q.lastQuery())); } q.first(); names.first = q.value(0).toString(); names.second = q.value(1).toString(); return names; } Prefix* PrefixCollection::getPrefix(QString id) { if (id.isEmpty()) return 0; Prefix *prefix = new Prefix (this, core); QSqlQuery q(db); q.prepare("SELECT wineprefix, wine FROM Apps WHERE prefix=:id"); q.bindValue(":id", id); if (!q.exec()) { core->client()->error(tr("Database error"), tr("Traceback: %1, query: %2").arg(q.lastError().text(), q.lastQuery())); return 0; } if (!q.first()) return 0; prefix->setID(id); prefix->setPath(q.value(0).toString()); prefix->setWine(q.value(1).toString()); Name names = getName(loc.name(), id); prefix->setName(names.first); prefix->setNote(names.second); return prefix; } bool PrefixCollection::updatePrefix(Prefix *newData, QString id) { /// WARNING: If you use this function, then name and note of this prefix is WILL UNCHANGED! if (newData->ID().isEmpty()) return false; if (id.isEmpty()) id = newData->ID(); QSqlQuery q(db); q.prepare("UPDATE Apps SET prefix=:prefix, wineprefix=:wineprefix, wine=:wine WHERE prefix=:id"); q.bindValue(":prefix", newData->ID()); q.bindValue(":wineprefix", newData->path()); q.bindValue(":wine", newData->wine()); q.bindValue(":id", id); if (!q.exec()) { core->client()->error(tr("Database error"), tr("Traceback: %1, query: %2").arg(q.lastError().text(), q.lastQuery())); return 0; } return true; } bool PrefixCollection::remove(QString id) { Prefix *prefix = getPrefix(id); if (prefix->path().isEmpty() || prefix->ID().isEmpty()) return false; QProcess p; core->runGenericProcess(&p, QString("rm -rf '%1'").arg(prefix->path()), tr("Removing prefix %1").arg(prefix->name())); core->runGenericProcess(&p, QString ("rm -rf '%1/wines/%2'").arg(core->wineDir(), prefix->ID()), tr("Removing Wine for %1").arg(prefix->name())); QSqlQuery q(db); q.prepare("DELETE FROM Apps WHERE prefix=:pr"); q.bindValue(":pr", id); if (!q.exec()) { qDebug() << "WARNING: Unable to execute query for delete Prefix"; return false; } return true; } bool PrefixCollection::havePrefix(const QString &id) { if (id.isEmpty()) return false; Prefix *prefix = getPrefix(id); if (!prefix) return false; return (!prefix->ID().isEmpty()) || (!prefix->path().isEmpty()); } void PrefixCollection::updateVideoMemory() { foreach (Prefix *prefix, prefixes()) { QString id = prefix->ID(); SourceReader *reader; foreach (FormatInterface *plugin, wrk->plugins()) { SourceReader *r = plugin->readerById(id); if (r) { reader = r; break; } } if (reader) { if (reader->needToSetMemory()) prefix->setMemory(); } else prefix->setMemory(); } } <commit_msg>Fix for remove () method<commit_after>/* WineStuff - library for manipulating WINE prefixes Copyright (C) 2010 Pavel Zinin <pzinin@gmail.com> 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 "prefixcollection.h" PrefixCollection::PrefixCollection (QSqlDatabase database, corelib *lib, PluginWorker *worker, QObject *parent) :QObject(parent) { db = database; wrk = worker; core =lib; loc = QLocale::system().name(); connect (lib, SIGNAL(videoMemoryChanged()), this, SLOT(updateVideoMemory())); } Prefix* PrefixCollection::install(SourceReader *reader, QString file, const QStringList &dvdObj, bool splash) { if (!reader) return 0; if (reader->prefixPath().isEmpty()) return 0; if (reader->name().isEmpty()) return 0; //проверяем Wine if(!reader->checkWine()) return 0; QString cdroot, image; if (dvdObj.count() == 2) { cdroot = dvdObj.at(0); image = dvdObj.at(1); } if (file.isEmpty()) core->client()->selectExe(tr("Select executable file"), file, QDir::currentPath()); if (havePrefix(reader->ID())) { Prefix *prefix (getPrefix(reader->ID())); prefix->runApplication(file, "", splash); //because of 'wine eject' return prefix; } /* Записываем Prefix в базу данныхъ */ QSqlQuery q (db); q.prepare("INSERT INTO Apps (prefix, wineprefix, wine) VALUES (:prefix, :wineprefix, :wine)"); q.bindValue(":prefix", reader->ID()); q.bindValue(":wineprefix", reader->prefixPath()); q.bindValue(":wine", reader->wine()); if (!q.exec()) { core->client()->error(tr("Database error"), tr("Traceback: %1, query: %2").arg(q.lastError().text(), q.lastQuery())); return 0; } foreach (QString locale, reader->locales()) { Name name = reader->nameForLang(locale); q.prepare("INSERT INTO Names (prefix, name, note, lang) VALUES (:prefix, :name, :note, :lang)"); q.bindValue(":prefix", reader->ID()); q.bindValue(":name", name.first); q.bindValue(":note", name.second); q.bindValue(":lang", locale); if (!q.exec()) { core->client()->error(tr("Database error"), tr("Traceback: %1, query: %2").arg(q.lastError().text(), q.lastQuery())); return 0; } } Prefix *pref = reader->prefix(); if (reader->needToSetMemory()) pref->setMemory(); if (!cdroot.isEmpty ()) reader->setDvd(image, cdroot); pref->makefix(); //launch winetricks launchWinetricks(pref, reader->components()); reader->setup(file); return pref; } void PrefixCollection::launchWinetricks(Prefix *prefix, const QStringList &args) { QProcess *p = new QProcess (this); p->setProcessEnvironment(prefix->environment()); qDebug() << "List of components that must be installed: " << args.join(" "); foreach (QString arg, args) { core->runGenericProcess(p, "winetricks -q " + arg, tr("Installing component: %1").arg(arg)); } } QList <Prefix*> PrefixCollection::prefixes() { QList <Prefix*> list; QSqlQuery q(db); q.prepare("SELECT prefix FROM Apps"); if (!q.exec()) { core->client()->error(tr("Database error"), tr("Traceback: %1, query: %2").arg(q.lastError().text(), q.lastQuery())); return list; } while (q.next()) { list.append(getPrefix(q.value(0).toString())); } return list; } Name PrefixCollection::getName(QString locale, QString ID) { Name names; // First of all, check if this locale exists QSqlQuery q(db); q.prepare("SELECT COUNT (id) FROM Names WHERE lang=? AND prefix=?"); q.addBindValue(locale); q.addBindValue(ID); if ((!q.exec()) || (!q.first())) { core->client()->error(tr("Database error"), tr("Traceback: %1, query: %2").arg(q.lastError().text(), q.lastQuery())); return names; } if ((q.value(0).toInt() == 0) && (locale != "C")) { return getName("C", ID); } //получаем name и note q.prepare("SELECT name, note FROM Names WHERE lang=:lang AND prefix=:prid"); q.bindValue(":lang", locale); q.bindValue(":prid", ID); if (!q.exec()) { core->client()->error(tr("Database error"), tr("Traceback: %1, query: %2").arg(q.lastError().text(), q.lastQuery())); } q.first(); names.first = q.value(0).toString(); names.second = q.value(1).toString(); return names; } Prefix* PrefixCollection::getPrefix(QString id) { if (id.isEmpty()) return 0; Prefix *prefix = new Prefix (this, core); QSqlQuery q(db); q.prepare("SELECT wineprefix, wine FROM Apps WHERE prefix=:id"); q.bindValue(":id", id); if (!q.exec()) { core->client()->error(tr("Database error"), tr("Traceback: %1, query: %2").arg(q.lastError().text(), q.lastQuery())); return 0; } if (!q.first()) return 0; prefix->setID(id); prefix->setPath(q.value(0).toString()); prefix->setWine(q.value(1).toString()); Name names = getName(loc.name(), id); prefix->setName(names.first); prefix->setNote(names.second); return prefix; } bool PrefixCollection::updatePrefix(Prefix *newData, QString id) { /// WARNING: If you use this function, then name and note of this prefix is WILL UNCHANGED! if (newData->ID().isEmpty()) return false; if (id.isEmpty()) id = newData->ID(); QSqlQuery q(db); q.prepare("UPDATE Apps SET prefix=:prefix, wineprefix=:wineprefix, wine=:wine WHERE prefix=:id"); q.bindValue(":prefix", newData->ID()); q.bindValue(":wineprefix", newData->path()); q.bindValue(":wine", newData->wine()); q.bindValue(":id", id); if (!q.exec()) { core->client()->error(tr("Database error"), tr("Traceback: %1, query: %2").arg(q.lastError().text(), q.lastQuery())); return 0; } return true; } bool PrefixCollection::remove(QString id) { Prefix *prefix = getPrefix(id); if (prefix->path().isEmpty() || prefix->ID().isEmpty()) return false; QProcess p; core->runGenericProcess(&p, QString("rm -rf %1").arg(prefix->path()), tr("Removing prefix %1").arg(prefix->name())); core->runGenericProcess(&p, QString ("rm -rf %1/wines/%2").arg(core->wineDir(), prefix->ID()), tr("Removing Wine for %1").arg(prefix->name())); QSqlQuery q(db); q.prepare("DELETE FROM Apps WHERE prefix=:pr"); q.bindValue(":pr", id); if (!q.exec()) { qDebug() << "WARNING: Unable to execute query for delete Prefix"; return false; } return true; } bool PrefixCollection::havePrefix(const QString &id) { if (id.isEmpty()) return false; Prefix *prefix = getPrefix(id); if (!prefix) return false; return (!prefix->ID().isEmpty()) || (!prefix->path().isEmpty()); } void PrefixCollection::updateVideoMemory() { foreach (Prefix *prefix, prefixes()) { QString id = prefix->ID(); SourceReader *reader; foreach (FormatInterface *plugin, wrk->plugins()) { SourceReader *r = plugin->readerById(id); if (r) { reader = r; break; } } if (reader) { if (reader->needToSetMemory()) prefix->setMemory(); } else prefix->setMemory(); } } <|endoftext|>
<commit_before>/* * Copyright 2018 Google 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. */ #include "file_handler.hpp" #include <cstdint> #include <experimental/filesystem> #include <memory> #include <string> #include <vector> namespace blobs { namespace fs = std::experimental::filesystem; bool FileHandler::open(const std::string& path) { this->path = path; if (file.is_open()) { /* This wasn't properly closed somehow. * TODO: Throw an error or just reset the state? */ return false; } /* using ofstream no need to set out */ file.open(filename, std::ios::binary); if (file.bad()) { /* TODO: Oh no! Care about this. */ return false; } /* We were able to open the file for staging. * TODO: We'll need to do other stuff to eventually. */ return true; } void FileHandler::close() { if (file.is_open()) { file.close(); } return; } bool FileHandler::write(std::uint32_t offset, const std::vector<std::uint8_t>& data) { if (!file.is_open()) { return false; } /* We could track this, but if they write in a scattered method, this is * easier. */ file.seekp(offset, std::ios_base::beg); if (!file.good()) { /* the documentation wasn't super clear on fail vs bad in these cases, * so let's only be happy with goodness. */ return false; } file.write(reinterpret_cast<const char*>(data.data()), data.size()); if (!file.good()) { return false; } return true; } int FileHandler::getSize() { try { return static_cast<int>(fs::file_size(filename)); } catch (const fs::filesystem_error& e) { } return 0; } } // namespace blobs <commit_msg>use filesystem instead of experimental<commit_after>/* * Copyright 2018 Google 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. */ #include "file_handler.hpp" #include <cstdint> #include <filesystem> #include <memory> #include <string> #include <vector> namespace blobs { namespace fs = std::filesystem; bool FileHandler::open(const std::string& path) { this->path = path; if (file.is_open()) { /* This wasn't properly closed somehow. * TODO: Throw an error or just reset the state? */ return false; } /* using ofstream no need to set out */ file.open(filename, std::ios::binary); if (file.bad()) { /* TODO: Oh no! Care about this. */ return false; } /* We were able to open the file for staging. * TODO: We'll need to do other stuff to eventually. */ return true; } void FileHandler::close() { if (file.is_open()) { file.close(); } return; } bool FileHandler::write(std::uint32_t offset, const std::vector<std::uint8_t>& data) { if (!file.is_open()) { return false; } /* We could track this, but if they write in a scattered method, this is * easier. */ file.seekp(offset, std::ios_base::beg); if (!file.good()) { /* the documentation wasn't super clear on fail vs bad in these cases, * so let's only be happy with goodness. */ return false; } file.write(reinterpret_cast<const char*>(data.data()), data.size()); if (!file.good()) { return false; } return true; } int FileHandler::getSize() { try { return static_cast<int>(fs::file_size(filename)); } catch (const fs::filesystem_error& e) { } return 0; } } // namespace blobs <|endoftext|>
<commit_before>//It is our future main class #include <iostream> #include "graph.h" #include "minion.h" /** * Classe qui représente la classe principale . */ using namespace std; int getRandValue(int min, int max) { return (rand()/(int)RAND_MAX)*(max-min)+min; } /** * Méthode de commencement de la partie de chasse aux minions */ int main() { //Parametrage const int nbMinion = 29; // en minion const int nbVille = 29; // en minion //int tpsVisite = 30;// en min //double evapPheromone = 10; const int nbIteration = 0; cout << "BANANA !" << endl; Graph* graph = new Graph(); Minion* lesMinions[nbMinion]; for(int nbMimi = 0; nbMimi < nbMinion; ++nbMimi) { int firstPt = getRandValue(0, 29); Minion* mimi = new Minion("Serge", firstPt); lesMinions[nbMimi] = mimi; } while(nbIteration != 100){ for(int lieu = 0; lieu < nbVille; ++lieu) { do { int pt = getRandValue(0, 29); }while(!mimi->addPts(pt)); } //eVAPORATION DE LA BANANE evapoBanane(); ++nbIteration; } return 0; } <commit_msg>Ajout de machin chose<commit_after>//It is our future main class #include <iostream> #include "graph.h" #include "minion.h" /** * Classe qui représente la classe principale . */ using namespace std; int getRandValue(int min, int max) { return (rand()/(int)RAND_MAX)*(max-min)+min; } /** * Méthode de commencement de la partie de chasse aux minions */ int main() { //Parametrage const int nbMinion = 29; // en minion const int nbVille = 29; // en minion //int tpsVisite = 30;// en min //double evapPheromone = 10; const int nbIteration = 0; cout << "BANANA !" << endl; Graph* graph = new Graph(); Minion* lesMinions[nbMinion]; for(int nbMimi = 0; nbMimi < nbMinion; ++nbMimi) { int firstPt = getRandValue(0, 29); Minion* mimi = new Minion("Serge", firstPt); lesMinions[nbMimi] = mimi; } int pt = 0; while(nbIteration != 100){ for(int nbMini = 0; nbMini < nbMinion; ++nbMini) { Minion* mini = lesMinions[nbMimi]; for(int lieu = 0; lieu < nbVille; ++lieu) { do { pt = getRandValue(0, 29); }while(!mimi->addPts(pt)); } } //eVAPORATION DE LA BANANE evapoBanane(); ++nbIteration; } return 0; } <|endoftext|>
<commit_before>#include <iostream> #include <vector> #include <iostream> #include <future> #include <string> #include "boost/asio.hpp" #include "doormat/doormat.hpp" static std::unique_ptr<char[]> make_data_ptr(const std::string& s) { auto ptr = std::make_unique<char[]>(s.size()); std::copy(s.begin(), s.end(), ptr.get()); return std::move(ptr); } int main ( int argc, const char**argv ) { std::string cert = "../app/cert/newcert.pem"; std::string key = "../app/cert/newkey.pem"; std::string password = "../app/cert/keypass"; if(argc > 1) cert = argv[1]; if(argc > 2) cert = argv[2]; if(argc > 3) cert = argv[3]; ::log_wrapper::init ( false, "trace", "" ); std::unique_ptr<doormat::http_server> doormat_srv = std::make_unique<doormat::http_server>(5000, 1443, 8081); doormat_srv->on_client_connect([](auto&& connection) { std::cout << "ON CONNECT" << std::endl; connection->on_request([](auto&&, auto&& req, auto&& res) { std::cout << "ON REQUEST" << std::endl; req->on_headers([res](auto&& req) { std::cout << "ON HEADERS" << std::endl; req->on_body([](auto&&, auto data, auto len) { std::cout << "ON BODY" << std::endl; }); req->on_trailer([](auto&&, auto&& k, auto&& v) { std::cout << "ON TRAILER" << std::endl; }); req->on_finished([res](auto&&) { std::cout << "ON FINISHED" << std::endl; std::string body = "Ave http2 client, server te salutat"; http::http_response r; r.protocol(http::proto_version::HTTP20); r.status(200); r.header("content-type", "text/plain"); r.header("date", "Tue, 17 May 2016 14:53:09 GMT"); r.hostname("doormat_app.org"); r.content_len(body.size()); res->headers(std::move(r)); res->body(make_data_ptr(body), body.size()); res->end(); }); req->on_error([](auto&&, auto&& e) { std::cout << "ON ERROR" << std::endl; }); }); }); }); boost::asio::io_service io; doormat_srv->add_certificate(cert, key, password); doormat_srv->start (io); io.run(); } <commit_msg>fix to app<commit_after>#include <iostream> #include <vector> #include <iostream> #include <future> #include <string> #include "boost/asio.hpp" #include "doormat/doormat.hpp" static std::unique_ptr<char[]> make_data_ptr(const std::string& s) { auto ptr = std::make_unique<char[]>(s.size()); std::copy(s.begin(), s.end(), ptr.get()); return std::move(ptr); } int main ( int argc, const char**argv ) { std::string cert = "../app/cert/newcert.pem"; std::string key = "../app/cert/newkey.pem"; std::string password = "../app/cert/keypass"; if(argc > 1) cert = argv[1]; if(argc > 2) key = argv[2]; if(argc > 3) password = argv[3]; ::log_wrapper::init ( false, "trace", "" ); std::unique_ptr<doormat::http_server> doormat_srv = std::make_unique<doormat::http_server>(5000, 1443, 8081); doormat_srv->on_client_connect([](auto&& connection) { std::cout << "ON CONNECT" << std::endl; connection->on_request([](auto&&, auto&& req, auto&& res) { std::cout << "ON REQUEST" << std::endl; req->on_headers([res](auto&& req) { std::cout << "ON HEADERS" << std::endl; req->on_body([](auto&&, auto data, auto len) { std::cout << "ON BODY" << std::endl; }); req->on_trailer([](auto&&, auto&& k, auto&& v) { std::cout << "ON TRAILER" << std::endl; }); req->on_finished([res](auto&&) { std::cout << "ON FINISHED" << std::endl; std::string body = "Ave http2 client, server te salutat"; http::http_response r; r.protocol(http::proto_version::HTTP20); r.status(200); r.header("content-type", "text/plain"); r.header("date", "Tue, 17 May 2016 14:53:09 GMT"); r.hostname("doormat_app.org"); r.content_len(body.size()); res->headers(std::move(r)); res->body(make_data_ptr(body), body.size()); res->end(); }); req->on_error([](auto&&, auto&& e) { std::cout << "ON ERROR" << std::endl; }); }); }); }); boost::asio::io_service io; doormat_srv->add_certificate(cert, key, password); doormat_srv->start (io); io.run(); } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////////////////////////////////////// // STL A* Search implementation // (C)2001 Justin Heyes-Jones // // Finding a path on a simple grid maze // This shows how to do shortest path finding using A* // Some of the code was modified to adapt it to towdef-ai data. //////////////////////////////////////////////////////////////////////////////////////////////////////////////// #include "stlastar.h" // See header for copyright and usage information #include <iostream> #include <stdio.h> #include <math.h> #include "defines.hpp" #define DEBUG_LISTS 0 #define DEBUG_LIST_LENGTHS_ONLY 0 #define DISPLAY_SOLUTION 0 using namespace std; // Global data // The world map const int MAP_WIDTH = BOARD_W; const int MAP_HEIGHT = BOARD_H; // Our sample problem defines the world as a 2d array representing a terrain // Each element contains an integer from 0 to 5 which indicates the cost // of travel across the terrain. Zero means the least possible difficulty // in travelling (think ice rink if you can skate) whilst 5 represents the // most difficult. 9 indicates that we cannot pass. int world_map[ MAP_WIDTH * MAP_HEIGHT ]; // map helper functions int GetMap( int x, int y ) { if( x < 0 || x >= MAP_WIDTH || y < 0 || y >= MAP_HEIGHT ) { return 9; } return world_map[(y*MAP_WIDTH)+x]; } void transformGen(std::vector<bool> &gen) { for (int i = 0; i < gen.size(); ++i) { world_map[i] = gen[i] == 0 ? 0 : 9; } } // Definitions class MapSearchNode { public: int x; // the (x,y) positions of the node int y; MapSearchNode() { x = y = 0; } MapSearchNode( int px, int py ) { x=px; y=py; } float GoalDistanceEstimate( MapSearchNode &nodeGoal ); bool IsGoal( MapSearchNode &nodeGoal ); bool GetSuccessors( AStarSearch<MapSearchNode> *astarsearch, MapSearchNode *parent_node ); float GetCost( MapSearchNode &successor ); bool IsSameState( MapSearchNode &rhs ); void PrintNodeInfo(); }; bool MapSearchNode::IsSameState( MapSearchNode &rhs ) { // same state in a maze search is simply when (x,y) are the same if( (x == rhs.x) && (y == rhs.y) ) { return true; } else { return false; } } void MapSearchNode::PrintNodeInfo() { char str[100]; sprintf( str, "Node position : (%d,%d)\n", x,y ); cout << str; } // Here's the heuristic function that estimates the distance from a Node // to the Goal. float MapSearchNode::GoalDistanceEstimate( MapSearchNode &nodeGoal ) { return fabsf(x - nodeGoal.x) + fabsf(y - nodeGoal.y); } bool MapSearchNode::IsGoal( MapSearchNode &nodeGoal ) { if( (x == nodeGoal.x) && (y == nodeGoal.y) ) { return true; } return false; } // This generates the successors to the given Node. It uses a helper function called // AddSuccessor to give the successors to the AStar class. The A* specific initialisation // is done for each node internally, so here you just set the state information that // is specific to the application bool MapSearchNode::GetSuccessors( AStarSearch<MapSearchNode> *astarsearch, MapSearchNode *parent_node ) { int parent_x = -1; int parent_y = -1; if( parent_node ) { parent_x = parent_node->x; parent_y = parent_node->y; } MapSearchNode NewNode; // push each possible move except allowing the search to go backwards if( (GetMap( x-1, y ) < 9) && !((parent_x == x-1) && (parent_y == y)) ) { NewNode = MapSearchNode( x-1, y ); astarsearch->AddSuccessor( NewNode ); } if( (GetMap( x, y-1 ) < 9) && !((parent_x == x) && (parent_y == y-1)) ) { NewNode = MapSearchNode( x, y-1 ); astarsearch->AddSuccessor( NewNode ); } if( (GetMap( x+1, y ) < 9) && !((parent_x == x+1) && (parent_y == y)) ) { NewNode = MapSearchNode( x+1, y ); astarsearch->AddSuccessor( NewNode ); } if( (GetMap( x, y+1 ) < 9) && !((parent_x == x) && (parent_y == y+1)) ) { NewNode = MapSearchNode( x, y+1 ); astarsearch->AddSuccessor( NewNode ); } return true; } // given this node, what does it cost to move to successor. In the case // of our map the answer is the map terrain value at this node since that is // conceptually where we're moving float MapSearchNode::GetCost( MapSearchNode &successor ) { return (float) GetMap( x, y ); } void calculateShortestPath(std::vector<bool> &gen) { // Create an instance of the search class... transformGen(gen); AStarSearch<MapSearchNode> astarsearch; unsigned int SearchCount = 0; const unsigned int NumSearches = 1; while(SearchCount < NumSearches) { // Create a start state MapSearchNode nodeStart; nodeStart.x = RESPAWN_X; nodeStart.y = RESPAWN_Y; // Define the goal state MapSearchNode nodeEnd; nodeEnd.x = PLAYER_X; nodeEnd.y = PLAYER_Y; // Set Start and goal states astarsearch.SetStartAndGoalStates( nodeStart, nodeEnd ); unsigned int SearchState; unsigned int SearchSteps = 0; do { SearchState = astarsearch.SearchStep(); SearchSteps++; #if DEBUG_LISTS cout << "Steps:" << SearchSteps << "\n"; int len = 0; cout << "Open:\n"; MapSearchNode *p = astarsearch.GetOpenListStart(); while( p ) { len++; #if !DEBUG_LIST_LENGTHS_ONLY ((MapSearchNode *)p)->PrintNodeInfo(); #endif p = astarsearch.GetOpenListNext(); } cout << "Open list has " << len << " nodes\n"; len = 0; cout << "Closed:\n"; p = astarsearch.GetClosedListStart(); while( p ) { len++; #if !DEBUG_LIST_LENGTHS_ONLY p->PrintNodeInfo(); #endif p = astarsearch.GetClosedListNext(); } cout << "Closed list has " << len << " nodes\n"; #endif } while( SearchState == AStarSearch<MapSearchNode>::SEARCH_STATE_SEARCHING ); if( SearchState == AStarSearch<MapSearchNode>::SEARCH_STATE_SUCCEEDED ) { cout << "Search found goal state\n"; MapSearchNode *node = astarsearch.GetSolutionStart(); #if DISPLAY_SOLUTION cout << "Displaying solution\n"; #endif int steps = 0; node->PrintNodeInfo(); for( ;; ) { node = astarsearch.GetSolutionNext(); if( !node ) { break; } node->PrintNodeInfo(); steps ++; }; cout << "Solution steps " << steps << endl; // Once you're done with the solution you can free the nodes up astarsearch.FreeSolutionNodes(); } else if( SearchState == AStarSearch<MapSearchNode>::SEARCH_STATE_FAILED ) { cout << "Search terminated. Did not find goal state\n"; } // Display the number of loops the search went through cout << "SearchSteps : " << SearchSteps << "\n"; SearchCount ++; astarsearch.EnsureMemoryFreed(); } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////// <commit_msg>Remove findpath cpp file because of the hpp file.<commit_after><|endoftext|>
<commit_before><commit_msg>Fixed bug when add light, GUI or sky single scene program<commit_after><|endoftext|>
<commit_before>#include <signal.h> #include "gen/wsdd.nsmap" #include "wsddapi.h" const int _metadataVersion = 1; const char* _xaddr="http://localhost/service"; const char* _type="\"http://schemas.xmlsoap.org/ws/2006/02/devprof\":device"; bool stop = false; void sighandler(int sig) { std::cout<< "Signal caught..." << std::endl; stop = true; } void mainloop(soap* serv) { int res = soap_wsdd_listen(serv, -1000); if (res != SOAP_OK) { soap_print_fault(serv, stderr); } } void sendHello() { struct soap* soap = soap_new(); printf("call soap_wsdd_Hello\n"); int res = soap_wsdd_Hello(soap, SOAP_WSDD_ADHOC, // mode "soap.udp://239.255.255.250:3702", // address of TS soap_wsa_rand_uuid(soap), // message ID NULL, NULL, NULL, _type, NULL, _xaddr, _metadataVersion); if (res != SOAP_OK) { soap_print_fault(soap, stderr); } soap_end(soap); } void sendBye() { struct soap* soap = soap_new(); printf("call soap_wsdd_Bye\n"); int res = soap_wsdd_Bye(soap, SOAP_WSDD_ADHOC, // mode "soap.udp://239.255.255.250:3702", // address of TS soap_wsa_rand_uuid(soap), // message ID NULL, NULL, _type, NULL, _xaddr, _metadataVersion); if (res != SOAP_OK) { soap_print_fault(soap, stderr); } soap_end(soap); } int main(int argc, char** argv) { const char* host = "239.255.255.250"; int port = 3702; // create answer listener struct soap* serv = soap_new1(SOAP_IO_UDP); serv->bind_flags=SO_REUSEADDR; serv->connect_flags = SO_BROADCAST; if (!soap_valid_socket(soap_bind(serv, NULL, port, 1000))) { soap_print_fault(serv, stderr); exit(1); } ip_mreq mcast; mcast.imr_multiaddr.s_addr = inet_addr(host); mcast.imr_interface.s_addr = htonl(INADDR_ANY); if (setsockopt(serv->master, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mcast, sizeof(mcast))<0) { std::cout << "group membership failed:" << strerror(errno) << std::endl; } sendHello(); mainloop(serv); signal(SIGINT, &sighandler); while (!stop) { int res = soap_wsdd_listen(serv, -500000); } sendBye(); mainloop(serv); soap_end(serv); return 0; } void wsdd_event_ProbeMatches(struct soap *soap, unsigned int InstanceId, const char *SequenceId, unsigned int MessageNumber, const char *MessageID, const char *RelatesTo, struct wsdd__ProbeMatchesType *matches) { printf("wsdd_event_ProbeMatches nbMatch:%d\n", matches->__sizeProbeMatch); } void wsdd_event_ResolveMatches(struct soap *soap, unsigned int InstanceId, const char *SequenceId, unsigned int MessageNumber, const char *MessageID, const char *RelatesTo, struct wsdd__ResolveMatchType *match) { printf("wsdd_event_ResolveMatches\n"); } void wsdd_event_Hello(struct soap *soap, unsigned int InstanceId, const char *SequenceId, unsigned int MessageNumber, const char *MessageID, const char *RelatesTo, const char *EndpointReference, const char *Types, const char *Scopes, const char *MatchBy, const char *XAddrs, unsigned int MetadataVersion) { printf("wsdd_event_Hello id=%s EndpointReference=%s XAddrs=%s\n", MessageID, EndpointReference, XAddrs); } void wsdd_event_Bye(struct soap *soap, unsigned int InstanceId, const char *SequenceId, unsigned int MessageNumber, const char *MessageID, const char *RelatesTo, const char *EndpointReference, const char *Types, const char *Scopes, const char *MatchBy, const char *XAddrs, unsigned int *MetadataVersion) { printf("wsdd_event_Bye id=%s EndpointReference=%s XAddrs=%s\n", MessageID, EndpointReference, XAddrs); } soap_wsdd_mode wsdd_event_Resolve(struct soap *soap, const char *MessageID, const char *ReplyTo, const char *EndpointReference, struct wsdd__ResolveMatchType *match) { printf("wsdd_event_Resolve id=%s replyTo=%s\n", MessageID, ReplyTo); return SOAP_WSDD_ADHOC; } soap_wsdd_mode wsdd_event_Probe(struct soap *soap, const char *MessageID, const char *ReplyTo, const char *Types, const char *Scopes, const char *MatchBy, struct wsdd__ProbeMatchesType *matches) { printf("wsdd_event_Probe id=%s replyTo=%s types=%s scopes=%s\n", MessageID, ReplyTo, Types, Scopes); soap_wsdd_init_ProbeMatches(soap,matches); soap_wsdd_add_ProbeMatch(soap, matches, "soap.udp://239.255.255.250:3702", _type, NULL, NULL, _xaddr, _metadataVersion); soap_wsdd_ProbeMatches(soap, "soap.udp://239.255.255.250:3702", soap_wsa_rand_uuid(soap) , MessageID, ReplyTo, matches); return SOAP_WSDD_ADHOC; } <commit_msg>add SOAP_IO_KEEPALIVE flag (in order to answer more that once because multicast subscription is lost when socket is closed)<commit_after>#include <signal.h> #include "gen/wsdd.nsmap" #include "wsddapi.h" const char* host = "239.255.255.250"; int port = 3702; const int _metadataVersion = 1; const char* _xaddr="http://localhost/service"; const char* _type="\"http://schemas.xmlsoap.org/ws/2006/02/devprof\":device"; bool stop = false; void sighandler(int sig) { std::cout<< "Signal caught..." << std::endl; stop = true; } int mainloop(soap* serv) { return soap_wsdd_listen(serv, -1000000); } void sendHello() { struct soap* soap = soap_new1(SOAP_IO_UDP); printf("call soap_wsdd_Hello\n"); int res = soap_wsdd_Hello(soap, SOAP_WSDD_ADHOC, // mode "soap.udp://239.255.255.250:3702", // address of TS soap_wsa_rand_uuid(soap), // message ID NULL, NULL, NULL, _type, NULL, _xaddr, _metadataVersion); if (res != SOAP_OK) { soap_print_fault(soap, stderr); } soap_end(soap); } void sendBye() { struct soap* soap = soap_new1(SOAP_IO_UDP); printf("call soap_wsdd_Bye\n"); int res = soap_wsdd_Bye(soap, SOAP_WSDD_ADHOC, // mode "soap.udp://239.255.255.250:3702", // address of TS soap_wsa_rand_uuid(soap), // message ID NULL, NULL, _type, NULL, _xaddr, _metadataVersion); if (res != SOAP_OK) { soap_print_fault(soap, stderr); } soap_end(soap); } int main(int argc, char** argv) { struct soap* serv = soap_new1(SOAP_IO_UDP | SOAP_IO_KEEPALIVE); serv->bind_flags=SO_REUSEADDR; serv->connect_flags = SO_BROADCAST; if (!soap_valid_socket(soap_bind(serv, NULL, port, 1000))) { soap_print_fault(serv, stderr); exit(1); } ip_mreq mcast; mcast.imr_multiaddr.s_addr = inet_addr(host); mcast.imr_interface.s_addr = htonl(INADDR_ANY); if (setsockopt(serv->master, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mcast, sizeof(mcast))<0) { std::cout << "group membership failed:" << strerror(errno) << std::endl; } sendHello(); mainloop(serv); signal(SIGINT, &sighandler); while (!stop) { mainloop(serv); } sendBye(); mainloop(serv); return 0; } void wsdd_event_ProbeMatches(struct soap *soap, unsigned int InstanceId, const char *SequenceId, unsigned int MessageNumber, const char *MessageID, const char *RelatesTo, struct wsdd__ProbeMatchesType *matches) { printf("wsdd_event_ProbeMatches nbMatch:%d\n", matches->__sizeProbeMatch); } void wsdd_event_ResolveMatches(struct soap *soap, unsigned int InstanceId, const char *SequenceId, unsigned int MessageNumber, const char *MessageID, const char *RelatesTo, struct wsdd__ResolveMatchType *match) { printf("wsdd_event_ResolveMatches\n"); } void wsdd_event_Hello(struct soap *soap, unsigned int InstanceId, const char *SequenceId, unsigned int MessageNumber, const char *MessageID, const char *RelatesTo, const char *EndpointReference, const char *Types, const char *Scopes, const char *MatchBy, const char *XAddrs, unsigned int MetadataVersion) { printf("wsdd_event_Hello id=%s EndpointReference=%s XAddrs=%s\n", MessageID, EndpointReference, XAddrs); } void wsdd_event_Bye(struct soap *soap, unsigned int InstanceId, const char *SequenceId, unsigned int MessageNumber, const char *MessageID, const char *RelatesTo, const char *EndpointReference, const char *Types, const char *Scopes, const char *MatchBy, const char *XAddrs, unsigned int *MetadataVersion) { printf("wsdd_event_Bye id=%s EndpointReference=%s XAddrs=%s\n", MessageID, EndpointReference, XAddrs); } soap_wsdd_mode wsdd_event_Resolve(struct soap *soap, const char *MessageID, const char *ReplyTo, const char *EndpointReference, struct wsdd__ResolveMatchType *match) { printf("wsdd_event_Resolve id=%s replyTo=%s\n", MessageID, ReplyTo); return SOAP_WSDD_ADHOC; } soap_wsdd_mode wsdd_event_Probe(struct soap *soap, const char *MessageID, const char *ReplyTo, const char *Types, const char *Scopes, const char *MatchBy, struct wsdd__ProbeMatchesType *matches) { printf("wsdd_event_Probe id=%s replyTo=%s types=%s scopes=%s\n", MessageID, ReplyTo, Types, Scopes); soap_wsdd_init_ProbeMatches(soap,matches); soap_wsdd_add_ProbeMatch(soap, matches, "soap.udp://239.255.255.250:3702", _type, NULL, NULL, _xaddr, _metadataVersion); soap_wsdd_ProbeMatches(soap, "soap.udp://239.255.255.250:3702", soap_wsa_rand_uuid(soap) , MessageID, ReplyTo, matches); return SOAP_WSDD_ADHOC; } <|endoftext|>
<commit_before>#include "wrap_body.hpp" #include "wrap_vertex_array.hpp" #include <boost/python.hpp> #include <Box2D/Collision/Shapes/b2CircleShape.h> #include <Box2D/Collision/Shapes/b2EdgeShape.h> #include <Box2D/Collision/Shapes/b2LoopShape.h> #include <Box2D/Collision/Shapes/b2PolygonShape.h> #include <Box2D/Dynamics/b2Fixture.h> #include <Box2D/Dynamics/b2Body.h> #include <Box2D/Dynamics/b2World.h> #include <Box2D/Dynamics/Contacts/b2Contact.h> #include <Box2D/Dynamics/Joints/b2Joint.h> using namespace boost::python; namespace pysics { void wrap_body_type() { enum_<b2BodyType>("BodyType") .value("STATIC_BODY", b2_staticBody) .value("KINEMATIC_BODY", b2_kinematicBody) .value("DYNAMIC_BODY", b2_dynamicBody) .export_values() ; } b2Fixture *create_fixture(b2Body *body, b2Shape *shape, b2UserData user_data, float32 friction, float32 restitution, float32 density, bool sensor, uint16 category_bits, uint16 mask_bits, uint16 group_index) { b2FixtureDef fixture_def; fixture_def.shape = shape; fixture_def.userData = user_data; fixture_def.friction = friction; fixture_def.restitution = restitution; fixture_def.density = density; fixture_def.isSensor = sensor; fixture_def.filter.categoryBits = category_bits; fixture_def.filter.maskBits = mask_bits; fixture_def.filter.groupIndex = group_index; return body->CreateFixture(&fixture_def); } b2Fixture *create_circle_fixture(b2Body *body, b2Vec2 position, float32 radius, b2UserData user_data, float32 friction, float32 restitution, float32 density, bool sensor, uint16 category_bits, uint16 mask_bits, uint16 group_index) { b2CircleShape circle_shape; circle_shape.m_p = position; circle_shape.m_radius = radius; b2FixtureDef fixture_def; fixture_def.shape = &circle_shape; fixture_def.userData = user_data; fixture_def.friction = friction; fixture_def.restitution = restitution; fixture_def.density = density; fixture_def.isSensor = sensor; fixture_def.filter.categoryBits = category_bits; fixture_def.filter.maskBits = mask_bits; fixture_def.filter.groupIndex = group_index; return body->CreateFixture(&fixture_def); } b2Fixture *create_edge_fixture(b2Body *body, b2Vec2 vertex_1, b2Vec2 vertex_2, b2UserData user_data, float32 friction, float32 restitution, float32 density, bool sensor, uint16 category_bits, uint16 mask_bits, uint16 group_index) { b2EdgeShape edge_shape; edge_shape.m_vertex1 = vertex_1; edge_shape.m_vertex2 = vertex_2; b2FixtureDef fixture_def; fixture_def.shape = &edge_shape; fixture_def.userData = user_data; fixture_def.friction = friction; fixture_def.restitution = restitution; fixture_def.density = density; fixture_def.isSensor = sensor; fixture_def.filter.categoryBits = category_bits; fixture_def.filter.maskBits = mask_bits; fixture_def.filter.groupIndex = group_index; return body->CreateFixture(&fixture_def); } namespace { void set_vertices(b2PolygonShape *polygon_shape, list vertices) { b2Vec2 arr[b2_maxPolygonVertices]; long n = len(vertices); for (long i = 0; i != n; ++i) { arr[i] = extract<b2Vec2>(vertices[i]); } polygon_shape->Set(arr, n); } } b2Fixture *create_polygon_fixture(b2Body *body, list vertices, b2UserData user_data, float32 friction, float32 restitution, float32 density, bool sensor, uint16 category_bits, uint16 mask_bits, uint16 group_index) { b2PolygonShape polygon_shape; if (len(vertices)) { set_vertices(&polygon_shape, vertices); } else { polygon_shape.SetAsBox(1.0f, 1.0f); } b2FixtureDef fixture_def; fixture_def.shape = &polygon_shape; fixture_def.userData = user_data; fixture_def.friction = friction; fixture_def.restitution = restitution; fixture_def.density = density; fixture_def.isSensor = sensor; fixture_def.filter.categoryBits = category_bits; fixture_def.filter.maskBits = mask_bits; fixture_def.filter.groupIndex = group_index; return body->CreateFixture(&fixture_def); } b2Fixture *create_loop_fixture(b2Body *body, VertexArray vertices, b2UserData user_data, float32 friction, float32 restitution, float32 density, bool sensor, uint16 category_bits, uint16 mask_bits, uint16 group_index) { b2LoopShape loop_shape; loop_shape.m_vertices = vertices.ptr(); loop_shape.m_count = vertices.size(); b2FixtureDef fixture_def; fixture_def.shape = &loop_shape; fixture_def.userData = user_data; fixture_def.friction = friction; fixture_def.restitution = restitution; fixture_def.density = density; fixture_def.isSensor = sensor; fixture_def.filter.categoryBits = category_bits; fixture_def.filter.maskBits = mask_bits; fixture_def.filter.groupIndex = group_index; return body->CreateFixture(&fixture_def); } void wrap_body() { b2Fixture *(b2Body::*get_fixture_list)() = &b2Body::GetFixtureList; b2JointEdge *(b2Body::*get_joint_list)() = &b2Body::GetJointList; b2ContactEdge *(b2Body::*get_contact_list)() = &b2Body::GetContactList; b2Body *(b2Body::*get_next)() = &b2Body::GetNext; b2World *(b2Body::*get_world)() = &b2Body::GetWorld; class_<b2Body, boost::noncopyable>("Body", no_init) .def("create_fixture", &create_fixture, return_internal_reference<>(), (arg("self"), arg("shape"), arg("user_data")=object(), arg("friction")=0.2f, arg("restitution")=0.0f, arg("density")=1.0f, arg("sensor")=false, arg("category_bits")=0x0001, arg("mask_bits")=0xffff, arg("group_index")=0)) .def("create_circle_fixture", &create_circle_fixture, return_internal_reference<>(), (arg("self"), arg("position")=b2Vec2(0.0f, 0.0f), arg("radius")=1.0f, arg("user_data")=object(), arg("friction")=0.2f, arg("restitution")=0.0f, arg("density")=1.0f, arg("sensor")=false, arg("category_bits")=0x0001, arg("mask_bits")=0xffff, arg("group_index")=0)) .def("create_edge_fixture", &create_edge_fixture, return_internal_reference<>(), (arg("self"), arg("vertex_1")=b2Vec2(0.0f, 0.0f), arg("vertex_2")=b2Vec2(0.0f, 0.0f), arg("user_data")=object(), arg("friction")=0.2f, arg("restitution")=0.0f, arg("density")=1.0f, arg("sensor")=false, arg("category_bits")=0x0001, arg("mask_bits")=0xffff, arg("group_index")=0)) .def("create_polygon_fixture", &create_polygon_fixture, return_internal_reference<>(), (arg("self"), arg("vertices")=list(), arg("user_data")=object(), arg("friction")=0.2f, arg("restitution")=0.0f, arg("density")=1.0f, arg("sensor")=false, arg("category_bits")=0x0001, arg("mask_bits")=0xffff, arg("group_index")=0)) .def("create_loop_fixture", &create_loop_fixture, return_internal_reference<>(), (arg("self"), arg("vertices"), arg("user_data")=object(), arg("friction")=0.2f, arg("restitution")=0.0f, arg("density")=1.0f, arg("sensor")=false, arg("category_bits")=0x0001, arg("mask_bits")=0xffff, arg("group_index")=0)) .def("destroy_fixture", &b2Body::DestroyFixture) .add_property("transform", make_function(&b2Body::GetTransform, return_value_policy<copy_const_reference>()), &b2Body::SetTransform) .add_property("position", make_function(&b2Body::GetPosition, return_value_policy<copy_const_reference>())) .add_property("angle", &b2Body::GetAngle) .add_property("world_center", make_function(&b2Body::GetWorldCenter, return_value_policy<copy_const_reference>())) .add_property("local_center", make_function(&b2Body::GetLocalCenter, return_value_policy<copy_const_reference>())) .add_property("linear_velocity", &b2Body::GetLinearVelocity, &b2Body::SetLinearVelocity) .add_property("angular_velocity", &b2Body::GetAngularVelocity, &b2Body::SetAngularVelocity) .def("apply_force", &b2Body::ApplyForce) .def("apply_torque", &b2Body::ApplyTorque) .def("apply_linear_impulse", &b2Body::ApplyLinearImpulse) .def("apply_angular_impulse", &b2Body::ApplyAngularImpulse) .add_property("mass", &b2Body::GetMass) .add_property("inertia", &b2Body::GetInertia) .add_property("mass_data", &b2Body::GetMassData, &b2Body::SetMassData) .def("reset_mass_data", &b2Body::ResetMassData) .def("get_world_point", &b2Body::GetWorldPoint) .def("get_world_vector", &b2Body::GetWorldVector) .def("get_local_point", &b2Body::GetLocalPoint) .def("get_local_vector", &b2Body::GetLocalVector) .def("get_linear_velocity_from_world_point", &b2Body::GetLinearVelocityFromWorldPoint) .def("get_linear_velocity_from_local_point", &b2Body::GetLinearVelocityFromLocalPoint) .add_property("linear_damping", &b2Body::GetLinearDamping, &b2Body::SetLinearDamping) .add_property("angular_damping", &b2Body::GetAngularDamping, &b2Body::SetAngularDamping) .add_property("type", &b2Body::GetType, &b2Body::SetType) .add_property("bullet", &b2Body::IsBullet, &b2Body::SetBullet) .add_property("sleeping_allowed", &b2Body::IsSleepingAllowed, &b2Body::SetSleepingAllowed) .add_property("awake", &b2Body::IsAwake, &b2Body::SetAwake) .add_property("active", &b2Body::IsActive, &b2Body::SetActive) .add_property("fixed_rotation", &b2Body::IsFixedRotation, &b2Body::SetFixedRotation) .add_property("fixture_list", make_function(get_fixture_list, return_internal_reference<>())) .add_property("joint_list", make_function(get_joint_list, return_internal_reference<>())) .add_property("contact_list", make_function(get_contact_list, return_internal_reference<>())) .add_property("next", make_function(get_next, return_internal_reference<>())) .add_property("user_data", &b2Body::GetUserData, &b2Body::SetUserData) .add_property("world", make_function(get_world, return_internal_reference<>())) ; } } <commit_msg>reverted default density to zero<commit_after>#include "wrap_body.hpp" #include "wrap_vertex_array.hpp" #include <boost/python.hpp> #include <Box2D/Collision/Shapes/b2CircleShape.h> #include <Box2D/Collision/Shapes/b2EdgeShape.h> #include <Box2D/Collision/Shapes/b2LoopShape.h> #include <Box2D/Collision/Shapes/b2PolygonShape.h> #include <Box2D/Dynamics/b2Fixture.h> #include <Box2D/Dynamics/b2Body.h> #include <Box2D/Dynamics/b2World.h> #include <Box2D/Dynamics/Contacts/b2Contact.h> #include <Box2D/Dynamics/Joints/b2Joint.h> using namespace boost::python; namespace pysics { void wrap_body_type() { enum_<b2BodyType>("BodyType") .value("STATIC_BODY", b2_staticBody) .value("KINEMATIC_BODY", b2_kinematicBody) .value("DYNAMIC_BODY", b2_dynamicBody) .export_values() ; } b2Fixture *create_fixture(b2Body *body, b2Shape *shape, b2UserData user_data, float32 friction, float32 restitution, float32 density, bool sensor, uint16 category_bits, uint16 mask_bits, uint16 group_index) { b2FixtureDef fixture_def; fixture_def.shape = shape; fixture_def.userData = user_data; fixture_def.friction = friction; fixture_def.restitution = restitution; fixture_def.density = density; fixture_def.isSensor = sensor; fixture_def.filter.categoryBits = category_bits; fixture_def.filter.maskBits = mask_bits; fixture_def.filter.groupIndex = group_index; return body->CreateFixture(&fixture_def); } b2Fixture *create_circle_fixture(b2Body *body, b2Vec2 position, float32 radius, b2UserData user_data, float32 friction, float32 restitution, float32 density, bool sensor, uint16 category_bits, uint16 mask_bits, uint16 group_index) { b2CircleShape circle_shape; circle_shape.m_p = position; circle_shape.m_radius = radius; b2FixtureDef fixture_def; fixture_def.shape = &circle_shape; fixture_def.userData = user_data; fixture_def.friction = friction; fixture_def.restitution = restitution; fixture_def.density = density; fixture_def.isSensor = sensor; fixture_def.filter.categoryBits = category_bits; fixture_def.filter.maskBits = mask_bits; fixture_def.filter.groupIndex = group_index; return body->CreateFixture(&fixture_def); } b2Fixture *create_edge_fixture(b2Body *body, b2Vec2 vertex_1, b2Vec2 vertex_2, b2UserData user_data, float32 friction, float32 restitution, float32 density, bool sensor, uint16 category_bits, uint16 mask_bits, uint16 group_index) { b2EdgeShape edge_shape; edge_shape.m_vertex1 = vertex_1; edge_shape.m_vertex2 = vertex_2; b2FixtureDef fixture_def; fixture_def.shape = &edge_shape; fixture_def.userData = user_data; fixture_def.friction = friction; fixture_def.restitution = restitution; fixture_def.density = density; fixture_def.isSensor = sensor; fixture_def.filter.categoryBits = category_bits; fixture_def.filter.maskBits = mask_bits; fixture_def.filter.groupIndex = group_index; return body->CreateFixture(&fixture_def); } namespace { void set_vertices(b2PolygonShape *polygon_shape, list vertices) { b2Vec2 arr[b2_maxPolygonVertices]; long n = len(vertices); for (long i = 0; i != n; ++i) { arr[i] = extract<b2Vec2>(vertices[i]); } polygon_shape->Set(arr, n); } } b2Fixture *create_polygon_fixture(b2Body *body, list vertices, b2UserData user_data, float32 friction, float32 restitution, float32 density, bool sensor, uint16 category_bits, uint16 mask_bits, uint16 group_index) { b2PolygonShape polygon_shape; if (len(vertices)) { set_vertices(&polygon_shape, vertices); } else { polygon_shape.SetAsBox(1.0f, 1.0f); } b2FixtureDef fixture_def; fixture_def.shape = &polygon_shape; fixture_def.userData = user_data; fixture_def.friction = friction; fixture_def.restitution = restitution; fixture_def.density = density; fixture_def.isSensor = sensor; fixture_def.filter.categoryBits = category_bits; fixture_def.filter.maskBits = mask_bits; fixture_def.filter.groupIndex = group_index; return body->CreateFixture(&fixture_def); } b2Fixture *create_loop_fixture(b2Body *body, VertexArray vertices, b2UserData user_data, float32 friction, float32 restitution, float32 density, bool sensor, uint16 category_bits, uint16 mask_bits, uint16 group_index) { b2LoopShape loop_shape; loop_shape.m_vertices = vertices.ptr(); loop_shape.m_count = vertices.size(); b2FixtureDef fixture_def; fixture_def.shape = &loop_shape; fixture_def.userData = user_data; fixture_def.friction = friction; fixture_def.restitution = restitution; fixture_def.density = density; fixture_def.isSensor = sensor; fixture_def.filter.categoryBits = category_bits; fixture_def.filter.maskBits = mask_bits; fixture_def.filter.groupIndex = group_index; return body->CreateFixture(&fixture_def); } void wrap_body() { b2Fixture *(b2Body::*get_fixture_list)() = &b2Body::GetFixtureList; b2JointEdge *(b2Body::*get_joint_list)() = &b2Body::GetJointList; b2ContactEdge *(b2Body::*get_contact_list)() = &b2Body::GetContactList; b2Body *(b2Body::*get_next)() = &b2Body::GetNext; b2World *(b2Body::*get_world)() = &b2Body::GetWorld; class_<b2Body, boost::noncopyable>("Body", no_init) .def("create_fixture", &create_fixture, return_internal_reference<>(), (arg("self"), arg("shape"), arg("user_data")=object(), arg("friction")=0.2f, arg("restitution")=0.0f, arg("density")=0.0f, arg("sensor")=false, arg("category_bits")=0x0001, arg("mask_bits")=0xffff, arg("group_index")=0)) .def("create_circle_fixture", &create_circle_fixture, return_internal_reference<>(), (arg("self"), arg("position")=b2Vec2(0.0f, 0.0f), arg("radius")=1.0f, arg("user_data")=object(), arg("friction")=0.2f, arg("restitution")=0.0f, arg("density")=0.0f, arg("sensor")=false, arg("category_bits")=0x0001, arg("mask_bits")=0xffff, arg("group_index")=0)) .def("create_edge_fixture", &create_edge_fixture, return_internal_reference<>(), (arg("self"), arg("vertex_1")=b2Vec2(0.0f, 0.0f), arg("vertex_2")=b2Vec2(0.0f, 0.0f), arg("user_data")=object(), arg("friction")=0.2f, arg("restitution")=0.0f, arg("density")=0.0f, arg("sensor")=false, arg("category_bits")=0x0001, arg("mask_bits")=0xffff, arg("group_index")=0)) .def("create_polygon_fixture", &create_polygon_fixture, return_internal_reference<>(), (arg("self"), arg("vertices")=list(), arg("user_data")=object(), arg("friction")=0.2f, arg("restitution")=0.0f, arg("density")=0.0f, arg("sensor")=false, arg("category_bits")=0x0001, arg("mask_bits")=0xffff, arg("group_index")=0)) .def("create_loop_fixture", &create_loop_fixture, return_internal_reference<>(), (arg("self"), arg("vertices"), arg("user_data")=object(), arg("friction")=0.2f, arg("restitution")=0.0f, arg("density")=0.0f, arg("sensor")=false, arg("category_bits")=0x0001, arg("mask_bits")=0xffff, arg("group_index")=0)) .def("destroy_fixture", &b2Body::DestroyFixture) .add_property("transform", make_function(&b2Body::GetTransform, return_value_policy<copy_const_reference>()), &b2Body::SetTransform) .add_property("position", make_function(&b2Body::GetPosition, return_value_policy<copy_const_reference>())) .add_property("angle", &b2Body::GetAngle) .add_property("world_center", make_function(&b2Body::GetWorldCenter, return_value_policy<copy_const_reference>())) .add_property("local_center", make_function(&b2Body::GetLocalCenter, return_value_policy<copy_const_reference>())) .add_property("linear_velocity", &b2Body::GetLinearVelocity, &b2Body::SetLinearVelocity) .add_property("angular_velocity", &b2Body::GetAngularVelocity, &b2Body::SetAngularVelocity) .def("apply_force", &b2Body::ApplyForce) .def("apply_torque", &b2Body::ApplyTorque) .def("apply_linear_impulse", &b2Body::ApplyLinearImpulse) .def("apply_angular_impulse", &b2Body::ApplyAngularImpulse) .add_property("mass", &b2Body::GetMass) .add_property("inertia", &b2Body::GetInertia) .add_property("mass_data", &b2Body::GetMassData, &b2Body::SetMassData) .def("reset_mass_data", &b2Body::ResetMassData) .def("get_world_point", &b2Body::GetWorldPoint) .def("get_world_vector", &b2Body::GetWorldVector) .def("get_local_point", &b2Body::GetLocalPoint) .def("get_local_vector", &b2Body::GetLocalVector) .def("get_linear_velocity_from_world_point", &b2Body::GetLinearVelocityFromWorldPoint) .def("get_linear_velocity_from_local_point", &b2Body::GetLinearVelocityFromLocalPoint) .add_property("linear_damping", &b2Body::GetLinearDamping, &b2Body::SetLinearDamping) .add_property("angular_damping", &b2Body::GetAngularDamping, &b2Body::SetAngularDamping) .add_property("type", &b2Body::GetType, &b2Body::SetType) .add_property("bullet", &b2Body::IsBullet, &b2Body::SetBullet) .add_property("sleeping_allowed", &b2Body::IsSleepingAllowed, &b2Body::SetSleepingAllowed) .add_property("awake", &b2Body::IsAwake, &b2Body::SetAwake) .add_property("active", &b2Body::IsActive, &b2Body::SetActive) .add_property("fixed_rotation", &b2Body::IsFixedRotation, &b2Body::SetFixedRotation) .add_property("fixture_list", make_function(get_fixture_list, return_internal_reference<>())) .add_property("joint_list", make_function(get_joint_list, return_internal_reference<>())) .add_property("contact_list", make_function(get_contact_list, return_internal_reference<>())) .add_property("next", make_function(get_next, return_internal_reference<>())) .add_property("user_data", &b2Body::GetUserData, &b2Body::SetUserData) .add_property("world", make_function(get_world, return_internal_reference<>())) ; } } <|endoftext|>
<commit_before>#include <iostream> #include <string> #include <cstdlib> #include <fstream> #include <vector> #include <cmath> #include <sstream> #include <stdio.h> #include <unistd.h> using namespace std; #include "Processes.h" #include "Base.h" #include "Command.h" #include "Andand.h" #include "Oror.h" //Simple constructor Processes::Processes() { currCmds.resize(0); } //Simple destructor Processes::~Processes() { for(unsigned i = 0; i < currCmds.size(); ++i) { delete currCmds.at(i); } } //This executes all objects within the object's currCmds vector int Processes::execute() { int temp = 0; for(unsigned i = 0; i < currCmds.size(); ++i) { temp = currCmds.at(i)->execute(); } return temp; } //Processes parses the code to split it into separate command lines //should there be any semicolons present. void Processes::parse(string input) { vector<string> currCs; istringstream inSS(input); string currString; //Main loop for parsing input that contains semicolons while(input.find(";") != string::npos) { bool hashtag = false; bool semicolon = false; currCs.resize(0); while(!semicolon) { inSS >> currString; input.erase(0, currString.size() + 1); //Tests for hashtag/semicolon presence if(currString.find("#") != string::npos) { hashtag = true; } if(currString.find(";") != string::npos) { semicolon = true; } if(!hashtag) { if(!semicolon) { currCs.push_back(currString); } else { currString.erase(currString.size() - 1); currCs.push_back(currString); } } } //Here, we detect the presence of connectors. bool detected = false; for(unsigned j = 0; j < currCs.size(); ++j) { if(currCs.at(j) == "||" || currCs.at(j) == "&&") { detected = true; break; } } //If it detects one, it sends the vector to a loop //that runs until the end of the current command string. //It stops at the next connector, looks at the previous connector, //and creates objects and links them correspondingly. if(detected) { string prevConnector; string nextConnector; vector<string> firstCommand; unsigned i = 0; while(currCs.at(i) != "&&" && currCs.at(i) != "||") { firstCommand.push_back(currCs.at(i)); ++i; } prevConnector = currCs.at(i); Base *temp3 = new Command(firstCommand); currCmds.push_back(temp3); ++i; vector<string> currCommand; for(;i < currCs.size(); ++i) { currCommand.push_back(currCs.at(i)); if(currCs.at(i) == "&&" || currCs.at(i) == "||") { currCommand.pop_back(); Base *temp = new Command(currCommand); nextConnector = currCs.at(i); if(prevConnector == "&&") { Base *temp2 = new Andand(currCmds.at(currCmds.size() - 1), temp); currCmds.pop_back(); currCmds.push_back(temp2); currCommand.resize(0); } else { Base * temp2 = new Oror(currCmds.at(currCmds.size() - 1), temp); currCmds.pop_back(); currCmds.push_back(temp2); currCommand.resize(0); } } } } //This runs if there no connectors left after semicolon detecting. else { vector<string> currCommand; for(unsigned k = 0; k < currCs.size(); ++k) { currCommand.push_back(currCs.at(k)); } Base *temp = new Command(currCommand); currCmds.push_back(temp); } } //Second loop that parses the remaining part of the input //Also, if the input never contained any semicolons, //the parse will go straight to this part of the code. currCs.resize(0); while(inSS >> currString) { if(currString.find("#") != string::npos) { break; } currCs.push_back(currString); } //Again, detects whether the string has connectors. bool detected = false; for(unsigned j = 0; j < currCs.size(); ++j) { if(currCs.at(j) == "&&" || currCs.at(j) == "||") { detected = true; break; } } //If it detects them, it sends them to be parsed, //where connector objects are created after the first command is created //and subsequently linked until the end of parsing. if(detected) { string prevConnector; string nextConnector; vector<string> firstCommand; unsigned i = 0; while(currCs.at(i) != "&&" && currCs.at(i) != "||") { firstCommand.push_back(currCs.at(i)); ++i; } prevConnector = currCs.at(i); Base *temp3 = new Command(firstCommand); currCmds.push_back(temp3); ++i; vector<string> currCommand; for(; i < currCs.size(); ++i) { currCommand.push_back(currCs.at(i)); if(currCs.at(i) == "&&" || currCs.at(i) == "||") { currCommand.pop_back(); Base *temp = new Command(currCommand); nextConnector = currCs.at(i); if(prevConnector == "&&") { Base *temp2 = new Andand(currCmds.at(currCmds.size() - 1), temp); currCmds.pop_back(); currCmds.push_back(temp2); currCommand.resize(0); } else { Base * temp2 = new Oror(currCmds.at(currCmds.size() - 1), temp); currCmds.pop_back(); currCmds.push_back(temp2); currCommand.resize(0); } } } Base * temp = new Command(currCommand); if(prevConnector == "&&") { Base *temp2 = new Andand(currCmds.at(currCmds.size() - 1), temp); currCmds.pop_back(); currCmds.push_back(temp2); currCommand.resize(0); } else { Base * temp2 = new Oror(currCmds.at(currCmds.size() - 1), temp); currCmds.pop_back(); currCmds.push_back(temp2); } } else { vector<string> currCommand; for(unsigned k = 0; k < currCs.size(); ++k) { currCommand.push_back(currCs.at(k)); } Base *temp = new Command(currCommand); currCmds.push_back(temp); } } //This is used to clean up the Processes vector in order to gather further //input from the user. void Processes::reset() { for(unsigned i = 0; i < currCmds.size(); ++i) { delete currCmds.at(i); } this->currCmds.resize(0); }<commit_msg>styling issues resolved<commit_after>#include <iostream> #include <string> #include <cstdlib> #include <fstream> #include <vector> #include <cmath> #include <sstream> #include <stdio.h> #include <unistd.h> using namespace std; #include "Processes.h" #include "Base.h" #include "Command.h" #include "Andand.h" #include "Oror.h" //Simple constructor Processes::Processes() { currCmds.resize(0); } //Simple destructor Processes::~Processes() { for(unsigned i = 0; i < currCmds.size(); ++i) { delete currCmds.at(i); } } //This executes all objects within the object's currCmds vector int Processes::execute() { int temp = 0; for(unsigned i = 0; i < currCmds.size(); ++i) { temp = currCmds.at(i)->execute(); } return temp; } //Processes parses the code to split it into separate command lines //should there be any semicolons present. void Processes::parse(string input) { vector<string> currCs; istringstream inSS(input); string currString; //Main loop for parsing input that contains semicolons while(input.find(";") != string::npos) { bool hashtag = false; bool semicolon = false; currCs.resize(0); while(!semicolon) { inSS >> currString; input.erase(0, currString.size() + 1); //Tests for hashtag/semicolon presence if(currString.find("#") != string::npos) { hashtag = true; } if(currString.find(";") != string::npos) { semicolon = true; } if(!hashtag) { if(!semicolon) { currCs.push_back(currString); } else { currString.erase(currString.size() - 1); currCs.push_back(currString); } } } //Here, we detect the presence of connectors. bool detected = false; for(unsigned j = 0; j < currCs.size(); ++j) { if(currCs.at(j) == "||" || currCs.at(j) == "&&") { detected = true; break; } } //If it detects one, it sends the vector to a loop //that runs until the end of the current command string. //It stops at the next connector, looks at the previous connector, //and creates objects and links them correspondingly. if(detected) { string prevConnector; string nextConnector; vector<string> firstCommand; unsigned i = 0; while(currCs.at(i) != "&&" && currCs.at(i) != "||") { firstCommand.push_back(currCs.at(i)); ++i; } prevConnector = currCs.at(i); Base *temp3 = new Command(firstCommand); currCmds.push_back(temp3); ++i; vector<string> currCommand; for(;i < currCs.size(); ++i) { currCommand.push_back(currCs.at(i)); if(currCs.at(i) == "&&" || currCs.at(i) == "||") { currCommand.pop_back(); Base *temp = new Command(currCommand); nextConnector = currCs.at(i); if(prevConnector == "&&") { Base *temp2 = new Andand(currCmds.at( currCmds.size() - 1), temp); currCmds.pop_back(); currCmds.push_back(temp2); currCommand.resize(0); } else { Base * temp2 = new Oror(currCmds.at( currCmds.size() - 1), temp); currCmds.pop_back(); currCmds.push_back(temp2); currCommand.resize(0); } } } } //This runs if there no connectors left after semicolon detecting. else { vector<string> currCommand; for(unsigned k = 0; k < currCs.size(); ++k) { currCommand.push_back(currCs.at(k)); } Base *temp = new Command(currCommand); currCmds.push_back(temp); } } //Second loop that parses the remaining part of the input //Also, if the input never contained any semicolons, //the parse will go straight to this part of the code. currCs.resize(0); while(inSS >> currString) { if(currString.find("#") != string::npos) { break; } currCs.push_back(currString); } //Again, detects whether the string has connectors. bool detected = false; for(unsigned j = 0; j < currCs.size(); ++j) { if(currCs.at(j) == "&&" || currCs.at(j) == "||") { detected = true; break; } } //If it detects them, it sends them to be parsed, //where connector objects are created after the first command is created //and subsequently linked until the end of parsing. if(detected) { string prevConnector; string nextConnector; vector<string> firstCommand; unsigned i = 0; while(currCs.at(i) != "&&" && currCs.at(i) != "||") { firstCommand.push_back(currCs.at(i)); ++i; } prevConnector = currCs.at(i); Base *temp3 = new Command(firstCommand); currCmds.push_back(temp3); ++i; vector<string> currCommand; for(; i < currCs.size(); ++i) { currCommand.push_back(currCs.at(i)); if(currCs.at(i) == "&&" || currCs.at(i) == "||") { currCommand.pop_back(); Base *temp = new Command(currCommand); nextConnector = currCs.at(i); if(prevConnector == "&&") { Base *temp2 = new Andand(currCmds.at(currCmds.size() - 1), temp); currCmds.pop_back(); currCmds.push_back(temp2); currCommand.resize(0); } else { Base * temp2 = new Oror(currCmds.at(currCmds.size() - 1), temp); currCmds.pop_back(); currCmds.push_back(temp2); currCommand.resize(0); } } } Base * temp = new Command(currCommand); if(prevConnector == "&&") { Base *temp2 = new Andand(currCmds.at(currCmds.size() - 1), temp); currCmds.pop_back(); currCmds.push_back(temp2); currCommand.resize(0); } else { Base * temp2 = new Oror(currCmds.at(currCmds.size() - 1), temp); currCmds.pop_back(); currCmds.push_back(temp2); } } else { vector<string> currCommand; for(unsigned k = 0; k < currCs.size(); ++k) { currCommand.push_back(currCs.at(k)); } Base *temp = new Command(currCommand); currCmds.push_back(temp); } } //This is used to clean up the Processes vector in order to gather further //input from the user. void Processes::reset() { for(unsigned i = 0; i < currCmds.size(); ++i) { delete currCmds.at(i); } this->currCmds.resize(0); }<|endoftext|>
<commit_before>// @(#)root/gl:$Id$ // Author: Timur Pocheptsov 03/08/2004 // NOTE: This code moved from obsoleted TGLSceneObject.h / .cxx - see these // attic files for previous CVS history /************************************************************************* * 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 "TGLPolyMarker.h" #include "TGLRnrCtx.h" #include "TGLIncludes.h" #include "TBuffer3D.h" #include "TBuffer3DTypes.h" #include "TMath.h" #include "TAttMarker.h" // For debug tracing #include "TClass.h" #include "TError.h" //______________________________________________________________________________ /* Begin_Html <center><h2>GL Polymarker</h2></center> To draw a 3D polymarker in a GL window. End_Html */ ClassImp(TGLPolyMarker) //______________________________________________________________________________ TGLPolyMarker::TGLPolyMarker(const TBuffer3D & buffer) : TGLLogicalShape(buffer), fVertices(buffer.fPnts, buffer.fPnts + 3 * buffer.NbPnts()), fStyle(7), fSize(1.) { //TAttMarker is not TObject descendant, so I need dynamic_cast if (TAttMarker *realObj = dynamic_cast<TAttMarker *>(buffer.fID)) { fStyle = realObj->GetMarkerStyle(); fSize = realObj->GetMarkerSize() / 2.; } } //______________________________________________________________________________ void TGLPolyMarker::DirectDraw(TGLRnrCtx & rnrCtx) const { // Debug tracing if (gDebug > 4) { Info("TGLPolyMarker::DirectDraw", "this %d (class %s) LOD %d", this, IsA()->GetName(), rnrCtx.ShapeLOD()); } if (rnrCtx.DrawPass() == TGLRnrCtx::kPassOutlineLine) return; const Double_t *vertices = &fVertices[0]; UInt_t size = fVertices.size(); Int_t stacks = 6, slices = 6; Float_t pixelSize = 1; Double_t topRadius = fSize; switch (fStyle) { case 27: stacks = 2, slices = 4; case 4:case 8:case 20:case 24: for (UInt_t i = 0; i < size; i += 3) { glPushMatrix(); glTranslated(vertices[i], vertices[i + 1], vertices[i + 2]); gluSphere(rnrCtx.GetGluQuadric(), fSize, slices, stacks); glPopMatrix(); } break; case 22:case 26: topRadius = 0.; case 21:case 25: for (UInt_t i = 0; i < size; i += 3) { glPushMatrix(); glTranslated(vertices[i], vertices[i + 1], vertices[i + 2]); gluCylinder(rnrCtx.GetGluQuadric(), fSize, topRadius, fSize, 4, 1); glPopMatrix(); } break; case 23: for (UInt_t i = 0; i < size; i += 3) { glPushMatrix(); glTranslated(vertices[i], vertices[i + 1], vertices[i + 2]); glRotated(180, 1., 0., 0.); gluCylinder(rnrCtx.GetGluQuadric(), fSize, 0., fSize, 4, 1); glPopMatrix(); } break; case 3: case 2: case 5: DrawStars(); break; case 7: pixelSize += 1; case 6: pixelSize += 1; case 1: case 9: case 10: case 11: default: glPointSize(pixelSize); glBegin(GL_POINTS); for (UInt_t i = 0; i < size; i += 3) glVertex3dv(vertices + i); glEnd(); break; } } //______________________________________________________________________________ void TGLPolyMarker::DrawStars()const { // Draw stars glDisable(GL_LIGHTING); const Double_t diag = TMath::Sqrt(2 * fSize * fSize) / 2; for (UInt_t i = 0; i < fVertices.size(); i += 3) { Double_t x = fVertices[i]; Double_t y = fVertices[i + 1]; Double_t z = fVertices[i + 2]; glBegin(GL_LINES); if (fStyle == 2 || fStyle == 3) { glVertex3d(x - fSize, y, z); glVertex3d(x + fSize, y, z); glVertex3d(x, y, z - fSize); glVertex3d(x, y, z + fSize); glVertex3d(x, y - fSize, z); glVertex3d(x, y + fSize, z); } if(fStyle != 2) { glVertex3d(x - diag, y - diag, z - diag); glVertex3d(x + diag, y + diag, z + diag); glVertex3d(x - diag, y - diag, z + diag); glVertex3d(x + diag, y + diag, z - diag); glVertex3d(x - diag, y + diag, z - diag); glVertex3d(x + diag, y - diag, z + diag); glVertex3d(x - diag, y + diag, z + diag); glVertex3d(x + diag, y - diag, z - diag); } glEnd(); } glEnable(GL_LIGHTING); } <commit_msg>Also use point-scaling in TGLPolyMarker.<commit_after>// @(#)root/gl:$Id$ // Author: Timur Pocheptsov 03/08/2004 // NOTE: This code moved from obsoleted TGLSceneObject.h / .cxx - see these // attic files for previous CVS history /************************************************************************* * 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 "TGLPolyMarker.h" #include "TGLRnrCtx.h" #include "TGLIncludes.h" #include "TGLUtil.h" #include "TBuffer3D.h" #include "TBuffer3DTypes.h" #include "TMath.h" #include "TAttMarker.h" // For debug tracing #include "TClass.h" #include "TError.h" //______________________________________________________________________________ /* Begin_Html <center><h2>GL Polymarker</h2></center> To draw a 3D polymarker in a GL window. End_Html */ ClassImp(TGLPolyMarker) //______________________________________________________________________________ TGLPolyMarker::TGLPolyMarker(const TBuffer3D & buffer) : TGLLogicalShape(buffer), fVertices(buffer.fPnts, buffer.fPnts + 3 * buffer.NbPnts()), fStyle(7), fSize(1.) { //TAttMarker is not TObject descendant, so I need dynamic_cast if (TAttMarker *realObj = dynamic_cast<TAttMarker *>(buffer.fID)) { fStyle = realObj->GetMarkerStyle(); fSize = realObj->GetMarkerSize() / 2.; } } //______________________________________________________________________________ void TGLPolyMarker::DirectDraw(TGLRnrCtx & rnrCtx) const { // Debug tracing if (gDebug > 4) { Info("TGLPolyMarker::DirectDraw", "this %d (class %s) LOD %d", this, IsA()->GetName(), rnrCtx.ShapeLOD()); } if (rnrCtx.DrawPass() == TGLRnrCtx::kPassOutlineLine) return; const Double_t *vertices = &fVertices[0]; UInt_t size = fVertices.size(); Int_t stacks = 6, slices = 6; Float_t pixelSize = 1; Double_t topRadius = fSize; switch (fStyle) { case 27: stacks = 2, slices = 4; case 4:case 8:case 20:case 24: for (UInt_t i = 0; i < size; i += 3) { glPushMatrix(); glTranslated(vertices[i], vertices[i + 1], vertices[i + 2]); gluSphere(rnrCtx.GetGluQuadric(), fSize, slices, stacks); glPopMatrix(); } break; case 22:case 26: topRadius = 0.; case 21:case 25: for (UInt_t i = 0; i < size; i += 3) { glPushMatrix(); glTranslated(vertices[i], vertices[i + 1], vertices[i + 2]); gluCylinder(rnrCtx.GetGluQuadric(), fSize, topRadius, fSize, 4, 1); glPopMatrix(); } break; case 23: for (UInt_t i = 0; i < size; i += 3) { glPushMatrix(); glTranslated(vertices[i], vertices[i + 1], vertices[i + 2]); glRotated(180, 1., 0., 0.); gluCylinder(rnrCtx.GetGluQuadric(), fSize, 0., fSize, 4, 1); glPopMatrix(); } break; case 3: case 2: case 5: DrawStars(); break; case 7: pixelSize += 1; case 6: pixelSize += 1; case 1: case 9: case 10: case 11: default: TGLUtil::PointSize(pixelSize); glBegin(GL_POINTS); for (UInt_t i = 0; i < size; i += 3) glVertex3dv(vertices + i); glEnd(); break; } } //______________________________________________________________________________ void TGLPolyMarker::DrawStars()const { // Draw stars glDisable(GL_LIGHTING); const Double_t diag = TMath::Sqrt(2 * fSize * fSize) / 2; for (UInt_t i = 0; i < fVertices.size(); i += 3) { Double_t x = fVertices[i]; Double_t y = fVertices[i + 1]; Double_t z = fVertices[i + 2]; glBegin(GL_LINES); if (fStyle == 2 || fStyle == 3) { glVertex3d(x - fSize, y, z); glVertex3d(x + fSize, y, z); glVertex3d(x, y, z - fSize); glVertex3d(x, y, z + fSize); glVertex3d(x, y - fSize, z); glVertex3d(x, y + fSize, z); } if(fStyle != 2) { glVertex3d(x - diag, y - diag, z - diag); glVertex3d(x + diag, y + diag, z + diag); glVertex3d(x - diag, y - diag, z + diag); glVertex3d(x + diag, y + diag, z - diag); glVertex3d(x - diag, y + diag, z - diag); glVertex3d(x + diag, y - diag, z + diag); glVertex3d(x - diag, y + diag, z + diag); glVertex3d(x + diag, y - diag, z - diag); } glEnd(); } glEnable(GL_LIGHTING); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: DAVSession.hxx,v $ * * $Revision: 1.15 $ * * last change: $Author: vg $ $Date: 2003-07-25 11:39:28 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _DAVSESSION_HXX_ #define _DAVSESSION_HXX_ #include <memory> #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif #ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_ #include <com/sun/star/io/XInputStream.hpp> #endif #ifndef _COM_SUN_STAR_IO_XOUTPUTSTREAM_HPP_ #include <com/sun/star/io/XOutputStream.hpp> #endif #ifndef _DAVEXCEPTION_HXX_ #include "DAVException.hxx" #endif #ifndef _DAVPROPERTIES_HXX_ #include "DAVProperties.hxx" #endif #ifndef _DAVRESOURCE_HXX_ #include "DAVResource.hxx" #endif #ifndef _DAVSESSIONFACTORY_HXX_ #include "DAVSessionFactory.hxx" #endif #ifndef _DAVTYPES_HXX_ #include "DAVTypes.hxx" #endif #ifndef _DAVREQUESTENVIRONMENT_HXX_ #include "DAVRequestEnvironment.hxx" #endif namespace webdav_ucp { class DAVAuthListener; class DAVSession { public: inline void acquire() SAL_THROW(()) { osl_incrementInterlockedCount( &m_nRefCount ); } void release() SAL_THROW(()) { if ( osl_decrementInterlockedCount( &m_nRefCount ) == 0 ) { m_xFactory->releaseElement( this ); delete this; } } virtual sal_Bool CanUse( const ::rtl::OUString & inPath ) = 0; virtual sal_Bool UsesProxy() = 0; // DAV methods // virtual void OPTIONS( const ::rtl::OUString & inPath, DAVCapabilities & outCapabilities, const DAVRequestEnvironment & rEnv ) throw( DAVException ) = 0; // allprop & named virtual void PROPFIND( const ::rtl::OUString & inPath, const Depth inDepth, const std::vector< ::rtl::OUString > & inPropertyNames, std::vector< DAVResource > & ioResources, const DAVRequestEnvironment & rEnv ) throw( DAVException ) = 0; // propnames virtual void PROPFIND( const ::rtl::OUString & inPath, const Depth inDepth, std::vector< DAVResourceInfo > & ioResInfo, const DAVRequestEnvironment & rEnv ) throw( DAVException ) = 0; virtual void PROPPATCH( const ::rtl::OUString & inPath, const std::vector< ProppatchValue > & inValues, const DAVRequestEnvironment & rEnv ) throw( DAVException ) = 0; virtual void HEAD( const ::rtl::OUString & inPath, const std::vector< ::rtl::OUString > & inHeaderNames, DAVResource & ioResource, const DAVRequestEnvironment & rEnv ) throw( DAVException ) = 0; virtual com::sun::star::uno::Reference< com::sun::star::io::XInputStream > GET( const ::rtl::OUString & inPath, const DAVRequestEnvironment & rEnv ) throw( DAVException ) = 0; virtual void GET( void* userData, const ::rtl::OUString & inPath, const DAVRequestEnvironment & rEnv ) throw( DAVException ) = 0; virtual void GET( const ::rtl::OUString & inPath, com::sun::star::uno::Reference< com::sun::star::io::XOutputStream >& o, const DAVRequestEnvironment & rEnv ) throw( DAVException ) = 0; virtual com::sun::star::uno::Reference< com::sun::star::io::XInputStream > GET( const ::rtl::OUString & inPath, const std::vector< ::rtl::OUString > & inHeaderNames, DAVResource & ioResource, const DAVRequestEnvironment & rEnv ) throw( DAVException ) = 0; virtual void GET( void* userData, const ::rtl::OUString & inPath, const std::vector< ::rtl::OUString > & inHeaderNames, DAVResource & ioResource, const DAVRequestEnvironment & rEnv ) throw( DAVException ) = 0; virtual void GET( const ::rtl::OUString & inPath, com::sun::star::uno::Reference< com::sun::star::io::XOutputStream >& o, const std::vector< ::rtl::OUString > & inHeaderNames, DAVResource & ioResource, const DAVRequestEnvironment & rEnv ) throw( DAVException ) = 0; virtual void PUT( const ::rtl::OUString & inPath, const com::sun::star::uno::Reference< com::sun::star::io::XInputStream >& s, const DAVRequestEnvironment & rEnv ) throw( DAVException ) = 0; virtual com::sun::star::uno::Reference< com::sun::star::io::XInputStream > POST( const rtl::OUString & inPath, const rtl::OUString & rContentType, const rtl::OUString & rReferer, const com::sun::star::uno::Reference< com::sun::star::io::XInputStream > & inInputStream, const DAVRequestEnvironment & rEnv ) throw ( DAVException ) = 0; virtual void POST( const rtl::OUString & inPath, const rtl::OUString & rContentType, const rtl::OUString & rReferer, const com::sun::star::uno::Reference< com::sun::star::io::XInputStream > & inInputStream, com::sun::star::uno::Reference< com::sun::star::io::XOutputStream > & oOutputStream, const DAVRequestEnvironment & rEnv ) throw ( DAVException ) = 0; virtual void MKCOL( const ::rtl::OUString & inPath, const DAVRequestEnvironment & rEnv ) throw( DAVException ) = 0; virtual void COPY( const ::rtl::OUString & inSource, const ::rtl::OUString & inDestination, const DAVRequestEnvironment & rEnv, sal_Bool inOverwrite = false ) throw( DAVException ) = 0; virtual void MOVE( const ::rtl::OUString & inSource, const ::rtl::OUString & inDestination, const DAVRequestEnvironment & rEnv, sal_Bool inOverwrite = false ) throw( DAVException ) = 0; virtual void DESTROY( const ::rtl::OUString & inPath, const DAVRequestEnvironment & rEnv ) throw( DAVException ) = 0; // Note: Uncomment the following if locking support is required /* virtual void LOCK ( const Lock & inLock, const DAVRequestEnvironment & rEnv ) throw( DAVException ) = 0; virtual void UNLOCK ( const Lock & inLock, const DAVRequestEnvironment & rEnv ) throw( DAVException ) = 0; */ protected: rtl::Reference< DAVSessionFactory > m_xFactory; DAVSession( rtl::Reference< DAVSessionFactory > const & rFactory ) : m_xFactory( rFactory ), m_nRefCount( 0 ) {} virtual ~DAVSession() {} private: DAVSessionFactory::Map::iterator m_aContainerIt; oslInterlockedCount m_nRefCount; friend class DAVSessionFactory; #if defined WNT friend struct std::auto_ptr< DAVSession >; // work around compiler bug... #else // WNT friend class std::auto_ptr< DAVSession >; #endif // WNT }; }; // namespace webdav_ucp #endif // _DAVSESSION_HXX_ <commit_msg>INTEGRATION: CWS net2003 (1.15.14); FILE MERGED 2003/09/24 09:50:38 obo 1.15.14.1: #111136# .net 2003 port<commit_after>/************************************************************************* * * $RCSfile: DAVSession.hxx,v $ * * $Revision: 1.16 $ * * last change: $Author: vg $ $Date: 2003-10-06 18:52:36 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _DAVSESSION_HXX_ #define _DAVSESSION_HXX_ #include <memory> #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif #ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_ #include <com/sun/star/io/XInputStream.hpp> #endif #ifndef _COM_SUN_STAR_IO_XOUTPUTSTREAM_HPP_ #include <com/sun/star/io/XOutputStream.hpp> #endif #ifndef _DAVEXCEPTION_HXX_ #include "DAVException.hxx" #endif #ifndef _DAVPROPERTIES_HXX_ #include "DAVProperties.hxx" #endif #ifndef _DAVRESOURCE_HXX_ #include "DAVResource.hxx" #endif #ifndef _DAVSESSIONFACTORY_HXX_ #include "DAVSessionFactory.hxx" #endif #ifndef _DAVTYPES_HXX_ #include "DAVTypes.hxx" #endif #ifndef _DAVREQUESTENVIRONMENT_HXX_ #include "DAVRequestEnvironment.hxx" #endif namespace webdav_ucp { class DAVAuthListener; class DAVSession { public: inline void acquire() SAL_THROW(()) { osl_incrementInterlockedCount( &m_nRefCount ); } void release() SAL_THROW(()) { if ( osl_decrementInterlockedCount( &m_nRefCount ) == 0 ) { m_xFactory->releaseElement( this ); delete this; } } virtual sal_Bool CanUse( const ::rtl::OUString & inPath ) = 0; virtual sal_Bool UsesProxy() = 0; // DAV methods // virtual void OPTIONS( const ::rtl::OUString & inPath, DAVCapabilities & outCapabilities, const DAVRequestEnvironment & rEnv ) throw( DAVException ) = 0; // allprop & named virtual void PROPFIND( const ::rtl::OUString & inPath, const Depth inDepth, const std::vector< ::rtl::OUString > & inPropertyNames, std::vector< DAVResource > & ioResources, const DAVRequestEnvironment & rEnv ) throw( DAVException ) = 0; // propnames virtual void PROPFIND( const ::rtl::OUString & inPath, const Depth inDepth, std::vector< DAVResourceInfo > & ioResInfo, const DAVRequestEnvironment & rEnv ) throw( DAVException ) = 0; virtual void PROPPATCH( const ::rtl::OUString & inPath, const std::vector< ProppatchValue > & inValues, const DAVRequestEnvironment & rEnv ) throw( DAVException ) = 0; virtual void HEAD( const ::rtl::OUString & inPath, const std::vector< ::rtl::OUString > & inHeaderNames, DAVResource & ioResource, const DAVRequestEnvironment & rEnv ) throw( DAVException ) = 0; virtual com::sun::star::uno::Reference< com::sun::star::io::XInputStream > GET( const ::rtl::OUString & inPath, const DAVRequestEnvironment & rEnv ) throw( DAVException ) = 0; virtual void GET( void* userData, const ::rtl::OUString & inPath, const DAVRequestEnvironment & rEnv ) throw( DAVException ) = 0; virtual void GET( const ::rtl::OUString & inPath, com::sun::star::uno::Reference< com::sun::star::io::XOutputStream >& o, const DAVRequestEnvironment & rEnv ) throw( DAVException ) = 0; virtual com::sun::star::uno::Reference< com::sun::star::io::XInputStream > GET( const ::rtl::OUString & inPath, const std::vector< ::rtl::OUString > & inHeaderNames, DAVResource & ioResource, const DAVRequestEnvironment & rEnv ) throw( DAVException ) = 0; virtual void GET( void* userData, const ::rtl::OUString & inPath, const std::vector< ::rtl::OUString > & inHeaderNames, DAVResource & ioResource, const DAVRequestEnvironment & rEnv ) throw( DAVException ) = 0; virtual void GET( const ::rtl::OUString & inPath, com::sun::star::uno::Reference< com::sun::star::io::XOutputStream >& o, const std::vector< ::rtl::OUString > & inHeaderNames, DAVResource & ioResource, const DAVRequestEnvironment & rEnv ) throw( DAVException ) = 0; virtual void PUT( const ::rtl::OUString & inPath, const com::sun::star::uno::Reference< com::sun::star::io::XInputStream >& s, const DAVRequestEnvironment & rEnv ) throw( DAVException ) = 0; virtual com::sun::star::uno::Reference< com::sun::star::io::XInputStream > POST( const rtl::OUString & inPath, const rtl::OUString & rContentType, const rtl::OUString & rReferer, const com::sun::star::uno::Reference< com::sun::star::io::XInputStream > & inInputStream, const DAVRequestEnvironment & rEnv ) throw ( DAVException ) = 0; virtual void POST( const rtl::OUString & inPath, const rtl::OUString & rContentType, const rtl::OUString & rReferer, const com::sun::star::uno::Reference< com::sun::star::io::XInputStream > & inInputStream, com::sun::star::uno::Reference< com::sun::star::io::XOutputStream > & oOutputStream, const DAVRequestEnvironment & rEnv ) throw ( DAVException ) = 0; virtual void MKCOL( const ::rtl::OUString & inPath, const DAVRequestEnvironment & rEnv ) throw( DAVException ) = 0; virtual void COPY( const ::rtl::OUString & inSource, const ::rtl::OUString & inDestination, const DAVRequestEnvironment & rEnv, sal_Bool inOverwrite = false ) throw( DAVException ) = 0; virtual void MOVE( const ::rtl::OUString & inSource, const ::rtl::OUString & inDestination, const DAVRequestEnvironment & rEnv, sal_Bool inOverwrite = false ) throw( DAVException ) = 0; virtual void DESTROY( const ::rtl::OUString & inPath, const DAVRequestEnvironment & rEnv ) throw( DAVException ) = 0; // Note: Uncomment the following if locking support is required /* virtual void LOCK ( const Lock & inLock, const DAVRequestEnvironment & rEnv ) throw( DAVException ) = 0; virtual void UNLOCK ( const Lock & inLock, const DAVRequestEnvironment & rEnv ) throw( DAVException ) = 0; */ protected: rtl::Reference< DAVSessionFactory > m_xFactory; DAVSession( rtl::Reference< DAVSessionFactory > const & rFactory ) : m_xFactory( rFactory ), m_nRefCount( 0 ) {} virtual ~DAVSession() {} private: DAVSessionFactory::Map::iterator m_aContainerIt; oslInterlockedCount m_nRefCount; friend class DAVSessionFactory; #if defined WNT && _MSC_VER < 1310 friend struct std::auto_ptr< DAVSession >; // work around compiler bug... #else // WNT friend class std::auto_ptr< DAVSession >; #endif // WNT }; }; // namespace webdav_ucp #endif // _DAVSESSION_HXX_ <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "libcef/browser/url_request_context_getter.h" #if defined(OS_WIN) #include <winhttp.h> #endif #include <string> #include <vector> #include "libcef/browser/content_browser_client.h" #include "libcef/browser/context.h" #include "libcef/browser/scheme_handler.h" #include "libcef/browser/thread_util.h" #include "libcef/browser/url_network_delegate.h" #include "libcef/browser/url_request_context_proxy.h" #include "libcef/browser/url_request_interceptor.h" #include "libcef/common/cef_switches.h" #include "base/command_line.h" #include "base/file_util.h" #include "base/logging.h" #include "base/stl_util.h" #include "base/strings/string_util.h" #include "base/threading/thread_restrictions.h" #include "base/threading/worker_pool.h" #include "chrome/browser/net/proxy_service_factory.h" #include "content/browser/net/sqlite_persistent_cookie_store.h" #include "content/public/browser/browser_thread.h" #include "content/public/common/content_switches.h" #include "content/public/common/url_constants.h" #include "net/cert/cert_verifier.h" #include "net/cookies/cookie_monster.h" #include "net/dns/host_resolver.h" #include "net/ftp/ftp_network_layer.h" #include "net/http/http_auth_handler_factory.h" #include "net/http/http_cache.h" #include "net/http/http_server_properties_impl.h" #include "net/http/transport_security_state.h" #include "net/proxy/proxy_service.h" #include "net/ssl/default_server_bound_cert_store.h" #include "net/ssl/server_bound_cert_service.h" #include "net/ssl/ssl_config_service_defaults.h" #include "net/url_request/static_http_user_agent_settings.h" #include "net/url_request/url_request.h" #include "net/url_request/url_request_context.h" #include "net/url_request/url_request_context_storage.h" #include "net/url_request/url_request_job_factory_impl.h" #include "net/url_request/url_request_job_manager.h" using content::BrowserThread; #if defined(OS_WIN) #pragma comment(lib, "winhttp.lib") #endif CefURLRequestContextGetter::CefURLRequestContextGetter( base::MessageLoop* io_loop, base::MessageLoop* file_loop, content::ProtocolHandlerMap* protocol_handlers) : io_loop_(io_loop), file_loop_(file_loop) { // Must first be created on the UI thread. CEF_REQUIRE_UIT(); std::swap(protocol_handlers_, *protocol_handlers); } CefURLRequestContextGetter::~CefURLRequestContextGetter() { CEF_REQUIRE_IOT(); STLDeleteElements(&url_request_context_proxies_); } net::URLRequestContext* CefURLRequestContextGetter::GetURLRequestContext() { CEF_REQUIRE_IOT(); if (!url_request_context_.get()) { const base::FilePath& cache_path = CefContext::Get()->cache_path(); const CommandLine& command_line = *CommandLine::ForCurrentProcess(); const CefSettings& settings = CefContext::Get()->settings(); url_request_context_.reset(new net::URLRequestContext()); storage_.reset( new net::URLRequestContextStorage(url_request_context_.get())); bool persist_session_cookies = (settings.persist_session_cookies || command_line.HasSwitch(switches::kPersistSessionCookies)); SetCookieStoragePath(cache_path, persist_session_cookies); storage_->set_network_delegate(new CefNetworkDelegate); storage_->set_server_bound_cert_service(new net::ServerBoundCertService( new net::DefaultServerBoundCertStore(NULL), base::WorkerPool::GetTaskRunner(true))); storage_->set_http_user_agent_settings( new net::StaticHttpUserAgentSettings("en-us,en", EmptyString())); storage_->set_host_resolver(net::HostResolver::CreateDefaultResolver(NULL)); storage_->set_cert_verifier(net::CertVerifier::CreateDefault()); storage_->set_transport_security_state(new net::TransportSecurityState); scoped_ptr<net::ProxyService> system_proxy_service; system_proxy_service.reset( ProxyServiceFactory::CreateProxyService( NULL, url_request_context_.get(), url_request_context_->network_delegate(), CefContentBrowserClient::Get()->proxy_config_service().release(), command_line)); storage_->set_proxy_service(system_proxy_service.release()); storage_->set_ssl_config_service(new net::SSLConfigServiceDefaults); // Add support for single sign-on. url_security_manager_.reset(net::URLSecurityManager::Create(NULL, NULL)); std::vector<std::string> supported_schemes; supported_schemes.push_back("basic"); supported_schemes.push_back("digest"); supported_schemes.push_back("ntlm"); supported_schemes.push_back("negotiate"); storage_->set_http_auth_handler_factory( net::HttpAuthHandlerRegistryFactory::Create( supported_schemes, url_security_manager_.get(), url_request_context_->host_resolver(), std::string(), false, false)); storage_->set_http_server_properties( make_scoped_ptr<net::HttpServerProperties>( new net::HttpServerPropertiesImpl)); net::HttpCache::DefaultBackend* main_backend = new net::HttpCache::DefaultBackend( cache_path.empty() ? net::MEMORY_CACHE : net::DISK_CACHE, net::CACHE_BACKEND_DEFAULT, cache_path, 0, BrowserThread::GetMessageLoopProxyForThread( BrowserThread::CACHE)); net::HttpNetworkSession::Params network_session_params; network_session_params.host_resolver = url_request_context_->host_resolver(); network_session_params.cert_verifier = url_request_context_->cert_verifier(); network_session_params.transport_security_state = url_request_context_->transport_security_state(); network_session_params.server_bound_cert_service = url_request_context_->server_bound_cert_service(); network_session_params.proxy_service = url_request_context_->proxy_service(); network_session_params.ssl_config_service = url_request_context_->ssl_config_service(); network_session_params.http_auth_handler_factory = url_request_context_->http_auth_handler_factory(); network_session_params.network_delegate = url_request_context_->network_delegate(); network_session_params.http_server_properties = url_request_context_->http_server_properties(); network_session_params.ignore_certificate_errors = (settings.ignore_certificate_errors || command_line.HasSwitch(switches::kIgnoreCertificateErrors)); net::HttpCache* main_cache = new net::HttpCache(network_session_params, main_backend); storage_->set_http_transaction_factory(main_cache); #if !defined(DISABLE_FTP_SUPPORT) ftp_transaction_factory_.reset( new net::FtpNetworkLayer(network_session_params.host_resolver)); #endif scoped_ptr<net::URLRequestJobFactoryImpl> job_factory( new net::URLRequestJobFactoryImpl()); job_factory_impl_ = job_factory.get(); scheme::InstallInternalProtectedHandlers(job_factory.get(), &protocol_handlers_, ftp_transaction_factory_.get()); protocol_handlers_.clear(); storage_->set_job_factory(job_factory.release()); request_interceptor_.reset(new CefRequestInterceptor); } return url_request_context_.get(); } scoped_refptr<base::SingleThreadTaskRunner> CefURLRequestContextGetter::GetNetworkTaskRunner() const { return BrowserThread::GetMessageLoopProxyForThread(CEF_IOT); } net::HostResolver* CefURLRequestContextGetter::host_resolver() { return url_request_context_->host_resolver(); } void CefURLRequestContextGetter::SetCookieStoragePath( const base::FilePath& path, bool persist_session_cookies) { CEF_REQUIRE_IOT(); if (url_request_context_->cookie_store() && ((cookie_store_path_.empty() && path.empty()) || cookie_store_path_ == path)) { // The path has not changed so don't do anything. return; } scoped_refptr<content::SQLitePersistentCookieStore> persistent_store; if (!path.empty()) { // TODO(cef): Move directory creation to the blocking pool instead of // allowing file IO on this thread. base::ThreadRestrictions::ScopedAllowIO allow_io; if (base::DirectoryExists(path) || file_util::CreateDirectory(path)) { const base::FilePath& cookie_path = path.AppendASCII("Cookies"); persistent_store = new content::SQLitePersistentCookieStore( cookie_path, BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO), BrowserThread::GetMessageLoopProxyForThread(BrowserThread::DB), persist_session_cookies, NULL); } else { NOTREACHED() << "The cookie storage directory could not be created"; } } // Set the new cookie store that will be used for all new requests. The old // cookie store, if any, will be automatically flushed and closed when no // longer referenced. scoped_refptr<net::CookieMonster> cookie_monster = new net::CookieMonster(persistent_store.get(), NULL); storage_->set_cookie_store(cookie_monster); if (persistent_store.get() && persist_session_cookies) cookie_monster->SetPersistSessionCookies(true); cookie_store_path_ = path; // Restore the previously supported schemes. SetCookieSupportedSchemes(cookie_supported_schemes_); } void CefURLRequestContextGetter::SetCookieSupportedSchemes( const std::vector<std::string>& schemes) { CEF_REQUIRE_IOT(); cookie_supported_schemes_ = schemes; if (cookie_supported_schemes_.empty()) { cookie_supported_schemes_.push_back("http"); cookie_supported_schemes_.push_back("https"); } std::set<std::string> scheme_set; std::vector<std::string>::const_iterator it = cookie_supported_schemes_.begin(); for (; it != cookie_supported_schemes_.end(); ++it) scheme_set.insert(*it); const char** arr = new const char*[scheme_set.size()]; std::set<std::string>::const_iterator it2 = scheme_set.begin(); for (int i = 0; it2 != scheme_set.end(); ++it2, ++i) arr[i] = it2->c_str(); url_request_context_->cookie_store()->GetCookieMonster()-> SetCookieableSchemes(arr, scheme_set.size()); delete [] arr; } CefURLRequestContextProxy* CefURLRequestContextGetter::CreateURLRequestContextProxy() { CEF_REQUIRE_IOT(); CefURLRequestContextProxy* proxy = new CefURLRequestContextProxy(this); url_request_context_proxies_.insert(proxy); return proxy; } void CefURLRequestContextGetter::ReleaseURLRequestContextProxy( CefURLRequestContextProxy* proxy) { CEF_REQUIRE_IOT(); // Don't do anything if we're currently shutting down. The proxy objects will // be deleted when this object is destroyed. if (CefContext::Get()->shutting_down()) return; if (proxy->url_requests()->size() == 0) { // Safe to delete the proxy. RequestContextProxySet::iterator it = url_request_context_proxies_.find(proxy); DCHECK(it != url_request_context_proxies_.end()); url_request_context_proxies_.erase(it); delete proxy; } else { proxy->increment_delete_try_count(); if (proxy->delete_try_count() <= 1) { // Cancel the pending requests. This may result in additional tasks being // posted on the IO thread. std::set<const net::URLRequest*>::iterator it = proxy->url_requests()->begin(); for (; it != proxy->url_requests()->end(); ++it) const_cast<net::URLRequest*>(*it)->Cancel(); // Try to delete the proxy again later. CEF_POST_TASK(CEF_IOT, base::Bind(&CefURLRequestContextGetter::ReleaseURLRequestContextProxy, this, proxy)); } else { NOTREACHED() << "too many retries to delete URLRequestContext proxy object"; } } } void CefURLRequestContextGetter::CreateProxyConfigService() { if (proxy_config_service_.get()) return; proxy_config_service_.reset( net::ProxyService::CreateSystemProxyConfigService( io_loop_->message_loop_proxy(), file_loop_)); } <commit_msg>Fix AssertNoURLRequests due to pending proxy connections during shutdown (issue #1037).<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "libcef/browser/url_request_context_getter.h" #if defined(OS_WIN) #include <winhttp.h> #endif #include <string> #include <vector> #include "libcef/browser/content_browser_client.h" #include "libcef/browser/context.h" #include "libcef/browser/scheme_handler.h" #include "libcef/browser/thread_util.h" #include "libcef/browser/url_network_delegate.h" #include "libcef/browser/url_request_context_proxy.h" #include "libcef/browser/url_request_interceptor.h" #include "libcef/common/cef_switches.h" #include "base/command_line.h" #include "base/file_util.h" #include "base/logging.h" #include "base/stl_util.h" #include "base/strings/string_util.h" #include "base/threading/thread_restrictions.h" #include "base/threading/worker_pool.h" #include "chrome/browser/net/proxy_service_factory.h" #include "content/browser/net/sqlite_persistent_cookie_store.h" #include "content/public/browser/browser_thread.h" #include "content/public/common/content_switches.h" #include "content/public/common/url_constants.h" #include "net/cert/cert_verifier.h" #include "net/cookies/cookie_monster.h" #include "net/dns/host_resolver.h" #include "net/ftp/ftp_network_layer.h" #include "net/http/http_auth_handler_factory.h" #include "net/http/http_cache.h" #include "net/http/http_server_properties_impl.h" #include "net/http/transport_security_state.h" #include "net/proxy/proxy_service.h" #include "net/ssl/default_server_bound_cert_store.h" #include "net/ssl/server_bound_cert_service.h" #include "net/ssl/ssl_config_service_defaults.h" #include "net/url_request/static_http_user_agent_settings.h" #include "net/url_request/url_request.h" #include "net/url_request/url_request_context.h" #include "net/url_request/url_request_context_storage.h" #include "net/url_request/url_request_job_factory_impl.h" #include "net/url_request/url_request_job_manager.h" using content::BrowserThread; #if defined(OS_WIN) #pragma comment(lib, "winhttp.lib") #endif CefURLRequestContextGetter::CefURLRequestContextGetter( base::MessageLoop* io_loop, base::MessageLoop* file_loop, content::ProtocolHandlerMap* protocol_handlers) : io_loop_(io_loop), file_loop_(file_loop) { // Must first be created on the UI thread. CEF_REQUIRE_UIT(); std::swap(protocol_handlers_, *protocol_handlers); } CefURLRequestContextGetter::~CefURLRequestContextGetter() { CEF_REQUIRE_IOT(); STLDeleteElements(&url_request_context_proxies_); // Delete the ProxyService object here so that any pending requests will be // canceled before the associated URLRequestContext is destroyed in this // object's destructor. storage_->set_proxy_service(NULL); } net::URLRequestContext* CefURLRequestContextGetter::GetURLRequestContext() { CEF_REQUIRE_IOT(); if (!url_request_context_.get()) { const base::FilePath& cache_path = CefContext::Get()->cache_path(); const CommandLine& command_line = *CommandLine::ForCurrentProcess(); const CefSettings& settings = CefContext::Get()->settings(); url_request_context_.reset(new net::URLRequestContext()); storage_.reset( new net::URLRequestContextStorage(url_request_context_.get())); bool persist_session_cookies = (settings.persist_session_cookies || command_line.HasSwitch(switches::kPersistSessionCookies)); SetCookieStoragePath(cache_path, persist_session_cookies); storage_->set_network_delegate(new CefNetworkDelegate); storage_->set_server_bound_cert_service(new net::ServerBoundCertService( new net::DefaultServerBoundCertStore(NULL), base::WorkerPool::GetTaskRunner(true))); storage_->set_http_user_agent_settings( new net::StaticHttpUserAgentSettings("en-us,en", EmptyString())); storage_->set_host_resolver(net::HostResolver::CreateDefaultResolver(NULL)); storage_->set_cert_verifier(net::CertVerifier::CreateDefault()); storage_->set_transport_security_state(new net::TransportSecurityState); scoped_ptr<net::ProxyService> system_proxy_service; system_proxy_service.reset( ProxyServiceFactory::CreateProxyService( NULL, url_request_context_.get(), url_request_context_->network_delegate(), CefContentBrowserClient::Get()->proxy_config_service().release(), command_line)); storage_->set_proxy_service(system_proxy_service.release()); storage_->set_ssl_config_service(new net::SSLConfigServiceDefaults); // Add support for single sign-on. url_security_manager_.reset(net::URLSecurityManager::Create(NULL, NULL)); std::vector<std::string> supported_schemes; supported_schemes.push_back("basic"); supported_schemes.push_back("digest"); supported_schemes.push_back("ntlm"); supported_schemes.push_back("negotiate"); storage_->set_http_auth_handler_factory( net::HttpAuthHandlerRegistryFactory::Create( supported_schemes, url_security_manager_.get(), url_request_context_->host_resolver(), std::string(), false, false)); storage_->set_http_server_properties( make_scoped_ptr<net::HttpServerProperties>( new net::HttpServerPropertiesImpl)); net::HttpCache::DefaultBackend* main_backend = new net::HttpCache::DefaultBackend( cache_path.empty() ? net::MEMORY_CACHE : net::DISK_CACHE, net::CACHE_BACKEND_DEFAULT, cache_path, 0, BrowserThread::GetMessageLoopProxyForThread( BrowserThread::CACHE)); net::HttpNetworkSession::Params network_session_params; network_session_params.host_resolver = url_request_context_->host_resolver(); network_session_params.cert_verifier = url_request_context_->cert_verifier(); network_session_params.transport_security_state = url_request_context_->transport_security_state(); network_session_params.server_bound_cert_service = url_request_context_->server_bound_cert_service(); network_session_params.proxy_service = url_request_context_->proxy_service(); network_session_params.ssl_config_service = url_request_context_->ssl_config_service(); network_session_params.http_auth_handler_factory = url_request_context_->http_auth_handler_factory(); network_session_params.network_delegate = url_request_context_->network_delegate(); network_session_params.http_server_properties = url_request_context_->http_server_properties(); network_session_params.ignore_certificate_errors = (settings.ignore_certificate_errors || command_line.HasSwitch(switches::kIgnoreCertificateErrors)); net::HttpCache* main_cache = new net::HttpCache(network_session_params, main_backend); storage_->set_http_transaction_factory(main_cache); #if !defined(DISABLE_FTP_SUPPORT) ftp_transaction_factory_.reset( new net::FtpNetworkLayer(network_session_params.host_resolver)); #endif scoped_ptr<net::URLRequestJobFactoryImpl> job_factory( new net::URLRequestJobFactoryImpl()); job_factory_impl_ = job_factory.get(); scheme::InstallInternalProtectedHandlers(job_factory.get(), &protocol_handlers_, ftp_transaction_factory_.get()); protocol_handlers_.clear(); storage_->set_job_factory(job_factory.release()); request_interceptor_.reset(new CefRequestInterceptor); } return url_request_context_.get(); } scoped_refptr<base::SingleThreadTaskRunner> CefURLRequestContextGetter::GetNetworkTaskRunner() const { return BrowserThread::GetMessageLoopProxyForThread(CEF_IOT); } net::HostResolver* CefURLRequestContextGetter::host_resolver() { return url_request_context_->host_resolver(); } void CefURLRequestContextGetter::SetCookieStoragePath( const base::FilePath& path, bool persist_session_cookies) { CEF_REQUIRE_IOT(); if (url_request_context_->cookie_store() && ((cookie_store_path_.empty() && path.empty()) || cookie_store_path_ == path)) { // The path has not changed so don't do anything. return; } scoped_refptr<content::SQLitePersistentCookieStore> persistent_store; if (!path.empty()) { // TODO(cef): Move directory creation to the blocking pool instead of // allowing file IO on this thread. base::ThreadRestrictions::ScopedAllowIO allow_io; if (base::DirectoryExists(path) || file_util::CreateDirectory(path)) { const base::FilePath& cookie_path = path.AppendASCII("Cookies"); persistent_store = new content::SQLitePersistentCookieStore( cookie_path, BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO), BrowserThread::GetMessageLoopProxyForThread(BrowserThread::DB), persist_session_cookies, NULL); } else { NOTREACHED() << "The cookie storage directory could not be created"; } } // Set the new cookie store that will be used for all new requests. The old // cookie store, if any, will be automatically flushed and closed when no // longer referenced. scoped_refptr<net::CookieMonster> cookie_monster = new net::CookieMonster(persistent_store.get(), NULL); storage_->set_cookie_store(cookie_monster); if (persistent_store.get() && persist_session_cookies) cookie_monster->SetPersistSessionCookies(true); cookie_store_path_ = path; // Restore the previously supported schemes. SetCookieSupportedSchemes(cookie_supported_schemes_); } void CefURLRequestContextGetter::SetCookieSupportedSchemes( const std::vector<std::string>& schemes) { CEF_REQUIRE_IOT(); cookie_supported_schemes_ = schemes; if (cookie_supported_schemes_.empty()) { cookie_supported_schemes_.push_back("http"); cookie_supported_schemes_.push_back("https"); } std::set<std::string> scheme_set; std::vector<std::string>::const_iterator it = cookie_supported_schemes_.begin(); for (; it != cookie_supported_schemes_.end(); ++it) scheme_set.insert(*it); const char** arr = new const char*[scheme_set.size()]; std::set<std::string>::const_iterator it2 = scheme_set.begin(); for (int i = 0; it2 != scheme_set.end(); ++it2, ++i) arr[i] = it2->c_str(); url_request_context_->cookie_store()->GetCookieMonster()-> SetCookieableSchemes(arr, scheme_set.size()); delete [] arr; } CefURLRequestContextProxy* CefURLRequestContextGetter::CreateURLRequestContextProxy() { CEF_REQUIRE_IOT(); CefURLRequestContextProxy* proxy = new CefURLRequestContextProxy(this); url_request_context_proxies_.insert(proxy); return proxy; } void CefURLRequestContextGetter::ReleaseURLRequestContextProxy( CefURLRequestContextProxy* proxy) { CEF_REQUIRE_IOT(); // Don't do anything if we're currently shutting down. The proxy objects will // be deleted when this object is destroyed. if (CefContext::Get()->shutting_down()) return; if (proxy->url_requests()->size() == 0) { // Safe to delete the proxy. RequestContextProxySet::iterator it = url_request_context_proxies_.find(proxy); DCHECK(it != url_request_context_proxies_.end()); url_request_context_proxies_.erase(it); delete proxy; } else { proxy->increment_delete_try_count(); if (proxy->delete_try_count() <= 1) { // Cancel the pending requests. This may result in additional tasks being // posted on the IO thread. std::set<const net::URLRequest*>::iterator it = proxy->url_requests()->begin(); for (; it != proxy->url_requests()->end(); ++it) const_cast<net::URLRequest*>(*it)->Cancel(); // Try to delete the proxy again later. CEF_POST_TASK(CEF_IOT, base::Bind(&CefURLRequestContextGetter::ReleaseURLRequestContextProxy, this, proxy)); } else { NOTREACHED() << "too many retries to delete URLRequestContext proxy object"; } } } void CefURLRequestContextGetter::CreateProxyConfigService() { if (proxy_config_service_.get()) return; proxy_config_service_.reset( net::ProxyService::CreateSystemProxyConfigService( io_loop_->message_loop_proxy(), file_loop_)); } <|endoftext|>
<commit_before>/* * Copyright (c) 2008-2016 the MRtrix3 contributors * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/ * * MRtrix is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * For more details, see www.mrtrix.org * */ #include "command.h" #include "progressbar.h" #include "algo/loop.h" #include "image.h" #include "fixel_format/helpers.h" #include "fixel_format/keys.h" using namespace MR; using namespace App; void usage () { AUTHOR = "David Raffelt (david.raffelt@florey.edu.au)"; DESCRIPTION + "Crop a fixel index image along with corresponding fixel data images"; ARGUMENTS + Argument ("dir_in", "the input fixel folder").type_text () + Argument ("dir_out", "the output fixel folder").type_text (); OPTIONS + Option ("mask", "the threshold mask").required () + Argument ("image").type_image_in () + Option ("data", "specify a fixel data image filename (relative to the input fixel folder) to " "be cropped.").allow_multiple () + Argument ("image").type_image_in (); } void run () { const auto fixel_folder = argument[0]; FixelFormat::check_fixel_folder (fixel_folder); const auto out_fixel_folder = argument[1]; auto index_image = FixelFormat::find_index_header (fixel_folder).get_image <uint32_t> (); auto opt = get_options ("mask"); auto mask_image = Image<bool>::open (std::string (opt[0][0])); FixelFormat::check_fixel_size (index_image, mask_image); FixelFormat::check_fixel_folder (out_fixel_folder, true); Header out_header = Header (index_image); size_t total_nfixels = std::stoul (out_header.keyval ()[FixelFormat::n_fixels_key]); // We need to do a first pass fo the mask image to determine the cropped num. of fixels for (auto l = Loop (0) (mask_image); l; ++l) { if (!mask_image.value ()) total_nfixels --; } out_header.keyval ()[FixelFormat::n_fixels_key] = str (total_nfixels); const auto index_image_basename = Path::basename (index_image.name ()); auto out_index_image = Image<uint32_t>::create (Path::join (out_fixel_folder, index_image_basename), out_header); // Crop index image mask_image.index (1) = 0; for (auto l = Loop ("cropping index image: " + index_image_basename, 0, 3) (index_image, out_index_image); l; ++l) { index_image.index (3) = 0; size_t nfixels = index_image.value (); index_image.index (3) = 1; size_t offset = index_image.value (); for (size_t i = 0, N = nfixels; i < N; ++i) { mask_image.index (0) = offset + i; if (!mask_image.value ()) nfixels--; } out_index_image.index (3) = 0; out_index_image.value () = nfixels; out_index_image.index (3) = 1; out_index_image.value () = offset; } // Crop data images opt = get_options ("data"); for (size_t n = 0, N = opt.size (); n < N; n++) { const auto data_file = opt[n][0]; const auto data_file_path = Path::join (fixel_folder, data_file); Header header = Header::open (data_file_path); auto in_data = header.get_image <float> (); check_dimensions (in_data, mask_image, {0, 2}); header.size (0) = total_nfixels; auto out_data = Image<float>::create (Path::join (out_fixel_folder, data_file), header); size_t offset(0); for (auto l = Loop ("cropping data: " + data_file, 0) (mask_image, in_data); l; ++l) { if (mask_image.value ()) { out_data.index (1) = offset; out_data.row (1) = in_data.row (1); offset++; } } } } <commit_msg>fixelcrop: Fixing comment typo<commit_after>/* * Copyright (c) 2008-2016 the MRtrix3 contributors * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/ * * MRtrix is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * For more details, see www.mrtrix.org * */ #include "command.h" #include "progressbar.h" #include "algo/loop.h" #include "image.h" #include "fixel_format/helpers.h" #include "fixel_format/keys.h" using namespace MR; using namespace App; void usage () { AUTHOR = "David Raffelt (david.raffelt@florey.edu.au)"; DESCRIPTION + "Crop a fixel index image along with corresponding fixel data images"; ARGUMENTS + Argument ("dir_in", "the input fixel folder").type_text () + Argument ("dir_out", "the output fixel folder").type_text (); OPTIONS + Option ("mask", "the threshold mask").required () + Argument ("image").type_image_in () + Option ("data", "specify a fixel data image filename (relative to the input fixel folder) to " "be cropped.").allow_multiple () + Argument ("image").type_image_in (); } void run () { const auto fixel_folder = argument[0]; FixelFormat::check_fixel_folder (fixel_folder); const auto out_fixel_folder = argument[1]; auto index_image = FixelFormat::find_index_header (fixel_folder).get_image <uint32_t> (); auto opt = get_options ("mask"); auto mask_image = Image<bool>::open (std::string (opt[0][0])); FixelFormat::check_fixel_size (index_image, mask_image); FixelFormat::check_fixel_folder (out_fixel_folder, true); Header out_header = Header (index_image); size_t total_nfixels = std::stoul (out_header.keyval ()[FixelFormat::n_fixels_key]); // We need to do a first pass of the mask image to determine the cropped num. of fixels for (auto l = Loop (0) (mask_image); l; ++l) { if (!mask_image.value ()) total_nfixels --; } out_header.keyval ()[FixelFormat::n_fixels_key] = str (total_nfixels); const auto index_image_basename = Path::basename (index_image.name ()); auto out_index_image = Image<uint32_t>::create (Path::join (out_fixel_folder, index_image_basename), out_header); // Crop index image mask_image.index (1) = 0; for (auto l = Loop ("cropping index image: " + index_image_basename, 0, 3) (index_image, out_index_image); l; ++l) { index_image.index (3) = 0; size_t nfixels = index_image.value (); index_image.index (3) = 1; size_t offset = index_image.value (); for (size_t i = 0, N = nfixels; i < N; ++i) { mask_image.index (0) = offset + i; if (!mask_image.value ()) nfixels--; } out_index_image.index (3) = 0; out_index_image.value () = nfixels; out_index_image.index (3) = 1; out_index_image.value () = offset; } // Crop data images opt = get_options ("data"); for (size_t n = 0, N = opt.size (); n < N; n++) { const auto data_file = opt[n][0]; const auto data_file_path = Path::join (fixel_folder, data_file); Header header = Header::open (data_file_path); auto in_data = header.get_image <float> (); check_dimensions (in_data, mask_image, {0, 2}); header.size (0) = total_nfixels; auto out_data = Image<float>::create (Path::join (out_fixel_folder, data_file), header); size_t offset(0); for (auto l = Loop ("cropping data: " + data_file, 0) (mask_image, in_data); l; ++l) { if (mask_image.value ()) { out_data.index (1) = offset; out_data.row (1) = in_data.row (1); offset++; } } } } <|endoftext|>
<commit_before>/* * This file is part of Poedit (https://poedit.net) * * Copyright (C) 2000-2018 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 <wx/utils.h> #include <wx/log.h> #include <wx/process.h> #include <wx/txtstrm.h> #include <wx/string.h> #include <wx/intl.h> #include <wx/stdpaths.h> #include <wx/translation.h> #include <wx/filename.h> #include <boost/throw_exception.hpp> #include "gexecute.h" #include "errors.h" // GCC's libstdc++ didn't have functional std::regex implementation until 4.9 #if (defined(__GNUC__) && !defined(__clang__) && !wxCHECK_GCC_VERSION(4,9)) #include <boost/regex.hpp> using boost::wregex; using boost::wsmatch; using boost::regex_match; #else #include <regex> using std::wregex; using std::wsmatch; using std::regex_match; #endif namespace { #ifdef __WXOSX__ wxString GetGettextPluginPath() { return wxStandardPaths::Get().GetPluginsDir() + "/GettextTools.bundle"; } #endif // __WXOSX__ #if defined(__WXOSX__) || defined(__WXMSW__) inline wxString GetAuxBinariesDir() { return GetGettextPackagePath() + "/bin"; } wxString GetPathToAuxBinary(const wxString& program) { wxFileName path; path.SetPath(GetAuxBinariesDir()); path.SetName(program); #ifdef __WXMSW__ path.SetExt("exe"); #endif if ( path.IsFileExecutable() ) { return wxString::Format(_T("\"%s\""), path.GetFullPath().c_str()); } else { wxLogTrace("poedit.execute", L"%s doesn’t exist, falling back to %s", path.GetFullPath().c_str(), program.c_str()); return program; } } #endif // __WXOSX__ || __WXMSW__ bool ReadOutput(wxInputStream& s, wxArrayString& out) { // the stream could be already at EOF or in wxSTREAM_BROKEN_PIPE state s.Reset(); wxTextInputStream tis(s, " ", wxConvAuto() /* UTF-8, fallback if impossible */); while (true) { wxString line = tis.ReadLine(); if ( !line.empty() ) out.push_back(line); if (s.Eof()) break; if ( !s ) return false; } return true; } long DoExecuteGettext(const wxString& cmdline_, wxArrayString& gstderr) { wxExecuteEnv env; wxString cmdline(cmdline_); #if defined(__WXOSX__) || defined(__WXMSW__) wxString binary = cmdline.BeforeFirst(_T(' ')); cmdline = GetPathToAuxBinary(binary) + cmdline.Mid(binary.length()); wxGetEnvMap(&env.env); env.env["GETTEXTIOENCODING"] = "UTF-8"; wxString lang = wxTranslations::Get()->GetBestTranslation("gettext-tools"); if ( !lang.empty() ) env.env["LANG"] = lang; #endif // __WXOSX__ || __WXMSW__ #ifdef __WXOSX__ // Hack alert! On Windows, relocation works, but building with it is too // messy/broken on macOS, so just use some custom hacks instead: auto sharedir = GetGettextPackagePath() + "/share"; env.env["POEDIT_LOCALEDIR"] = sharedir + "/locale"; env.env["GETTEXTDATADIR"] = sharedir + "/gettext"; #endif wxLogTrace("poedit.execute", "executing: %s", cmdline.c_str()); wxScopedPtr<wxProcess> process(new wxProcess); process->Redirect(); long retcode = wxExecute(cmdline, wxEXEC_BLOCK | wxEXEC_NODISABLE | wxEXEC_NOEVENTS, process.get(), &env); wxInputStream *std_err = process->GetErrorStream(); if ( std_err && !ReadOutput(*std_err, gstderr) ) retcode = -1; if ( retcode == -1 ) { BOOST_THROW_EXCEPTION(Exception(wxString::Format(_("Cannot execute program: %s"), cmdline.c_str()))); } return retcode; } } // anonymous namespace bool ExecuteGettext(const wxString& cmdline) { wxArrayString gstderr; long retcode = DoExecuteGettext(cmdline, gstderr); wxString pending; for (auto& ln: gstderr) { if (ln.empty()) continue; // special handling of multiline errors if (ln[0] == ' ' || ln[0] == '\t') { pending += "\n\t" + ln.Strip(wxString::both); } else { if (!pending.empty()) wxLogError("%s", pending); pending = ln; } } if (!pending.empty()) wxLogError("%s", pending); return retcode == 0; } bool ExecuteGettextAndParseOutput(const wxString& cmdline, GettextErrors& errors) { wxArrayString gstderr; long retcode = DoExecuteGettext(cmdline, gstderr); static const wregex RE_ERROR(L".*\\.po:([0-9]+)(:[0-9]+)?: (.*)"); for (const auto& ewx: gstderr) { const auto e = ewx.ToStdWstring(); wxLogTrace("poedit", " stderr: %s", e.c_str()); if ( e.empty() ) continue; GettextError rec; wsmatch match; if (regex_match(e, match, RE_ERROR)) { rec.line = std::stoi(match.str(1)); rec.text = match.str(3); errors.push_back(rec); wxLogTrace("poedit.execute", _T(" => parsed error = \"%s\" at %d"), rec.text.c_str(), rec.line); } else { wxLogTrace("poedit.execute", " (unrecognized line!)"); // FIXME: handle the rest of output gracefully too } } return retcode == 0; } wxString QuoteCmdlineArg(const wxString& s) { wxString s2(s); #ifdef __UNIX__ s2.Replace("\"", "\\\""); #endif return "\"" + s2 + "\""; } #if defined(__WXOSX__) || defined(__WXMSW__) wxString GetGettextPackagePath() { #if defined(__WXOSX__) return GetGettextPluginPath() + "/Contents/MacOS"; #elif defined(__WXMSW__) return wxStandardPaths::Get().GetDataDir() + wxFILE_SEP_PATH + "GettextTools"; #endif } #endif // __WXOSX__ || __WXMSW__ <commit_msg>Fix mangled non-English gettext error messages<commit_after>/* * This file is part of Poedit (https://poedit.net) * * Copyright (C) 2000-2018 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 <wx/utils.h> #include <wx/log.h> #include <wx/process.h> #include <wx/txtstrm.h> #include <wx/string.h> #include <wx/intl.h> #include <wx/stdpaths.h> #include <wx/translation.h> #include <wx/filename.h> #include <boost/throw_exception.hpp> #include "gexecute.h" #include "errors.h" // GCC's libstdc++ didn't have functional std::regex implementation until 4.9 #if (defined(__GNUC__) && !defined(__clang__) && !wxCHECK_GCC_VERSION(4,9)) #include <boost/regex.hpp> using boost::wregex; using boost::wsmatch; using boost::regex_match; #else #include <regex> using std::wregex; using std::wsmatch; using std::regex_match; #endif namespace { #ifdef __WXOSX__ wxString GetGettextPluginPath() { return wxStandardPaths::Get().GetPluginsDir() + "/GettextTools.bundle"; } #endif // __WXOSX__ #if defined(__WXOSX__) || defined(__WXMSW__) inline wxString GetAuxBinariesDir() { return GetGettextPackagePath() + "/bin"; } wxString GetPathToAuxBinary(const wxString& program) { wxFileName path; path.SetPath(GetAuxBinariesDir()); path.SetName(program); #ifdef __WXMSW__ path.SetExt("exe"); #endif if ( path.IsFileExecutable() ) { return wxString::Format(_T("\"%s\""), path.GetFullPath().c_str()); } else { wxLogTrace("poedit.execute", L"%s doesn’t exist, falling back to %s", path.GetFullPath().c_str(), program.c_str()); return program; } } #endif // __WXOSX__ || __WXMSW__ bool ReadOutput(wxInputStream& s, wxArrayString& out) { // the stream could be already at EOF or in wxSTREAM_BROKEN_PIPE state s.Reset(); // Read the input as Latin1, even though we know it's UTF-8. This is terrible, // terrible thing to do, but gettext tools may sometimes output invalid UTF-8 // (e.g. when using non-ASCII, non-UTF8 msgids) and wxTextInputStream logic // can't cope well with failing conversions. To make this work, we read the // input as Latin1 and later re-encode it back and re-parse as UTF-8. wxTextInputStream tis(s, " ", wxConvISO8859_1); while (true) { const wxString line = tis.ReadLine(); if ( !line.empty() ) { // reconstruct the UTF-8 text if we can wxString line2(line.mb_str(wxConvISO8859_1), wxConvUTF8); if (line2.empty()) line2 = line; out.push_back(line2); } if (s.Eof()) break; if ( !s ) return false; } return true; } long DoExecuteGettext(const wxString& cmdline_, wxArrayString& gstderr) { wxExecuteEnv env; wxString cmdline(cmdline_); #if defined(__WXOSX__) || defined(__WXMSW__) wxString binary = cmdline.BeforeFirst(_T(' ')); cmdline = GetPathToAuxBinary(binary) + cmdline.Mid(binary.length()); wxGetEnvMap(&env.env); env.env["GETTEXTIOENCODING"] = "UTF-8"; wxString lang = wxTranslations::Get()->GetBestTranslation("gettext-tools"); if ( !lang.empty() ) env.env["LANG"] = lang; #endif // __WXOSX__ || __WXMSW__ #ifdef __WXOSX__ // Hack alert! On Windows, relocation works, but building with it is too // messy/broken on macOS, so just use some custom hacks instead: auto sharedir = GetGettextPackagePath() + "/share"; env.env["POEDIT_LOCALEDIR"] = sharedir + "/locale"; env.env["GETTEXTDATADIR"] = sharedir + "/gettext"; #endif wxLogTrace("poedit.execute", "executing: %s", cmdline.c_str()); wxScopedPtr<wxProcess> process(new wxProcess); process->Redirect(); long retcode = wxExecute(cmdline, wxEXEC_BLOCK | wxEXEC_NODISABLE | wxEXEC_NOEVENTS, process.get(), &env); wxInputStream *std_err = process->GetErrorStream(); if ( std_err && !ReadOutput(*std_err, gstderr) ) retcode = -1; if ( retcode == -1 ) { BOOST_THROW_EXCEPTION(Exception(wxString::Format(_("Cannot execute program: %s"), cmdline.c_str()))); } return retcode; } } // anonymous namespace bool ExecuteGettext(const wxString& cmdline) { wxArrayString gstderr; long retcode = DoExecuteGettext(cmdline, gstderr); wxString pending; for (auto& ln: gstderr) { if (ln.empty()) continue; // special handling of multiline errors if (ln[0] == ' ' || ln[0] == '\t') { pending += "\n\t" + ln.Strip(wxString::both); } else { if (!pending.empty()) wxLogError("%s", pending); pending = ln; } } if (!pending.empty()) wxLogError("%s", pending); return retcode == 0; } bool ExecuteGettextAndParseOutput(const wxString& cmdline, GettextErrors& errors) { wxArrayString gstderr; long retcode = DoExecuteGettext(cmdline, gstderr); static const wregex RE_ERROR(L".*\\.po:([0-9]+)(:[0-9]+)?: (.*)"); for (const auto& ewx: gstderr) { const auto e = ewx.ToStdWstring(); wxLogTrace("poedit", " stderr: %s", e.c_str()); if ( e.empty() ) continue; GettextError rec; wsmatch match; if (regex_match(e, match, RE_ERROR)) { rec.line = std::stoi(match.str(1)); rec.text = match.str(3); errors.push_back(rec); wxLogTrace("poedit.execute", _T(" => parsed error = \"%s\" at %d"), rec.text.c_str(), rec.line); } else { wxLogTrace("poedit.execute", " (unrecognized line!)"); // FIXME: handle the rest of output gracefully too } } return retcode == 0; } wxString QuoteCmdlineArg(const wxString& s) { wxString s2(s); #ifdef __UNIX__ s2.Replace("\"", "\\\""); #endif return "\"" + s2 + "\""; } #if defined(__WXOSX__) || defined(__WXMSW__) wxString GetGettextPackagePath() { #if defined(__WXOSX__) return GetGettextPluginPath() + "/Contents/MacOS"; #elif defined(__WXMSW__) return wxStandardPaths::Get().GetDataDir() + wxFILE_SEP_PATH + "GettextTools"; #endif } #endif // __WXOSX__ || __WXMSW__ <|endoftext|>
<commit_before>#include "types.h" #include "stat.h" #include "user.h" #include "mtrace.h" #include "amd64.h" #include "fcntl.h" static const bool pinit = true; enum { nloop = 100 }; enum { nfile = 10 }; enum { nlookup = 100 }; void bench(u32 tid) { char pn[MAXNAME]; if (pinit) setaffinity(tid); for (u32 x = 0; x < nloop; x++) { for (u32 i = 0; i < nfile; i++) { snprintf(pn, sizeof(pn), "/dbx/f:%d:%d", tid, i); int fd = open(pn, O_CREATE | O_RDWR); if (fd < 0) die("create failed\n"); close(fd); } for (u32 i = 0; i < nlookup; i++) { snprintf(pn, sizeof(pn), "/dbx/f:%d:%d", tid, (i % nfile)); int fd = open(pn, O_RDWR); if (fd < 0) die("open failed\n"); close(fd); } for (u32 i = 0; i < nfile; i++) { snprintf(pn, sizeof(pn), "/dbx/f:%d:%d", tid, i); if (unlink(pn) < 0) die("unlink failed\n"); } } exit(); } int main(int ac, char** av) { int nthread; if (ac < 2) die("usage: %s nthreads", av[0]); nthread = atoi(av[1]); mkdir("/dbx"); u64 t0 = rdtsc(); for(u32 i = 0; i < nthread; i++) { int pid = fork(0); if (pid == 0) bench(i); else if (pid < 0) die("fork"); } for (u32 i = 0; i < nthread; i++) wait(); u64 t1 = rdtsc(); printf("dirbench: %lu\n", t1-t0); return 0; } <commit_msg>dirbench hack for qemu<commit_after>#include "types.h" #include "stat.h" #include "user.h" #include "mtrace.h" #include "amd64.h" #include "fcntl.h" static const bool pinit = true; #ifdef HW_qemu enum { nloop = 100 }; #else enum { nloop = 1000 }; #endif enum { nfile = 10 }; enum { nlookup = 100 }; void bench(u32 tid) { char pn[MAXNAME]; if (pinit) setaffinity(tid); for (u32 x = 0; x < nloop; x++) { for (u32 i = 0; i < nfile; i++) { snprintf(pn, sizeof(pn), "/dbx/f:%d:%d", tid, i); int fd = open(pn, O_CREATE | O_RDWR); if (fd < 0) die("create failed\n"); close(fd); } for (u32 i = 0; i < nlookup; i++) { snprintf(pn, sizeof(pn), "/dbx/f:%d:%d", tid, (i % nfile)); int fd = open(pn, O_RDWR); if (fd < 0) die("open failed\n"); close(fd); } for (u32 i = 0; i < nfile; i++) { snprintf(pn, sizeof(pn), "/dbx/f:%d:%d", tid, i); if (unlink(pn) < 0) die("unlink failed\n"); } } exit(); } int main(int ac, char** av) { int nthread; if (ac < 2) die("usage: %s nthreads", av[0]); nthread = atoi(av[1]); mkdir("/dbx"); u64 t0 = rdtsc(); for(u32 i = 0; i < nthread; i++) { int pid = fork(0); if (pid == 0) bench(i); else if (pid < 0) die("fork"); } for (u32 i = 0; i < nthread; i++) wait(); u64 t1 = rdtsc(); printf("dirbench: %lu\n", t1-t0); return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2011-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include <config/bitcoin-config.h> #endif #include <qt/forms/ui_optionsdialog.h> #include <qt/optionsdialog.h> #include <interfaces/node.h> #include <netbase.h> #include <qt/bitcoinunits.h> #include <qt/guiconstants.h> #include <qt/guiutil.h> #include <qt/optionsmodel.h> #include <txdb.h> // for -dbcache defaults #include <validation.h> // for DEFAULT_SCRIPTCHECK_THREADS and MAX_SCRIPTCHECK_THREADS #include <QDataWidgetMapper> #include <QDir> #include <QIntValidator> #include <QLocale> #include <QMessageBox> #include <QSystemTrayIcon> #include <QTimer> OptionsDialog::OptionsDialog(QWidget *parent, bool enableWallet) : QDialog(parent), ui(new Ui::OptionsDialog), model(nullptr), mapper(nullptr) { ui->setupUi(this); /* Main elements init */ ui->databaseCache->setMinimum(nMinDbCache); ui->databaseCache->setMaximum(nMaxDbCache); ui->threadsScriptVerif->setMinimum(-GetNumCores()); ui->threadsScriptVerif->setMaximum(MAX_SCRIPTCHECK_THREADS); ui->pruneWarning->setVisible(false); ui->pruneWarning->setStyleSheet("QLabel { color: red; }"); ui->pruneSize->setEnabled(false); connect(ui->prune, &QPushButton::toggled, ui->pruneSize, &QWidget::setEnabled); /* Network elements init */ #ifndef USE_UPNP ui->mapPortUpnp->setEnabled(false); #endif ui->proxyIp->setEnabled(false); ui->proxyPort->setEnabled(false); ui->proxyPort->setValidator(new QIntValidator(1, 65535, this)); ui->proxyIpTor->setEnabled(false); ui->proxyPortTor->setEnabled(false); ui->proxyPortTor->setValidator(new QIntValidator(1, 65535, this)); connect(ui->connectSocks, &QPushButton::toggled, ui->proxyIp, &QWidget::setEnabled); connect(ui->connectSocks, &QPushButton::toggled, ui->proxyPort, &QWidget::setEnabled); connect(ui->connectSocks, &QPushButton::toggled, this, &OptionsDialog::updateProxyValidationState); connect(ui->connectSocksTor, &QPushButton::toggled, ui->proxyIpTor, &QWidget::setEnabled); connect(ui->connectSocksTor, &QPushButton::toggled, ui->proxyPortTor, &QWidget::setEnabled); connect(ui->connectSocksTor, &QPushButton::toggled, this, &OptionsDialog::updateProxyValidationState); /* Window elements init */ #ifdef Q_OS_MAC /* remove Window tab on Mac */ ui->tabWidget->removeTab(ui->tabWidget->indexOf(ui->tabWindow)); /* hide launch at startup option on macOS */ ui->bitcoinAtStartup->setVisible(false); ui->verticalLayout_Main->removeWidget(ui->bitcoinAtStartup); ui->verticalLayout_Main->removeItem(ui->horizontalSpacer_0_Main); #endif /* remove Wallet tab in case of -disablewallet */ if (!enableWallet) { ui->tabWidget->removeTab(ui->tabWidget->indexOf(ui->tabWallet)); } /* Display elements init */ QDir translations(":translations"); ui->bitcoinAtStartup->setToolTip( ui->bitcoinAtStartup->toolTip().arg(PACKAGE_NAME)); ui->bitcoinAtStartup->setText( ui->bitcoinAtStartup->text().arg(PACKAGE_NAME)); ui->openBitcoinConfButton->setToolTip( ui->openBitcoinConfButton->toolTip().arg(PACKAGE_NAME)); ui->lang->setToolTip(ui->lang->toolTip().arg(PACKAGE_NAME)); ui->lang->addItem(QString("(") + tr("default") + QString(")"), QVariant("")); for (const QString &langStr : translations.entryList()) { QLocale locale(langStr); /** check if the locale name consists of 2 parts (language_country) */ if (langStr.contains("_")) { /** display language strings as "native language - native country * (locale name)", e.g. "Deutsch - Deutschland (de)" */ ui->lang->addItem(locale.nativeLanguageName() + QString(" - ") + locale.nativeCountryName() + QString(" (") + langStr + QString(")"), QVariant(langStr)); } else { /** display language strings as "native language (locale name)", * e.g. "Deutsch (de)" */ ui->lang->addItem(locale.nativeLanguageName() + QString(" (") + langStr + QString(")"), QVariant(langStr)); } } ui->unit->setModel(new BitcoinUnits(this)); /* Widget-to-option mapper */ mapper = new QDataWidgetMapper(this); mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit); mapper->setOrientation(Qt::Vertical); GUIUtil::ItemDelegate *delegate = new GUIUtil::ItemDelegate(mapper); connect(delegate, &GUIUtil::ItemDelegate::keyEscapePressed, this, &OptionsDialog::reject); mapper->setItemDelegate(delegate); /* setup/change UI elements when proxy IPs are invalid/valid */ ui->proxyIp->setCheckValidator(new ProxyAddressValidator(parent)); ui->proxyIpTor->setCheckValidator(new ProxyAddressValidator(parent)); connect(ui->proxyIp, &QValidatedLineEdit::validationDidChange, this, &OptionsDialog::updateProxyValidationState); connect(ui->proxyIpTor, &QValidatedLineEdit::validationDidChange, this, &OptionsDialog::updateProxyValidationState); connect(ui->proxyPort, &QLineEdit::textChanged, this, &OptionsDialog::updateProxyValidationState); connect(ui->proxyPortTor, &QLineEdit::textChanged, this, &OptionsDialog::updateProxyValidationState); if (!QSystemTrayIcon::isSystemTrayAvailable()) { ui->hideTrayIcon->setChecked(true); ui->hideTrayIcon->setEnabled(false); ui->minimizeToTray->setChecked(false); ui->minimizeToTray->setEnabled(false); } } OptionsDialog::~OptionsDialog() { delete ui; } void OptionsDialog::setModel(OptionsModel *_model) { this->model = _model; if (_model) { /* check if client restart is needed and show persistent message */ if (_model->isRestartRequired()) { showRestartWarning(true); } // Prune values are in GB to be consistent with intro.cpp static constexpr uint64_t nMinDiskSpace = (MIN_DISK_SPACE_FOR_BLOCK_FILES / GB_BYTES) + (MIN_DISK_SPACE_FOR_BLOCK_FILES % GB_BYTES) ? 1 : 0; ui->pruneSize->setRange(nMinDiskSpace, std::numeric_limits<int>::max()); QString strLabel = _model->getOverriddenByCommandLine(); if (strLabel.isEmpty()) { strLabel = tr("none"); } ui->overriddenByCommandLineLabel->setText(strLabel); mapper->setModel(_model); setMapper(); mapper->toFirst(); updateDefaultProxyNets(); } /* warn when one of the following settings changes by user action (placed * here so init via mapper doesn't trigger them) */ /* Main */ connect(ui->prune, &QCheckBox::clicked, this, &OptionsDialog::showRestartWarning); connect(ui->prune, &QCheckBox::clicked, this, &OptionsDialog::togglePruneWarning); connect(ui->pruneSize, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this, &OptionsDialog::showRestartWarning); connect(ui->databaseCache, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this, &OptionsDialog::showRestartWarning); connect(ui->threadsScriptVerif, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this, &OptionsDialog::showRestartWarning); /* Wallet */ connect(ui->spendZeroConfChange, &QCheckBox::clicked, this, &OptionsDialog::showRestartWarning); /* Network */ connect(ui->allowIncoming, &QCheckBox::clicked, this, &OptionsDialog::showRestartWarning); connect(ui->connectSocks, &QCheckBox::clicked, this, &OptionsDialog::showRestartWarning); connect(ui->connectSocksTor, &QCheckBox::clicked, this, &OptionsDialog::showRestartWarning); /* Display */ connect( ui->lang, static_cast<void (QValueComboBox::*)()>(&QValueComboBox::valueChanged), [this] { showRestartWarning(); }); connect(ui->thirdPartyTxUrls, &QLineEdit::textChanged, [this] { showRestartWarning(); }); } void OptionsDialog::setCurrentTab(OptionsDialog::Tab tab) { QWidget *tab_widget = nullptr; if (tab == OptionsDialog::Tab::TAB_NETWORK) { tab_widget = ui->tabNetwork; } if (tab == OptionsDialog::Tab::TAB_MAIN) { tab_widget = ui->tabMain; } if (tab_widget && ui->tabWidget->currentWidget() != tab_widget) { ui->tabWidget->setCurrentWidget(tab_widget); } } void OptionsDialog::setMapper() { /* Main */ mapper->addMapping(ui->bitcoinAtStartup, OptionsModel::StartAtStartup); mapper->addMapping(ui->threadsScriptVerif, OptionsModel::ThreadsScriptVerif); mapper->addMapping(ui->databaseCache, OptionsModel::DatabaseCache); mapper->addMapping(ui->prune, OptionsModel::Prune); mapper->addMapping(ui->pruneSize, OptionsModel::PruneSize); /* Wallet */ mapper->addMapping(ui->spendZeroConfChange, OptionsModel::SpendZeroConfChange); mapper->addMapping(ui->coinControlFeatures, OptionsModel::CoinControlFeatures); /* Network */ mapper->addMapping(ui->mapPortUpnp, OptionsModel::MapPortUPnP); mapper->addMapping(ui->allowIncoming, OptionsModel::Listen); mapper->addMapping(ui->connectSocks, OptionsModel::ProxyUse); mapper->addMapping(ui->proxyIp, OptionsModel::ProxyIP); mapper->addMapping(ui->proxyPort, OptionsModel::ProxyPort); mapper->addMapping(ui->connectSocksTor, OptionsModel::ProxyUseTor); mapper->addMapping(ui->proxyIpTor, OptionsModel::ProxyIPTor); mapper->addMapping(ui->proxyPortTor, OptionsModel::ProxyPortTor); /* Window */ #ifndef Q_OS_MAC if (QSystemTrayIcon::isSystemTrayAvailable()) { mapper->addMapping(ui->hideTrayIcon, OptionsModel::HideTrayIcon); mapper->addMapping(ui->minimizeToTray, OptionsModel::MinimizeToTray); } mapper->addMapping(ui->minimizeOnClose, OptionsModel::MinimizeOnClose); #endif /* Display */ mapper->addMapping(ui->lang, OptionsModel::Language); mapper->addMapping(ui->unit, OptionsModel::DisplayUnit); mapper->addMapping(ui->thirdPartyTxUrls, OptionsModel::ThirdPartyTxUrls); } void OptionsDialog::setOkButtonState(bool fState) { ui->okButton->setEnabled(fState); } void OptionsDialog::on_resetButton_clicked() { if (model) { // confirmation dialog QMessageBox::StandardButton btnRetVal = QMessageBox::question( this, tr("Confirm options reset"), tr("Client restart required to activate changes.") + "<br><br>" + tr("Client will be shut down. Do you want to proceed?"), QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel); if (btnRetVal == QMessageBox::Cancel) { return; } /* reset all options and close GUI */ model->Reset(); QApplication::quit(); } } void OptionsDialog::on_openBitcoinConfButton_clicked() { /* explain the purpose of the config file */ QMessageBox::information( this, tr("Configuration options"), tr("The configuration file is used to specify advanced user options " "which override GUI settings. Additionally, any command-line " "options will override this configuration file.")); /* show an error if there was some problem opening the file */ if (!GUIUtil::openBitcoinConf()) { QMessageBox::critical( this, tr("Error"), tr("The configuration file could not be opened.")); } } void OptionsDialog::on_okButton_clicked() { mapper->submit(); accept(); updateDefaultProxyNets(); } void OptionsDialog::on_cancelButton_clicked() { reject(); } void OptionsDialog::on_hideTrayIcon_stateChanged(int fState) { if (fState) { ui->minimizeToTray->setChecked(false); ui->minimizeToTray->setEnabled(false); } else { ui->minimizeToTray->setEnabled(true); } } void OptionsDialog::togglePruneWarning(bool enabled) { ui->pruneWarning->setVisible(!ui->pruneWarning->isVisible()); } void OptionsDialog::showRestartWarning(bool fPersistent) { ui->statusLabel->setStyleSheet("QLabel { color: red; }"); if (fPersistent) { ui->statusLabel->setText( tr("Client restart required to activate changes.")); } else { ui->statusLabel->setText( tr("This change would require a client restart.")); // clear non-persistent status label after 10 seconds // TODO: should perhaps be a class attribute, if we extend the use of // statusLabel QTimer::singleShot(10000, this, &OptionsDialog::clearStatusLabel); } } void OptionsDialog::clearStatusLabel() { ui->statusLabel->clear(); if (model && model->isRestartRequired()) { showRestartWarning(true); } } void OptionsDialog::updateProxyValidationState() { QValidatedLineEdit *pUiProxyIp = ui->proxyIp; QValidatedLineEdit *otherProxyWidget = (pUiProxyIp == ui->proxyIpTor) ? ui->proxyIp : ui->proxyIpTor; if (pUiProxyIp->isValid() && (!ui->proxyPort->isEnabled() || ui->proxyPort->text().toInt() > 0) && (!ui->proxyPortTor->isEnabled() || ui->proxyPortTor->text().toInt() > 0)) { // Only enable ok button if both proxys are valid setOkButtonState(otherProxyWidget->isValid()); clearStatusLabel(); } else { setOkButtonState(false); ui->statusLabel->setStyleSheet("QLabel { color: red; }"); ui->statusLabel->setText(tr("The supplied proxy address is invalid.")); } } void OptionsDialog::updateDefaultProxyNets() { proxyType proxy; std::string strProxy; QString strDefaultProxyGUI; model->node().getProxy(NET_IPV4, proxy); strProxy = proxy.proxy.ToStringIP() + ":" + proxy.proxy.ToStringPort(); strDefaultProxyGUI = ui->proxyIp->text() + ":" + ui->proxyPort->text(); (strProxy == strDefaultProxyGUI.toStdString()) ? ui->proxyReachIPv4->setChecked(true) : ui->proxyReachIPv4->setChecked(false); model->node().getProxy(NET_IPV6, proxy); strProxy = proxy.proxy.ToStringIP() + ":" + proxy.proxy.ToStringPort(); strDefaultProxyGUI = ui->proxyIp->text() + ":" + ui->proxyPort->text(); (strProxy == strDefaultProxyGUI.toStdString()) ? ui->proxyReachIPv6->setChecked(true) : ui->proxyReachIPv6->setChecked(false); model->node().getProxy(NET_ONION, proxy); strProxy = proxy.proxy.ToStringIP() + ":" + proxy.proxy.ToStringPort(); strDefaultProxyGUI = ui->proxyIp->text() + ":" + ui->proxyPort->text(); (strProxy == strDefaultProxyGUI.toStdString()) ? ui->proxyReachTor->setChecked(true) : ui->proxyReachTor->setChecked(false); } ProxyAddressValidator::ProxyAddressValidator(QObject *parent) : QValidator(parent) {} QValidator::State ProxyAddressValidator::validate(QString &input, int &pos) const { Q_UNUSED(pos); // Validate the proxy CService serv( LookupNumeric(input.toStdString().c_str(), DEFAULT_GUI_PROXY_PORT)); proxyType addrProxy = proxyType(serv, true); if (addrProxy.IsValid()) { return QValidator::Acceptable; } return QValidator::Invalid; } <commit_msg>ui: disable 3rd-party tx-urls when wallet disabled<commit_after>// Copyright (c) 2011-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include <config/bitcoin-config.h> #endif #include <qt/forms/ui_optionsdialog.h> #include <qt/optionsdialog.h> #include <interfaces/node.h> #include <netbase.h> #include <qt/bitcoinunits.h> #include <qt/guiconstants.h> #include <qt/guiutil.h> #include <qt/optionsmodel.h> #include <txdb.h> // for -dbcache defaults #include <validation.h> // for DEFAULT_SCRIPTCHECK_THREADS and MAX_SCRIPTCHECK_THREADS #include <QDataWidgetMapper> #include <QDir> #include <QIntValidator> #include <QLocale> #include <QMessageBox> #include <QSystemTrayIcon> #include <QTimer> OptionsDialog::OptionsDialog(QWidget *parent, bool enableWallet) : QDialog(parent), ui(new Ui::OptionsDialog), model(nullptr), mapper(nullptr) { ui->setupUi(this); /* Main elements init */ ui->databaseCache->setMinimum(nMinDbCache); ui->databaseCache->setMaximum(nMaxDbCache); ui->threadsScriptVerif->setMinimum(-GetNumCores()); ui->threadsScriptVerif->setMaximum(MAX_SCRIPTCHECK_THREADS); ui->pruneWarning->setVisible(false); ui->pruneWarning->setStyleSheet("QLabel { color: red; }"); ui->pruneSize->setEnabled(false); connect(ui->prune, &QPushButton::toggled, ui->pruneSize, &QWidget::setEnabled); /* Network elements init */ #ifndef USE_UPNP ui->mapPortUpnp->setEnabled(false); #endif ui->proxyIp->setEnabled(false); ui->proxyPort->setEnabled(false); ui->proxyPort->setValidator(new QIntValidator(1, 65535, this)); ui->proxyIpTor->setEnabled(false); ui->proxyPortTor->setEnabled(false); ui->proxyPortTor->setValidator(new QIntValidator(1, 65535, this)); connect(ui->connectSocks, &QPushButton::toggled, ui->proxyIp, &QWidget::setEnabled); connect(ui->connectSocks, &QPushButton::toggled, ui->proxyPort, &QWidget::setEnabled); connect(ui->connectSocks, &QPushButton::toggled, this, &OptionsDialog::updateProxyValidationState); connect(ui->connectSocksTor, &QPushButton::toggled, ui->proxyIpTor, &QWidget::setEnabled); connect(ui->connectSocksTor, &QPushButton::toggled, ui->proxyPortTor, &QWidget::setEnabled); connect(ui->connectSocksTor, &QPushButton::toggled, this, &OptionsDialog::updateProxyValidationState); /* Window elements init */ #ifdef Q_OS_MAC /* remove Window tab on Mac */ ui->tabWidget->removeTab(ui->tabWidget->indexOf(ui->tabWindow)); /* hide launch at startup option on macOS */ ui->bitcoinAtStartup->setVisible(false); ui->verticalLayout_Main->removeWidget(ui->bitcoinAtStartup); ui->verticalLayout_Main->removeItem(ui->horizontalSpacer_0_Main); #endif /* remove Wallet tab and 3rd party-URL textbox in case of -disablewallet */ if (!enableWallet) { ui->tabWidget->removeTab(ui->tabWidget->indexOf(ui->tabWallet)); ui->thirdPartyTxUrlsLabel->setVisible(false); ui->thirdPartyTxUrls->setVisible(false); } /* Display elements init */ QDir translations(":translations"); ui->bitcoinAtStartup->setToolTip( ui->bitcoinAtStartup->toolTip().arg(PACKAGE_NAME)); ui->bitcoinAtStartup->setText( ui->bitcoinAtStartup->text().arg(PACKAGE_NAME)); ui->openBitcoinConfButton->setToolTip( ui->openBitcoinConfButton->toolTip().arg(PACKAGE_NAME)); ui->lang->setToolTip(ui->lang->toolTip().arg(PACKAGE_NAME)); ui->lang->addItem(QString("(") + tr("default") + QString(")"), QVariant("")); for (const QString &langStr : translations.entryList()) { QLocale locale(langStr); /** check if the locale name consists of 2 parts (language_country) */ if (langStr.contains("_")) { /** display language strings as "native language - native country * (locale name)", e.g. "Deutsch - Deutschland (de)" */ ui->lang->addItem(locale.nativeLanguageName() + QString(" - ") + locale.nativeCountryName() + QString(" (") + langStr + QString(")"), QVariant(langStr)); } else { /** display language strings as "native language (locale name)", * e.g. "Deutsch (de)" */ ui->lang->addItem(locale.nativeLanguageName() + QString(" (") + langStr + QString(")"), QVariant(langStr)); } } ui->unit->setModel(new BitcoinUnits(this)); /* Widget-to-option mapper */ mapper = new QDataWidgetMapper(this); mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit); mapper->setOrientation(Qt::Vertical); GUIUtil::ItemDelegate *delegate = new GUIUtil::ItemDelegate(mapper); connect(delegate, &GUIUtil::ItemDelegate::keyEscapePressed, this, &OptionsDialog::reject); mapper->setItemDelegate(delegate); /* setup/change UI elements when proxy IPs are invalid/valid */ ui->proxyIp->setCheckValidator(new ProxyAddressValidator(parent)); ui->proxyIpTor->setCheckValidator(new ProxyAddressValidator(parent)); connect(ui->proxyIp, &QValidatedLineEdit::validationDidChange, this, &OptionsDialog::updateProxyValidationState); connect(ui->proxyIpTor, &QValidatedLineEdit::validationDidChange, this, &OptionsDialog::updateProxyValidationState); connect(ui->proxyPort, &QLineEdit::textChanged, this, &OptionsDialog::updateProxyValidationState); connect(ui->proxyPortTor, &QLineEdit::textChanged, this, &OptionsDialog::updateProxyValidationState); if (!QSystemTrayIcon::isSystemTrayAvailable()) { ui->hideTrayIcon->setChecked(true); ui->hideTrayIcon->setEnabled(false); ui->minimizeToTray->setChecked(false); ui->minimizeToTray->setEnabled(false); } } OptionsDialog::~OptionsDialog() { delete ui; } void OptionsDialog::setModel(OptionsModel *_model) { this->model = _model; if (_model) { /* check if client restart is needed and show persistent message */ if (_model->isRestartRequired()) { showRestartWarning(true); } // Prune values are in GB to be consistent with intro.cpp static constexpr uint64_t nMinDiskSpace = (MIN_DISK_SPACE_FOR_BLOCK_FILES / GB_BYTES) + (MIN_DISK_SPACE_FOR_BLOCK_FILES % GB_BYTES) ? 1 : 0; ui->pruneSize->setRange(nMinDiskSpace, std::numeric_limits<int>::max()); QString strLabel = _model->getOverriddenByCommandLine(); if (strLabel.isEmpty()) { strLabel = tr("none"); } ui->overriddenByCommandLineLabel->setText(strLabel); mapper->setModel(_model); setMapper(); mapper->toFirst(); updateDefaultProxyNets(); } /* warn when one of the following settings changes by user action (placed * here so init via mapper doesn't trigger them) */ /* Main */ connect(ui->prune, &QCheckBox::clicked, this, &OptionsDialog::showRestartWarning); connect(ui->prune, &QCheckBox::clicked, this, &OptionsDialog::togglePruneWarning); connect(ui->pruneSize, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this, &OptionsDialog::showRestartWarning); connect(ui->databaseCache, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this, &OptionsDialog::showRestartWarning); connect(ui->threadsScriptVerif, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this, &OptionsDialog::showRestartWarning); /* Wallet */ connect(ui->spendZeroConfChange, &QCheckBox::clicked, this, &OptionsDialog::showRestartWarning); /* Network */ connect(ui->allowIncoming, &QCheckBox::clicked, this, &OptionsDialog::showRestartWarning); connect(ui->connectSocks, &QCheckBox::clicked, this, &OptionsDialog::showRestartWarning); connect(ui->connectSocksTor, &QCheckBox::clicked, this, &OptionsDialog::showRestartWarning); /* Display */ connect( ui->lang, static_cast<void (QValueComboBox::*)()>(&QValueComboBox::valueChanged), [this] { showRestartWarning(); }); connect(ui->thirdPartyTxUrls, &QLineEdit::textChanged, [this] { showRestartWarning(); }); } void OptionsDialog::setCurrentTab(OptionsDialog::Tab tab) { QWidget *tab_widget = nullptr; if (tab == OptionsDialog::Tab::TAB_NETWORK) { tab_widget = ui->tabNetwork; } if (tab == OptionsDialog::Tab::TAB_MAIN) { tab_widget = ui->tabMain; } if (tab_widget && ui->tabWidget->currentWidget() != tab_widget) { ui->tabWidget->setCurrentWidget(tab_widget); } } void OptionsDialog::setMapper() { /* Main */ mapper->addMapping(ui->bitcoinAtStartup, OptionsModel::StartAtStartup); mapper->addMapping(ui->threadsScriptVerif, OptionsModel::ThreadsScriptVerif); mapper->addMapping(ui->databaseCache, OptionsModel::DatabaseCache); mapper->addMapping(ui->prune, OptionsModel::Prune); mapper->addMapping(ui->pruneSize, OptionsModel::PruneSize); /* Wallet */ mapper->addMapping(ui->spendZeroConfChange, OptionsModel::SpendZeroConfChange); mapper->addMapping(ui->coinControlFeatures, OptionsModel::CoinControlFeatures); /* Network */ mapper->addMapping(ui->mapPortUpnp, OptionsModel::MapPortUPnP); mapper->addMapping(ui->allowIncoming, OptionsModel::Listen); mapper->addMapping(ui->connectSocks, OptionsModel::ProxyUse); mapper->addMapping(ui->proxyIp, OptionsModel::ProxyIP); mapper->addMapping(ui->proxyPort, OptionsModel::ProxyPort); mapper->addMapping(ui->connectSocksTor, OptionsModel::ProxyUseTor); mapper->addMapping(ui->proxyIpTor, OptionsModel::ProxyIPTor); mapper->addMapping(ui->proxyPortTor, OptionsModel::ProxyPortTor); /* Window */ #ifndef Q_OS_MAC if (QSystemTrayIcon::isSystemTrayAvailable()) { mapper->addMapping(ui->hideTrayIcon, OptionsModel::HideTrayIcon); mapper->addMapping(ui->minimizeToTray, OptionsModel::MinimizeToTray); } mapper->addMapping(ui->minimizeOnClose, OptionsModel::MinimizeOnClose); #endif /* Display */ mapper->addMapping(ui->lang, OptionsModel::Language); mapper->addMapping(ui->unit, OptionsModel::DisplayUnit); mapper->addMapping(ui->thirdPartyTxUrls, OptionsModel::ThirdPartyTxUrls); } void OptionsDialog::setOkButtonState(bool fState) { ui->okButton->setEnabled(fState); } void OptionsDialog::on_resetButton_clicked() { if (model) { // confirmation dialog QMessageBox::StandardButton btnRetVal = QMessageBox::question( this, tr("Confirm options reset"), tr("Client restart required to activate changes.") + "<br><br>" + tr("Client will be shut down. Do you want to proceed?"), QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel); if (btnRetVal == QMessageBox::Cancel) { return; } /* reset all options and close GUI */ model->Reset(); QApplication::quit(); } } void OptionsDialog::on_openBitcoinConfButton_clicked() { /* explain the purpose of the config file */ QMessageBox::information( this, tr("Configuration options"), tr("The configuration file is used to specify advanced user options " "which override GUI settings. Additionally, any command-line " "options will override this configuration file.")); /* show an error if there was some problem opening the file */ if (!GUIUtil::openBitcoinConf()) { QMessageBox::critical( this, tr("Error"), tr("The configuration file could not be opened.")); } } void OptionsDialog::on_okButton_clicked() { mapper->submit(); accept(); updateDefaultProxyNets(); } void OptionsDialog::on_cancelButton_clicked() { reject(); } void OptionsDialog::on_hideTrayIcon_stateChanged(int fState) { if (fState) { ui->minimizeToTray->setChecked(false); ui->minimizeToTray->setEnabled(false); } else { ui->minimizeToTray->setEnabled(true); } } void OptionsDialog::togglePruneWarning(bool enabled) { ui->pruneWarning->setVisible(!ui->pruneWarning->isVisible()); } void OptionsDialog::showRestartWarning(bool fPersistent) { ui->statusLabel->setStyleSheet("QLabel { color: red; }"); if (fPersistent) { ui->statusLabel->setText( tr("Client restart required to activate changes.")); } else { ui->statusLabel->setText( tr("This change would require a client restart.")); // clear non-persistent status label after 10 seconds // TODO: should perhaps be a class attribute, if we extend the use of // statusLabel QTimer::singleShot(10000, this, &OptionsDialog::clearStatusLabel); } } void OptionsDialog::clearStatusLabel() { ui->statusLabel->clear(); if (model && model->isRestartRequired()) { showRestartWarning(true); } } void OptionsDialog::updateProxyValidationState() { QValidatedLineEdit *pUiProxyIp = ui->proxyIp; QValidatedLineEdit *otherProxyWidget = (pUiProxyIp == ui->proxyIpTor) ? ui->proxyIp : ui->proxyIpTor; if (pUiProxyIp->isValid() && (!ui->proxyPort->isEnabled() || ui->proxyPort->text().toInt() > 0) && (!ui->proxyPortTor->isEnabled() || ui->proxyPortTor->text().toInt() > 0)) { // Only enable ok button if both proxys are valid setOkButtonState(otherProxyWidget->isValid()); clearStatusLabel(); } else { setOkButtonState(false); ui->statusLabel->setStyleSheet("QLabel { color: red; }"); ui->statusLabel->setText(tr("The supplied proxy address is invalid.")); } } void OptionsDialog::updateDefaultProxyNets() { proxyType proxy; std::string strProxy; QString strDefaultProxyGUI; model->node().getProxy(NET_IPV4, proxy); strProxy = proxy.proxy.ToStringIP() + ":" + proxy.proxy.ToStringPort(); strDefaultProxyGUI = ui->proxyIp->text() + ":" + ui->proxyPort->text(); (strProxy == strDefaultProxyGUI.toStdString()) ? ui->proxyReachIPv4->setChecked(true) : ui->proxyReachIPv4->setChecked(false); model->node().getProxy(NET_IPV6, proxy); strProxy = proxy.proxy.ToStringIP() + ":" + proxy.proxy.ToStringPort(); strDefaultProxyGUI = ui->proxyIp->text() + ":" + ui->proxyPort->text(); (strProxy == strDefaultProxyGUI.toStdString()) ? ui->proxyReachIPv6->setChecked(true) : ui->proxyReachIPv6->setChecked(false); model->node().getProxy(NET_ONION, proxy); strProxy = proxy.proxy.ToStringIP() + ":" + proxy.proxy.ToStringPort(); strDefaultProxyGUI = ui->proxyIp->text() + ":" + ui->proxyPort->text(); (strProxy == strDefaultProxyGUI.toStdString()) ? ui->proxyReachTor->setChecked(true) : ui->proxyReachTor->setChecked(false); } ProxyAddressValidator::ProxyAddressValidator(QObject *parent) : QValidator(parent) {} QValidator::State ProxyAddressValidator::validate(QString &input, int &pos) const { Q_UNUSED(pos); // Validate the proxy CService serv( LookupNumeric(input.toStdString().c_str(), DEFAULT_GUI_PROXY_PORT)); proxyType addrProxy = proxyType(serv, true); if (addrProxy.IsValid()) { return QValidator::Acceptable; } return QValidator::Invalid; } <|endoftext|>
<commit_before>#include "rotocoinunits.h" #include <QStringList> RotocoinUnits::RotocoinUnits(QObject *parent): QAbstractListModel(parent), unitlist(availableUnits()) { } QList<RotocoinUnits::Unit> RotocoinUnits::availableUnits() { QList<RotocoinUnits::Unit> unitlist; unitlist.append(Rt2); unitlist.append(mRt2); unitlist.append(uRt2); unitlist.append(ilitris); return unitlist; } bool RotocoinUnits::valid(int unit) { switch(unit) { case Rt2: case mRt2: case uRt2: case ilitris: return true; default: return false; } } QString RotocoinUnits::name(int unit) { switch(unit) { case Rt2: return QString("Rt2"); case mRt2: return QString("mRt2"); case uRt2: return QString::fromUtf8("μRt2"); case ilitris: return QString::fromUtf8("ilitris"); default: return QString("???"); } } QString RotocoinUnits::description(int unit) { switch(unit) { case Rt2: return QString("Rotocoins"); case mRt2: return QString("Milli-Rotocoins (0.001 Rt2)"); // ( 1 / 1,000 ) case uRt2: return QString("Micro-Rotocoins (0.000001 Rt2)"); // ( 1 / 1,000,000 ) case ilitris: return QString("ilitris (0.00000001 Rt2)"); // ( 1 / 100,000,000 ) default: return QString("???"); } } qint64 RotocoinUnits::factor(int unit) { switch(unit) { case Rt2: return 100000000; case mRt2: return 100000; case uRt2: return 100; case ilitris: return 1; default: return 100000000; } } int RotocoinUnits::amountDigits(int unit) { switch(unit) { case Rt2: return 6; // 288,000 (# digits, without commas) case mRt2: return 9; // 288,000,000 case uRt2: return 12; // 288,000,000,000 case ilitris: return 14; // 28,800,000,000,000 default: return 0; } } int RotocoinUnits::decimals(int unit) { switch(unit) { case Rt2: return 8; case mRt2: return 5; case uRt2: return 2; case ilitris: return 0; default: return 0; } } QString RotocoinUnits::format(int unit, qint64 n, bool fPlus) { // Note: not using straight sprintf here because we do NOT want // localized number formatting. if(!valid(unit)) return QString(); // Refuse to format invalid unit qint64 coin = factor(unit); int num_decimals = decimals(unit); qint64 n_abs = (n > 0 ? n : -n); qint64 quotient = n_abs / coin; qint64 remainder = n_abs % coin; QString quotient_str = QString::number(quotient); QString remainder_str = QString::number(remainder).rightJustified(num_decimals, '0'); // Right-trim excess zeros after the decimal point int nTrim = 0; for (int i = remainder_str.size()-1; i>=2 && (remainder_str.at(i) == '0'); --i) ++nTrim; remainder_str.chop(nTrim); if (n < 0) quotient_str.insert(0, '-'); else if (fPlus && n > 0) quotient_str.insert(0, '+'); if (unit != ilitris) return quotient_str + QString(".") + remainder_str; else return quotient_str; } QString RotocoinUnits::formatWithUnit(int unit, qint64 amount, bool plussign) { return format(unit, amount, plussign) + QString(" ") + name(unit); } bool RotocoinUnits::parse(int unit, const QString &value, qint64 *val_out) { if(!valid(unit) || value.isEmpty()) return false; // Refuse to parse invalid unit or empty string int num_decimals = decimals(unit); QStringList parts = value.split("."); if(parts.size() > 2) { return false; // More than one dot } QString whole = parts[0]; QString decimals; if(parts.size() > 1) { decimals = parts[1]; } if(decimals.size() > num_decimals) { return false; // Exceeds max precision } bool ok = false; QString str = whole + decimals.leftJustified(num_decimals, '0'); if(str.size() > 18) { return false; // Longer numbers will exceed 63 bits } qint64 retvalue = str.toLongLong(&ok); if(val_out) { *val_out = retvalue; } return ok; } int RotocoinUnits::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent); return unitlist.size(); } QVariant RotocoinUnits::data(const QModelIndex &index, int role) const { int row = index.row(); if(row >= 0 && row < unitlist.size()) { Unit unit = unitlist.at(row); switch(role) { case Qt::EditRole: case Qt::DisplayRole: return QVariant(name(unit)); case Qt::ToolTipRole: return QVariant(description(unit)); case UnitRole: return QVariant(static_cast<int>(unit)); } } return QVariant(); } <commit_msg>prettify units displaying<commit_after>#include "rotocoinunits.h" #include <QStringList> RotocoinUnits::RotocoinUnits(QObject *parent): QAbstractListModel(parent), unitlist(availableUnits()) { } QList<RotocoinUnits::Unit> RotocoinUnits::availableUnits() { QList<RotocoinUnits::Unit> unitlist; unitlist.append(Rt2); unitlist.append(mRt2); unitlist.append(uRt2); unitlist.append(ilitris); return unitlist; } bool RotocoinUnits::valid(int unit) { switch(unit) { case Rt2: case mRt2: case uRt2: case ilitris: return true; default: return false; } } QString RotocoinUnits::name(int unit) { switch(unit) { case Rt2: return QString("Rt2"); case mRt2: return QString("mRt2"); case uRt2: return QString::fromUtf8("μRt2"); case ilitris: return QString::fromUtf8("ilitris"); default: return QString("???"); } } QString RotocoinUnits::description(int unit) { switch(unit) { case Rt2: return QString("Rotocoins"); case mRt2: return QString("Milli-Rotocoins (0.001 Rt2)"); // ( 1 / 1,000 ) case uRt2: return QString("Micro-Rotocoins (0.000001 Rt2)"); // ( 1 / 1,000,000 ) case ilitris: return QString("ilitris (0.00000001 Rt2)"); // ( 1 / 100,000,000 ) default: return QString("???"); } } qint64 RotocoinUnits::factor(int unit) { switch(unit) { case Rt2: return 100000000; case mRt2: return 100000; case uRt2: return 100; case ilitris: return 1; default: return 100000000; } } int RotocoinUnits::amountDigits(int unit) { switch(unit) { case Rt2: return 6; // 288,000 (# digits, without commas) case mRt2: return 9; // 288,000,000 case uRt2: return 12; // 288,000,000,000 case ilitris: return 14; // 28,800,000,000,000 default: return 0; } } int RotocoinUnits::decimals(int unit) { switch(unit) { case Rt2: return 8; case mRt2: return 5; case uRt2: return 2; case ilitris: return 0; default: return 0; } } QString RotocoinUnits::format(int unit, qint64 n, bool fPlus) { // Note: not using straight sprintf here because we do NOT want // localized number formatting. if(!valid(unit)) return QString(); // Refuse to format invalid unit qint64 coin = factor(unit); int num_decimals = decimals(unit); qint64 n_abs = (n > 0 ? n : -n); qint64 quotient = n_abs / coin; qint64 remainder = n_abs % coin; QString quotient_str = QString::number(quotient); // Dirty hack - TODO: prettify int qnum = quotient_str.size(); for (int i = qnum; i>0 ; i=i-3) quotient_str.insert(i, " "); QString remainder_str = QString::number(remainder).rightJustified(num_decimals, '0'); // Right-trim excess zeros after the decimal point int nTrim = 0; for (int i = remainder_str.size()-1; i>=2 && (remainder_str.at(i) == '0'); --i) ++nTrim; remainder_str.chop(nTrim); if (n < 0) quotient_str.insert(0, '-'); else if (fPlus && n > 0) quotient_str.insert(0, '+'); if (unit != ilitris) return quotient_str + QString(".") + remainder_str; else return quotient_str; } QString RotocoinUnits::formatWithUnit(int unit, qint64 amount, bool plussign) { return format(unit, amount, plussign) + QString(" ") + name(unit); } bool RotocoinUnits::parse(int unit, const QString &value, qint64 *val_out) { if(!valid(unit) || value.isEmpty()) return false; // Refuse to parse invalid unit or empty string int num_decimals = decimals(unit); QStringList parts = value.split("."); if(parts.size() > 2) { return false; // More than one dot } QString whole = parts[0]; QString decimals; if(parts.size() > 1) { decimals = parts[1]; } if(decimals.size() > num_decimals) { return false; // Exceeds max precision } bool ok = false; QString str = whole + decimals.leftJustified(num_decimals, '0'); if(str.size() > 18) { return false; // Longer numbers will exceed 63 bits } qint64 retvalue = str.toLongLong(&ok); if(val_out) { *val_out = retvalue; } return ok; } int RotocoinUnits::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent); return unitlist.size(); } QVariant RotocoinUnits::data(const QModelIndex &index, int role) const { int row = index.row(); if(row >= 0 && row < unitlist.size()) { Unit unit = unitlist.at(row); switch(role) { case Qt::EditRole: case Qt::DisplayRole: return QVariant(name(unit)); case Qt::ToolTipRole: return QVariant(description(unit)); case UnitRole: return QVariant(static_cast<int>(unit)); } } return QVariant(); } <|endoftext|>
<commit_before>/////////////////////////////////////////////////////////////////////////////// // // File FilterEnergy.cpp // // For more information, please see: http://www.nektar.info // // The MIT License // // Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA), // Department of Aeronautics, Imperial College London (UK), and Scientific // Computing and Imaging Institute, University of Utah (USA). // // License for the specific language governing rights and limitations under // 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. // // Description: Output kinetic energy and enstrophy. // /////////////////////////////////////////////////////////////////////////////// #include <iomanip> #include <SolverUtils/Filters/FilterEnergy.h> namespace Nektar { namespace SolverUtils { std::string FilterEnergy::className = GetFilterFactory(). RegisterCreatorFunction("Energy", FilterEnergy::create); FilterEnergy::FilterEnergy( const LibUtilities::SessionReaderSharedPtr &pSession, const std::map<std::string, std::string> &pParams) : Filter(pSession), m_planes(), m_index(0), m_homogeneous(false) { std::string outName; if (pParams.find("OutputFile") == pParams.end()) { outName = m_session->GetSessionName(); } else { ASSERTL0(!(pParams.find("OutputFile")->second.empty()), "Missing parameter 'OutputFile'."); outName = pParams.find("OutputFile")->second; } m_comm = pSession->GetComm(); outName += ".eny"; if (m_comm->GetRank() == 0) { m_outFile.open(outName.c_str()); ASSERTL0(m_outFile.good(), "Unable to open: '" + outName + "'"); } ASSERTL0(pParams.find("OutputFrequency") != pParams.end(), "Missing parameter 'OutputFrequency'."); m_outputFrequency = atoi(pParams.find("OutputFrequency")->second.c_str()); if (pSession->DefinesSolverInfo("HOMOGENEOUS")) { std::string HomoStr = m_session->GetSolverInfo("HOMOGENEOUS"); if (HomoStr == "HOMOGENEOUS1D" || HomoStr == "Homogeneous1D" || HomoStr == "1D" || HomoStr == "Homo1D") { m_homogeneous = true; pSession->LoadParameter("LZ", m_homogeneousLength); } else { ASSERTL0(false, "The energy filter only supports 1D " "homogeneous expansions."); } } } FilterEnergy::~FilterEnergy() { } void FilterEnergy::v_Initialise( const Array<OneD, const MultiRegions::ExpListSharedPtr> &pFields, const NekDouble &time) { m_index = 0; MultiRegions::ExpListSharedPtr areaField; // Calculate area/volume of domain. if (m_homogeneous) { m_planes = pFields[0]->GetZIDs(); areaField = pFields[0]->GetPlane(0); } else { areaField = pFields[0]; } Array<OneD, NekDouble> inarray(areaField->GetNpoints(), 1.0); m_area = areaField->Integral(inarray); if (m_homogeneous) { m_area *= m_homogeneousLength; } v_Update(pFields, time); } void FilterEnergy::v_Update( const Array<OneD, const MultiRegions::ExpListSharedPtr> &pFields, const NekDouble &time) { int i, n, nPoints = pFields[0]->GetNpoints(), nPlanePts = 0; if (m_homogeneous) { nPlanePts = pFields[0]->GetPlane(0)->GetNpoints(); } m_index++; if (m_index % m_outputFrequency > 0) { return; } // Calculate kinetic energy. NekDouble Ek = 0.0; Array<OneD, NekDouble> tmp(nPoints); Array<OneD, Array<OneD, NekDouble> > u(3); for (i = 0; i < 3; ++i) { if (m_homogeneous) { pFields[i]->HomogeneousBwdTrans(pFields[i]->GetPhys(), tmp); } u[i] = Array<OneD, NekDouble>(nPoints); Vmath::Vcopy(nPoints, tmp, 1, u[i], 1); Vmath::Vmul (nPoints, tmp, 1, tmp, 1, tmp, 1); if (m_homogeneous) { pFields[i]->HomogeneousFwdTrans(tmp, tmp); Ek += pFields[i]->GetPlane(0)->Integral(tmp) * 2.0 * M_PI; } else { Ek += pFields[i]->Integral(tmp); } } Ek /= 2.0*m_area; if (m_comm->GetRank() == 0) { m_outFile << setw(10) << time << setw(20) << Ek; } bool waveSpace[3] = { pFields[0]->GetWaveSpace(), pFields[1]->GetWaveSpace(), pFields[2]->GetWaveSpace() }; if (m_homogeneous) { for (i = 0; i < 3; ++i) { pFields[i]->SetWaveSpace(false); } } // First calculate vorticity field. Array<OneD, NekDouble> tmp2(nPoints), tmp3(nPoints); Vmath::Zero(nPoints, tmp, 1); for (i = 0; i < 3; ++i) { int f1 = (i+2) % 3, c2 = f1; int c1 = (i+1) % 3, f2 = c1; pFields[f1]->PhysDeriv(c1, u[f1], tmp2); pFields[f2]->PhysDeriv(c2, u[f2], tmp3); Vmath::Vsub (nPoints, tmp2, 1, tmp3, 1, tmp2, 1); Vmath::Vvtvp(nPoints, tmp2, 1, tmp2, 1, tmp, 1, tmp, 1); } if (m_homogeneous) { for (i = 0; i < 3; ++i) { pFields[i]->SetWaveSpace(waveSpace[i]); } pFields[0]->HomogeneousFwdTrans(tmp, tmp); Ek = pFields[0]->GetPlane(0)->Integral(tmp) * 2 * M_PI; } else { Ek = pFields[0]->Integral(tmp); } Ek /= 2.0*m_area; if (m_comm->GetRank() == 0) { m_outFile << setw(20) << Ek << endl; } } void FilterEnergy::v_Finalise( const Array<OneD, const MultiRegions::ExpListSharedPtr> &pFields, const NekDouble &time) { m_outFile.close(); } bool FilterEnergy::v_IsTimeDependent() { return true; } } } <commit_msg>Fix energy filter for full 3D simulation.<commit_after>/////////////////////////////////////////////////////////////////////////////// // // File FilterEnergy.cpp // // For more information, please see: http://www.nektar.info // // The MIT License // // Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA), // Department of Aeronautics, Imperial College London (UK), and Scientific // Computing and Imaging Institute, University of Utah (USA). // // License for the specific language governing rights and limitations under // 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. // // Description: Output kinetic energy and enstrophy. // /////////////////////////////////////////////////////////////////////////////// #include <iomanip> #include <SolverUtils/Filters/FilterEnergy.h> namespace Nektar { namespace SolverUtils { std::string FilterEnergy::className = GetFilterFactory(). RegisterCreatorFunction("Energy", FilterEnergy::create); FilterEnergy::FilterEnergy( const LibUtilities::SessionReaderSharedPtr &pSession, const std::map<std::string, std::string> &pParams) : Filter(pSession), m_planes(), m_index(0), m_homogeneous(false) { std::string outName; if (pParams.find("OutputFile") == pParams.end()) { outName = m_session->GetSessionName(); } else { ASSERTL0(!(pParams.find("OutputFile")->second.empty()), "Missing parameter 'OutputFile'."); outName = pParams.find("OutputFile")->second; } m_comm = pSession->GetComm(); outName += ".eny"; if (m_comm->GetRank() == 0) { m_outFile.open(outName.c_str()); ASSERTL0(m_outFile.good(), "Unable to open: '" + outName + "'"); } ASSERTL0(pParams.find("OutputFrequency") != pParams.end(), "Missing parameter 'OutputFrequency'."); m_outputFrequency = atoi(pParams.find("OutputFrequency")->second.c_str()); if (pSession->DefinesSolverInfo("HOMOGENEOUS")) { std::string HomoStr = m_session->GetSolverInfo("HOMOGENEOUS"); if (HomoStr == "HOMOGENEOUS1D" || HomoStr == "Homogeneous1D" || HomoStr == "1D" || HomoStr == "Homo1D") { m_homogeneous = true; pSession->LoadParameter("LZ", m_homogeneousLength); } else { ASSERTL0(false, "The energy filter only supports 1D " "homogeneous expansions."); } } } FilterEnergy::~FilterEnergy() { } void FilterEnergy::v_Initialise( const Array<OneD, const MultiRegions::ExpListSharedPtr> &pFields, const NekDouble &time) { m_index = 0; MultiRegions::ExpListSharedPtr areaField; // Calculate area/volume of domain. if (m_homogeneous) { m_planes = pFields[0]->GetZIDs(); areaField = pFields[0]->GetPlane(0); } else { areaField = pFields[0]; } Array<OneD, NekDouble> inarray(areaField->GetNpoints(), 1.0); m_area = areaField->Integral(inarray); if (m_homogeneous) { m_area *= m_homogeneousLength; } // Output values at initial time. v_Update(pFields, time); } void FilterEnergy::v_Update( const Array<OneD, const MultiRegions::ExpListSharedPtr> &pFields, const NekDouble &time) { int i, n, nPoints = pFields[0]->GetNpoints(), nPlanePts = 0; if (m_homogeneous) { nPlanePts = pFields[0]->GetPlane(0)->GetNpoints(); } m_index++; if (m_index % m_outputFrequency > 0) { return; } // Calculate kinetic energy. NekDouble Ek = 0.0; Array<OneD, NekDouble> tmp(nPoints); Array<OneD, Array<OneD, NekDouble> > u(3); for (i = 0; i < 3; ++i) { if (m_homogeneous) { pFields[i]->HomogeneousBwdTrans(pFields[i]->GetPhys(), tmp); } else { tmp = pFields[i]->GetPhys(); } u[i] = Array<OneD, NekDouble>(nPoints); Vmath::Vcopy(nPoints, tmp, 1, u[i], 1); Vmath::Vmul (nPoints, tmp, 1, tmp, 1, tmp, 1); if (m_homogeneous) { pFields[i]->HomogeneousFwdTrans(tmp, tmp); Ek += pFields[i]->GetPlane(0)->Integral(tmp) * 2.0 * M_PI; } else { Ek += pFields[i]->Integral(tmp); } } Ek /= 2.0*m_area; if (m_comm->GetRank() == 0) { m_outFile << setw(10) << time << setw(20) << Ek; } bool waveSpace[3] = { pFields[0]->GetWaveSpace(), pFields[1]->GetWaveSpace(), pFields[2]->GetWaveSpace() }; if (m_homogeneous) { for (i = 0; i < 3; ++i) { pFields[i]->SetWaveSpace(false); } } // First calculate vorticity field. Array<OneD, NekDouble> tmp2(nPoints), tmp3(nPoints); Vmath::Zero(nPoints, tmp, 1); for (i = 0; i < 3; ++i) { int f1 = (i+2) % 3, c2 = f1; int c1 = (i+1) % 3, f2 = c1; pFields[f1]->PhysDeriv(c1, u[f1], tmp2); pFields[f2]->PhysDeriv(c2, u[f2], tmp3); Vmath::Vsub (nPoints, tmp2, 1, tmp3, 1, tmp2, 1); Vmath::Vvtvp(nPoints, tmp2, 1, tmp2, 1, tmp, 1, tmp, 1); } if (m_homogeneous) { for (i = 0; i < 3; ++i) { pFields[i]->SetWaveSpace(waveSpace[i]); } pFields[0]->HomogeneousFwdTrans(tmp, tmp); Ek = pFields[0]->GetPlane(0)->Integral(tmp) * 2 * M_PI; } else { Ek = pFields[0]->Integral(tmp); } Ek /= 2.0*m_area; if (m_comm->GetRank() == 0) { m_outFile << setw(20) << Ek << endl; } } void FilterEnergy::v_Finalise( const Array<OneD, const MultiRegions::ExpListSharedPtr> &pFields, const NekDouble &time) { m_outFile.close(); } bool FilterEnergy::v_IsTimeDependent() { return true; } } } <|endoftext|>
<commit_before>/* This is free and unencumbered software released into the public domain. */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include "rdf++/reader/trix.h" #include "rdf++/quad.h" #include "rdf++/term.h" #include "rdf++/triple.h" #include "xml_reader.h" #include <memory> /* for std::unique_ptr */ #include <cstring> /* for std::strcmp() */ namespace { enum class trix_element { unknown = 0, trix, graph, triple, id, uri, plain_literal, typed_literal, }; enum class trix_state {start, document, graph, triple, eof, abort}; struct trix_context { trix_state state = trix_state::start; trix_element element = trix_element::unknown; unsigned int term_pos = 0; std::unique_ptr<rdf::term> terms[3] = {nullptr, nullptr, nullptr}; std::unique_ptr<rdf::uri_reference> graph = nullptr; std::function<void (rdf::triple*)> triple_callback = nullptr; std::function<void (rdf::quad*)> quad_callback = nullptr; }; struct implementation : public rdf::reader::implementation { implementation(FILE* stream, const char* content_type, const char* charset, const char* base_uri); virtual ~implementation() noexcept override; virtual void read_triples(std::function<void (rdf::triple*)> callback) override; virtual void read_quads(std::function<void (rdf::quad*)> callback) override; virtual void abort() override; protected: void read_with_context(trix_context& context); void ensure_state(trix_context& context, trix_state state); void assert_state(trix_context& context, trix_state state); void enter_state(trix_context& context, trix_state state); void leave_state(trix_context& context, trix_state state); void change_state(trix_context& context, trix_state state); void ensure_depth(trix_context& context, unsigned int depth); void record_term(trix_context& context); void begin_element(trix_context& context); void finish_element(trix_context& context); rdf::term* construct_term(trix_context& context); void throw_error(trix_context& context, const char* what); private: xml_reader _reader; }; } rdf::reader::implementation* rdf_reader_for_trix(FILE* const stream, const char* const content_type, const char* const charset, const char* const base_uri) { return new implementation(stream, content_type, charset, base_uri); } implementation::implementation(FILE* const stream, const char* const content_type, const char* const charset, const char* const base_uri) : _reader(stream, base_uri, charset) { assert(stream != nullptr); (void)content_type; } implementation::~implementation() noexcept = default; static trix_element intern_trix_element(const char* const element_name) { switch (*element_name) { case 'T': if (std::strcmp(element_name, "TriX") == 0 || std::strcmp(element_name, "trix") == 0) { return trix_element::trix; } break; case 'g': if (std::strcmp(element_name, "graph") == 0) { return trix_element::graph; } break; case 't': if (std::strcmp(element_name, "triple") == 0) { return trix_element::triple; } if (std::strcmp(element_name, "typedLiteral") == 0) { return trix_element::typed_literal; } break; case 'i': if (std::strcmp(element_name, "id") == 0) { return trix_element::id; } break; case 'u': if (std::strcmp(element_name, "uri") == 0) { return trix_element::uri; } break; case 'p': if (std::strcmp(element_name, "plainLiteral") == 0) { return trix_element::plain_literal; } break; default: break; } return trix_element::unknown; } void implementation::read_triples(std::function<void (rdf::triple*)> callback) { trix_context context; context.triple_callback = callback; read_with_context(context); } void implementation::read_quads(std::function<void (rdf::quad*)> callback) { trix_context context; context.quad_callback = callback; read_with_context(context); } void implementation::abort() { // TODO } void implementation::read_with_context(trix_context& context) { while (_reader.read()) { switch (_reader.node_type()) { case xml_node_type::element: begin_element(context); break; case xml_node_type::end_element: finish_element(context); break; default: /* ignored */ break; } } } void implementation::ensure_state(trix_context& context, const trix_state state) { if (context.state != state) { throw_error(context, "mismatched nesting of elements in TriX input"); } } void implementation::assert_state(trix_context& context, const trix_state state) { (void)state, (void)context; assert(context.state == state); } void implementation::enter_state(trix_context& context, const trix_state state) { switch (state) { case trix_state::graph: context.graph.reset(); break; case trix_state::triple: context.term_pos = 0; break; default: break; } } void implementation::leave_state(trix_context& context, const trix_state state) { switch (state) { case trix_state::triple: if (context.quad_callback) { auto quad = new rdf::quad( context.terms[0].get(), context.terms[1].get(), context.terms[2].get(), context.graph ? (context.graph)->clone() : nullptr); context.quad_callback(quad); } else if (context.triple_callback) { auto triple = new rdf::triple( context.terms[0].get(), context.terms[1].get(), context.terms[2].get()); context.triple_callback(triple); } for (auto i = 0U; i < 3; i++) { if (context.quad_callback || context.triple_callback) { /* The callback took ownership of the terms: */ context.terms[i].release(); } else { context.terms[i].reset(); } } context.term_pos = 0; break; default: break; } } void implementation::change_state(trix_context& context, const trix_state state) { leave_state(context, context.state); context.state = state; enter_state(context, context.state); } void implementation::ensure_depth(trix_context& context, const unsigned int depth) { if (_reader.depth() != depth) { throw_error(context, "incorrect nesting of elements in TriX input"); } } void implementation::record_term(trix_context& context) { if (context.term_pos >= 3) { throw_error(context, "too many elements inside <triple> element"); } context.terms[context.term_pos].reset(construct_term(context)); context.term_pos++; } void implementation::begin_element(trix_context& context) { context.element = intern_trix_element(_reader.name()); switch (context.element) { case trix_element::trix: ensure_state(context, trix_state::start); ensure_depth(context, 0); change_state(context, trix_state::document); break; case trix_element::graph: ensure_state(context, trix_state::document); ensure_depth(context, 1); change_state(context, trix_state::graph); break; case trix_element::triple: ensure_state(context, trix_state::graph); ensure_depth(context, 2); change_state(context, trix_state::triple); break; case trix_element::uri: if (context.state == trix_state::graph) { ensure_depth(context, 2); if (context.graph) { throw_error(context, "repeated <uri> element inside <graph> element"); } context.graph.reset(new rdf::uri_reference(_reader.read_string())); break; } ensure_state(context, trix_state::triple); ensure_depth(context, 3); record_term(context); break; case trix_element::id: case trix_element::plain_literal: case trix_element::typed_literal: ensure_state(context, trix_state::triple); ensure_depth(context, 3); record_term(context); break; default: throw_error(context, "unknown XML element in TriX input"); } } void implementation::finish_element(trix_context& context) { context.element = intern_trix_element(_reader.name()); switch (context.element) { case trix_element::trix: assert_state(context, trix_state::document); change_state(context, trix_state::eof); break; case trix_element::graph: assert_state(context, trix_state::graph); change_state(context, trix_state::document); break; case trix_element::triple: assert_state(context, trix_state::triple); change_state(context, trix_state::graph); break; case trix_element::uri: //assert_state(trix_state::triple, context); // FIXME: triple | graph break; case trix_element::id: case trix_element::plain_literal: case trix_element::typed_literal: assert_state(context, trix_state::triple); break; default: abort(); /* never reached */ } } rdf::term* implementation::construct_term(trix_context& context) { rdf::term* term = nullptr; const auto text = _reader.read_string(); switch (context.element) { case trix_element::id: { term = new rdf::blank_node(text); break; } case trix_element::uri: { term = new rdf::uri_reference(text); break; } case trix_element::plain_literal: { term = new rdf::plain_literal(text, _reader.xml_lang()); break; } case trix_element::typed_literal: { const auto datatype_uri = _reader.get_attribute("datatype"); if (!datatype_uri) { throw_error(context, "missing 'datatype' attribute for <typedLiteral> element"); } term = new rdf::typed_literal(text, datatype_uri); break; } default: abort(); /* never reached */ } return term; } void implementation::throw_error(trix_context& context, const char* const what) { (void)context; throw rdf::reader_error(what, _reader.line_number(), _reader.column_number()); } <commit_msg>Fixed a bug in TriX element name interning.<commit_after>/* This is free and unencumbered software released into the public domain. */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include "rdf++/reader/trix.h" #include "rdf++/quad.h" #include "rdf++/term.h" #include "rdf++/triple.h" #include "xml_reader.h" #include <memory> /* for std::unique_ptr */ #include <cstring> /* for std::strcmp() */ namespace { enum class trix_element { unknown = 0, trix, graph, triple, id, uri, plain_literal, typed_literal, }; enum class trix_state {start, document, graph, triple, eof, abort}; struct trix_context { trix_state state = trix_state::start; trix_element element = trix_element::unknown; unsigned int term_pos = 0; std::unique_ptr<rdf::term> terms[3] = {nullptr, nullptr, nullptr}; std::unique_ptr<rdf::uri_reference> graph = nullptr; std::function<void (rdf::triple*)> triple_callback = nullptr; std::function<void (rdf::quad*)> quad_callback = nullptr; }; struct implementation : public rdf::reader::implementation { implementation(FILE* stream, const char* content_type, const char* charset, const char* base_uri); virtual ~implementation() noexcept override; virtual void read_triples(std::function<void (rdf::triple*)> callback) override; virtual void read_quads(std::function<void (rdf::quad*)> callback) override; virtual void abort() override; protected: void read_with_context(trix_context& context); void ensure_state(trix_context& context, trix_state state); void assert_state(trix_context& context, trix_state state); void enter_state(trix_context& context, trix_state state); void leave_state(trix_context& context, trix_state state); void change_state(trix_context& context, trix_state state); void ensure_depth(trix_context& context, unsigned int depth); void record_term(trix_context& context); void begin_element(trix_context& context); void finish_element(trix_context& context); rdf::term* construct_term(trix_context& context); void throw_error(trix_context& context, const char* what); private: xml_reader _reader; }; } rdf::reader::implementation* rdf_reader_for_trix(FILE* const stream, const char* const content_type, const char* const charset, const char* const base_uri) { return new implementation(stream, content_type, charset, base_uri); } implementation::implementation(FILE* const stream, const char* const content_type, const char* const charset, const char* const base_uri) : _reader(stream, base_uri, charset) { assert(stream != nullptr); (void)content_type; } implementation::~implementation() noexcept = default; static trix_element intern_trix_element(const char* const element_name) { switch (*element_name) { case 'T': if (std::strcmp(element_name, "TriX") == 0) { return trix_element::trix; } break; case 'g': if (std::strcmp(element_name, "graph") == 0) { return trix_element::graph; } break; case 'i': if (std::strcmp(element_name, "id") == 0) { return trix_element::id; } break; case 'p': if (std::strcmp(element_name, "plainLiteral") == 0) { return trix_element::plain_literal; } break; case 't': if (std::strcmp(element_name, "trix") == 0) { return trix_element::trix; } if (std::strcmp(element_name, "triple") == 0) { return trix_element::triple; } if (std::strcmp(element_name, "typedLiteral") == 0) { return trix_element::typed_literal; } break; case 'u': if (std::strcmp(element_name, "uri") == 0) { return trix_element::uri; } break; default: break; } return trix_element::unknown; } void implementation::read_triples(std::function<void (rdf::triple*)> callback) { trix_context context; context.triple_callback = callback; read_with_context(context); } void implementation::read_quads(std::function<void (rdf::quad*)> callback) { trix_context context; context.quad_callback = callback; read_with_context(context); } void implementation::abort() { // TODO } void implementation::read_with_context(trix_context& context) { while (_reader.read()) { switch (_reader.node_type()) { case xml_node_type::element: begin_element(context); break; case xml_node_type::end_element: finish_element(context); break; default: /* ignored */ break; } } } void implementation::ensure_state(trix_context& context, const trix_state state) { if (context.state != state) { throw_error(context, "mismatched nesting of elements in TriX input"); } } void implementation::assert_state(trix_context& context, const trix_state state) { (void)state, (void)context; assert(context.state == state); } void implementation::enter_state(trix_context& context, const trix_state state) { switch (state) { case trix_state::graph: context.graph.reset(); break; case trix_state::triple: context.term_pos = 0; break; default: break; } } void implementation::leave_state(trix_context& context, const trix_state state) { switch (state) { case trix_state::triple: if (context.quad_callback) { auto quad = new rdf::quad( context.terms[0].get(), context.terms[1].get(), context.terms[2].get(), context.graph ? (context.graph)->clone() : nullptr); context.quad_callback(quad); } else if (context.triple_callback) { auto triple = new rdf::triple( context.terms[0].get(), context.terms[1].get(), context.terms[2].get()); context.triple_callback(triple); } for (auto i = 0U; i < 3; i++) { if (context.quad_callback || context.triple_callback) { /* The callback took ownership of the terms: */ context.terms[i].release(); } else { context.terms[i].reset(); } } context.term_pos = 0; break; default: break; } } void implementation::change_state(trix_context& context, const trix_state state) { leave_state(context, context.state); context.state = state; enter_state(context, context.state); } void implementation::ensure_depth(trix_context& context, const unsigned int depth) { if (_reader.depth() != depth) { throw_error(context, "incorrect nesting of elements in TriX input"); } } void implementation::record_term(trix_context& context) { if (context.term_pos >= 3) { throw_error(context, "too many elements inside <triple> element"); } context.terms[context.term_pos].reset(construct_term(context)); context.term_pos++; } void implementation::begin_element(trix_context& context) { context.element = intern_trix_element(_reader.name()); switch (context.element) { case trix_element::trix: ensure_state(context, trix_state::start); ensure_depth(context, 0); change_state(context, trix_state::document); break; case trix_element::graph: ensure_state(context, trix_state::document); ensure_depth(context, 1); change_state(context, trix_state::graph); break; case trix_element::triple: ensure_state(context, trix_state::graph); ensure_depth(context, 2); change_state(context, trix_state::triple); break; case trix_element::uri: if (context.state == trix_state::graph) { ensure_depth(context, 2); if (context.graph) { throw_error(context, "repeated <uri> element inside <graph> element"); } context.graph.reset(new rdf::uri_reference(_reader.read_string())); break; } ensure_state(context, trix_state::triple); ensure_depth(context, 3); record_term(context); break; case trix_element::id: case trix_element::plain_literal: case trix_element::typed_literal: ensure_state(context, trix_state::triple); ensure_depth(context, 3); record_term(context); break; default: throw_error(context, "unknown XML element in TriX input"); } } void implementation::finish_element(trix_context& context) { context.element = intern_trix_element(_reader.name()); switch (context.element) { case trix_element::trix: assert_state(context, trix_state::document); change_state(context, trix_state::eof); break; case trix_element::graph: assert_state(context, trix_state::graph); change_state(context, trix_state::document); break; case trix_element::triple: assert_state(context, trix_state::triple); change_state(context, trix_state::graph); break; case trix_element::uri: //assert_state(trix_state::triple, context); // FIXME: triple | graph break; case trix_element::id: case trix_element::plain_literal: case trix_element::typed_literal: assert_state(context, trix_state::triple); break; default: abort(); /* never reached */ } } rdf::term* implementation::construct_term(trix_context& context) { rdf::term* term = nullptr; const auto text = _reader.read_string(); switch (context.element) { case trix_element::id: { term = new rdf::blank_node(text); break; } case trix_element::uri: { term = new rdf::uri_reference(text); break; } case trix_element::plain_literal: { term = new rdf::plain_literal(text, _reader.xml_lang()); break; } case trix_element::typed_literal: { const auto datatype_uri = _reader.get_attribute("datatype"); if (!datatype_uri) { throw_error(context, "missing 'datatype' attribute for <typedLiteral> element"); } term = new rdf::typed_literal(text, datatype_uri); break; } default: abort(); /* never reached */ } return term; } void implementation::throw_error(trix_context& context, const char* const what) { (void)context; throw rdf::reader_error(what, _reader.line_number(), _reader.column_number()); } <|endoftext|>
<commit_before>/* Copyright (c) 2010, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/storage.hpp" #include "libtorrent/file_pool.hpp" #include <boost/utility.hpp> #include <stdlib.h> using namespace libtorrent; int main(int argc, char* argv[]) { if (argc != 3 && argc != 2) { fprintf(stderr, "Usage: fragmentation_test torrent-file file-storage-path\n" " fragmentation_test file\n\n"); return 1; } if (argc == 2) { error_code ec; file f(argv[1], file::read_only, ec); if (ec) { fprintf(stderr, "Error opening file %s: %s\n", argv[1], ec.message().c_str()); return 1; } size_type off = f.phys_offset(0); printf("physical offset of file %s: %" PRId64 "\n", argv[1], off); return 0; } error_code ec; boost::intrusive_ptr<torrent_info> ti(new torrent_info(argv[1], ec)); if (ec) { fprintf(stderr, "Error while loading torrent file: %s\n", ec.message().c_str()); return 1; } file_pool fp; boost::shared_ptr<storage_interface> st(default_storage_constructor(ti->files(), 0, argv[2], fp, std::vector<boost::uint8_t>())); // the first field is the piece index, the second // one is the physical location of the piece on disk std::vector<std::pair<int, size_type> > pieces; // make sure all the files are there std::vector<std::pair<size_type, std::time_t> > files = get_filesizes(ti->files(), argv[2]); for (int i = 0; i < ti->num_files(); ++i) { if (ti->file_at(i).size == files[i].first) continue; fprintf(stderr, "Files for this torrent are missing or incomplete: %s was %"PRId64" bytes, expected %"PRId64" bytes\n" , ti->files().file_path(ti->file_at(i)).c_str(), files[i].first, ti->file_at(i).size); return 1; } for (int i = 0; i < ti->num_pieces(); ++i) { pieces.push_back(std::make_pair(i, st->physical_offset(i, 0))); if (pieces.back().second == size_type(i) * ti->piece_length()) { // this suggests that the OS doesn't support physical offset // or that the file doesn't exist, or some other file error fprintf(stderr, "Your operating system or filesystem " "does not appear to support querying physical disk offset\n"); return 1; } } FILE* f = fopen("fragmentation.log", "w+"); if (f == 0) { fprintf(stderr, "error while opening log file: %s\n", strerror(errno)); return 1; } for (int i = 0; i < ti->num_pieces(); ++i) { fprintf(f, "%d %"PRId64"\n", pieces[i].first, pieces[i].second); } fclose(f); f = fopen("fragmentation.gnuplot", "w+"); if (f == 0) { fprintf(stderr, "error while opening gnuplot file: %s\n", strerror(errno)); return 1; } fprintf(f, "set term png size 1200,800\n" "set output \"fragmentation.png\"\n" "set xrange [*:*]\n" "set xlabel \"piece\"\n" "set ylabel \"drive offset\"\n" "set key box\n" "set title \"fragmentation for '%s'\"\n" "set tics nomirror\n" "plot \"fragmentation.log\" using 1:2 with dots lt rgb \"#e07070\" notitle axis x1y1, x=0\n" , ti->name().c_str()); fclose(f); system("gnuplot fragmentation.gnuplot"); } <commit_msg>fix gnuplot syntax error in fragmentation test<commit_after>/* Copyright (c) 2010, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/storage.hpp" #include "libtorrent/file_pool.hpp" #include <boost/utility.hpp> #include <stdlib.h> using namespace libtorrent; int main(int argc, char* argv[]) { if (argc != 3 && argc != 2) { fprintf(stderr, "Usage: fragmentation_test torrent-file file-storage-path\n" " fragmentation_test file\n\n"); return 1; } if (argc == 2) { error_code ec; file f(argv[1], file::read_only, ec); if (ec) { fprintf(stderr, "Error opening file %s: %s\n", argv[1], ec.message().c_str()); return 1; } size_type off = f.phys_offset(0); printf("physical offset of file %s: %" PRId64 "\n", argv[1], off); return 0; } error_code ec; boost::intrusive_ptr<torrent_info> ti(new torrent_info(argv[1], ec)); if (ec) { fprintf(stderr, "Error while loading torrent file: %s\n", ec.message().c_str()); return 1; } file_pool fp; boost::shared_ptr<storage_interface> st(default_storage_constructor(ti->files(), 0, argv[2], fp, std::vector<boost::uint8_t>())); // the first field is the piece index, the second // one is the physical location of the piece on disk std::vector<std::pair<int, size_type> > pieces; // make sure all the files are there std::vector<std::pair<size_type, std::time_t> > files = get_filesizes(ti->files(), argv[2]); for (int i = 0; i < ti->num_files(); ++i) { if (ti->file_at(i).size == files[i].first) continue; fprintf(stderr, "Files for this torrent are missing or incomplete: %s was %"PRId64" bytes, expected %"PRId64" bytes\n" , ti->files().file_path(ti->file_at(i)).c_str(), files[i].first, ti->file_at(i).size); return 1; } for (int i = 0; i < ti->num_pieces(); ++i) { pieces.push_back(std::make_pair(i, st->physical_offset(i, 0))); if (pieces.back().second == size_type(i) * ti->piece_length()) { // this suggests that the OS doesn't support physical offset // or that the file doesn't exist, or some other file error fprintf(stderr, "Your operating system or filesystem " "does not appear to support querying physical disk offset\n"); return 1; } } FILE* f = fopen("fragmentation.log", "w+"); if (f == 0) { fprintf(stderr, "error while opening log file: %s\n", strerror(errno)); return 1; } for (int i = 0; i < ti->num_pieces(); ++i) { fprintf(f, "%d %"PRId64"\n", pieces[i].first, pieces[i].second); } fclose(f); f = fopen("fragmentation.gnuplot", "w+"); if (f == 0) { fprintf(stderr, "error while opening gnuplot file: %s\n", strerror(errno)); return 1; } fprintf(f, "set term png size 1200,800\n" "set output \"fragmentation.png\"\n" "set xrange [*:*]\n" "set xlabel \"piece\"\n" "set ylabel \"drive offset\"\n" "set key box\n" "set title \"fragmentation for '%s'\"\n" "set tics nomirror\n" "plot \"fragmentation.log\" using 1:2 with dots lt rgb \"#e07070\" notitle axis x1y1\n" , ti->name().c_str()); fclose(f); system("gnuplot fragmentation.gnuplot"); } <|endoftext|>
<commit_before>#include "tree_sitter/compiler.h" #include "helpers.h" namespace tree_sitter_examples { using tree_sitter::Grammar; using namespace tree_sitter::rules; extern const Grammar javascript({ { "program", repeat(sym("statement")) }, // Statements { "statement", choice({ sym("statement_block"), sym("if_statement"), sym("try_statement"), sym("switch_statement"), sym("while_statement"), sym("for_statement"), sym("break_statement"), sym("var_declaration"), sym("return_statement"), sym("delete_statement"), sym("expression_statement") }) }, { "statement_block", in_braces(err(repeat(sym("statement")))) }, { "for_statement", seq({ keyword("for"), in_parens(seq({ choice({ sym("var_declaration"), sym("expression_statement") }), sym("expression_statement"), err(sym("expression")) })), sym("statement") }) }, { "if_statement", seq({ keyword("if"), in_parens(err(sym("expression"))), sym("statement"), optional(prec(1, seq({ keyword("else"), sym("statement") }))) }) }, { "while_statement", seq({ keyword("while"), in_parens(err(sym("expression"))), sym("statement") }) }, { "try_statement", seq({ keyword("try"), sym("statement"), keyword("catch"), in_parens(err(sym("identifier"))), sym("statement") }) }, { "switch_statement", seq({ keyword("switch"), in_parens(err(sym("expression"))), in_braces(repeat(sym("switch_case"))) }) }, { "switch_case", seq({ choice({ seq({ keyword("case"), sym("expression") }), keyword("default") }), str(":"), repeat(sym("statement")) }) }, { "break_statement", seq({ keyword("break"), sym("_terminator") }) }, { "var_declaration", seq({ keyword("var"), comma_sep(seq({ optional(sym("comment")), choice({ sym("assignment"), sym("identifier") }) })), sym("_terminator") }) }, { "expression_statement", seq({ err(sym("expression")), sym("_terminator") }) }, { "return_statement", seq({ keyword("return"), optional(sym("expression")), sym("_terminator") }) }, { "delete_statement", seq({ keyword("delete"), sym("property_access"), sym("_terminator") }) }, // Expressions { "expression", choice({ sym("function_expression"), sym("function_call"), sym("constructor_call"), sym("property_access"), sym("assignment"), sym("ternary"), sym("math_op"), sym("bool_op"), sym("object"), sym("array"), sym("regex"), sym("string"), sym("number"), sym("true"), sym("false"), sym("null"), sym("identifier"), in_parens(sym("expression")) }) }, { "math_op", choice({ prefix_op("++", "expression", 3), prefix_op("--", "expression", 3), postfix_op("++", "expression", 3), postfix_op("--", "expression", 3), prefix_op("+", "expression", 3), prefix_op("-", "expression", 3), infix_op("*", "expression", 2), infix_op("/", "expression", 2), infix_op("&", "expression", 2), infix_op("|", "expression", 2), infix_op("^", "expression", 2), infix_op("+", "expression", 1), infix_op("-", "expression", 1) }) }, { "bool_op", choice({ infix_op("||", "expression", 1), infix_op("&&", "expression", 2), infix_op("===", "expression", 3), infix_op("==", "expression", 3), infix_op("!==", "expression", 3), infix_op("!=", "expression", 3), infix_op("<=", "expression", 3), infix_op("<", "expression", 3), infix_op(">=", "expression", 3), infix_op(">", "expression", 3), prefix_op("!", "expression", 4) }) }, { "ternary", seq({ sym("expression"), str("?"), sym("expression"), str(":"), sym("expression") }) }, { "assignment", prec(-1, seq({ choice({ sym("identifier"), sym("property_access") }), str("="), sym("expression") })) }, { "function_expression", seq({ keyword("function"), optional(sym("identifier")), sym("formal_parameters"), sym("statement_block") }) }, { "function_call", seq({ sym("expression"), in_parens(comma_sep(err(sym("expression")))) }) }, { "constructor_call", seq({ keyword("new"), sym("function_call") }) }, { "property_access", seq({ sym("expression"), choice({ seq({ str("."), sym("identifier") }), in_brackets(sym("expression")) }) }) }, { "formal_parameters", in_parens(comma_sep(sym("identifier"))) }, // Literals { "comment", token(choice({ seq({ str("/*"), repeat(pattern("[^*]|(*[^/])")), str("*/") }), pattern("//[^\n]*") })) }, { "object", in_braces(comma_sep(err(seq({ choice({ sym("string"), sym("identifier") }), str(":"), sym("expression") })))) }, { "array", in_brackets(comma_sep(err(sym("expression")))) }, { "_terminator", pattern("[;\n]") }, { "regex", token(delimited("/")) }, { "string", token(choice({ delimited("\""), delimited("'") })) }, { "identifier", pattern("[\\a_$][\\w_$]*") }, { "number", pattern("\\d+(\\.\\d+)?") }, { "null", keyword("null") }, { "true", keyword("true") }, { "false", keyword("false") }, }, { // ubiquitous_tokens { "comment" } }); } <commit_msg>Remove unnecessary comment rule from JS grammar<commit_after>#include "tree_sitter/compiler.h" #include "helpers.h" namespace tree_sitter_examples { using tree_sitter::Grammar; using namespace tree_sitter::rules; extern const Grammar javascript({ { "program", repeat(sym("statement")) }, // Statements { "statement", choice({ sym("statement_block"), sym("if_statement"), sym("try_statement"), sym("switch_statement"), sym("while_statement"), sym("for_statement"), sym("break_statement"), sym("var_declaration"), sym("return_statement"), sym("delete_statement"), sym("expression_statement") }) }, { "statement_block", in_braces(err(repeat(sym("statement")))) }, { "for_statement", seq({ keyword("for"), in_parens(seq({ choice({ sym("var_declaration"), sym("expression_statement") }), sym("expression_statement"), err(sym("expression")) })), sym("statement") }) }, { "if_statement", seq({ keyword("if"), in_parens(err(sym("expression"))), sym("statement"), optional(prec(1, seq({ keyword("else"), sym("statement") }))) }) }, { "while_statement", seq({ keyword("while"), in_parens(err(sym("expression"))), sym("statement") }) }, { "try_statement", seq({ keyword("try"), sym("statement"), keyword("catch"), in_parens(err(sym("identifier"))), sym("statement") }) }, { "switch_statement", seq({ keyword("switch"), in_parens(err(sym("expression"))), in_braces(repeat(sym("switch_case"))) }) }, { "switch_case", seq({ choice({ seq({ keyword("case"), sym("expression") }), keyword("default") }), str(":"), repeat(sym("statement")) }) }, { "break_statement", seq({ keyword("break"), sym("_terminator") }) }, { "var_declaration", seq({ keyword("var"), comma_sep(err(choice({ sym("assignment"), sym("identifier") }))), sym("_terminator") }) }, { "expression_statement", seq({ err(sym("expression")), sym("_terminator") }) }, { "return_statement", seq({ keyword("return"), optional(sym("expression")), sym("_terminator") }) }, { "delete_statement", seq({ keyword("delete"), sym("property_access"), sym("_terminator") }) }, // Expressions { "expression", choice({ sym("function_expression"), sym("function_call"), sym("constructor_call"), sym("property_access"), sym("assignment"), sym("ternary"), sym("math_op"), sym("bool_op"), sym("object"), sym("array"), sym("regex"), sym("string"), sym("number"), sym("true"), sym("false"), sym("null"), sym("identifier"), in_parens(sym("expression")) }) }, { "math_op", choice({ prefix_op("++", "expression", 3), prefix_op("--", "expression", 3), postfix_op("++", "expression", 3), postfix_op("--", "expression", 3), prefix_op("+", "expression", 3), prefix_op("-", "expression", 3), infix_op("*", "expression", 2), infix_op("/", "expression", 2), infix_op("&", "expression", 2), infix_op("|", "expression", 2), infix_op("^", "expression", 2), infix_op("+", "expression", 1), infix_op("-", "expression", 1) }) }, { "bool_op", choice({ infix_op("||", "expression", 1), infix_op("&&", "expression", 2), infix_op("===", "expression", 3), infix_op("==", "expression", 3), infix_op("!==", "expression", 3), infix_op("!=", "expression", 3), infix_op("<=", "expression", 3), infix_op("<", "expression", 3), infix_op(">=", "expression", 3), infix_op(">", "expression", 3), prefix_op("!", "expression", 4) }) }, { "ternary", seq({ sym("expression"), str("?"), sym("expression"), str(":"), sym("expression") }) }, { "assignment", prec(-1, seq({ choice({ sym("identifier"), sym("property_access") }), str("="), sym("expression") })) }, { "function_expression", seq({ keyword("function"), optional(sym("identifier")), sym("formal_parameters"), sym("statement_block") }) }, { "function_call", seq({ sym("expression"), in_parens(comma_sep(err(sym("expression")))) }) }, { "constructor_call", seq({ keyword("new"), sym("function_call") }) }, { "property_access", seq({ sym("expression"), choice({ seq({ str("."), sym("identifier") }), in_brackets(sym("expression")) }) }) }, { "formal_parameters", in_parens(comma_sep(sym("identifier"))) }, // Literals { "comment", token(choice({ seq({ str("/*"), repeat(pattern("[^*]|(*[^/])")), str("*/") }), pattern("//[^\n]*") })) }, { "object", in_braces(comma_sep(err(seq({ choice({ sym("string"), sym("identifier") }), str(":"), sym("expression") })))) }, { "array", in_brackets(comma_sep(err(sym("expression")))) }, { "_terminator", pattern("[;\n]") }, { "regex", token(delimited("/")) }, { "string", token(choice({ delimited("\""), delimited("'") })) }, { "identifier", pattern("[\\a_$][\\w_$]*") }, { "number", pattern("\\d+(\\.\\d+)?") }, { "null", keyword("null") }, { "true", keyword("true") }, { "false", keyword("false") }, }, { // ubiquitous_tokens { "comment" } }); } <|endoftext|>
<commit_before>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id$ */ //_________________________________________________________________________ // Base class for the clusterization algorithm (pure abstract) //*-- //*-- Author: Yves Schutz SUBATECH ////////////////////////////////////////////////////////////////////////////// // --- ROOT system --- // --- Standard library --- // --- AliRoot header files --- #include "AliPHOSClusterizer.h" #include "AliPHOSGetter.h" ClassImp(AliPHOSClusterizer) //____________________________________________________________________________ AliPHOSClusterizer::AliPHOSClusterizer():TTask("","") { // ctor fEventFolderName = "" ; fFirstEvent = 0 ; fLastEvent = -1 ; } //____________________________________________________________________________ AliPHOSClusterizer::AliPHOSClusterizer(const TString alirunFileName, const TString eventFolderName): TTask("PHOS"+AliConfig::Instance()->GetReconstructionerTaskName(), alirunFileName), fEventFolderName(eventFolderName) { // ctor fFirstEvent = 0 ; fLastEvent = -1 ; } //____________________________________________________________________________ AliPHOSClusterizer::~AliPHOSClusterizer() { // dtor //Remove this from the parental task before destroying AliPHOSGetter::Instance()->PhosLoader()->CleanReconstructioner(); } <commit_msg>Test on PHOSloader existence added to destr.<commit_after>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id$ */ //_________________________________________________________________________ // Base class for the clusterization algorithm (pure abstract) //*-- //*-- Author: Yves Schutz SUBATECH ////////////////////////////////////////////////////////////////////////////// // --- ROOT system --- // --- Standard library --- // --- AliRoot header files --- #include "AliPHOSClusterizer.h" #include "AliPHOSGetter.h" ClassImp(AliPHOSClusterizer) //____________________________________________________________________________ AliPHOSClusterizer::AliPHOSClusterizer():TTask("","") { // ctor fEventFolderName = "" ; fFirstEvent = 0 ; fLastEvent = -1 ; } //____________________________________________________________________________ AliPHOSClusterizer::AliPHOSClusterizer(const TString alirunFileName, const TString eventFolderName): TTask("PHOS"+AliConfig::Instance()->GetReconstructionerTaskName(), alirunFileName), fEventFolderName(eventFolderName) { // ctor fFirstEvent = 0 ; fLastEvent = -1 ; } //____________________________________________________________________________ AliPHOSClusterizer::~AliPHOSClusterizer() { // dtor //Remove this from the parental task before destroying if(AliPHOSGetter::Instance()->PhosLoader()) AliPHOSGetter::Instance()->PhosLoader()->CleanReconstructioner(); } <|endoftext|>
<commit_before>// Copyright (C) 2010-2013 Joshua Boyce. // See the file COPYING for copying permission. #include <memory> #include <string> #include <vector> #include <sstream> #include <iostream> #include <algorithm> #include <hadesmem/detail/warning_disable_prefix.hpp> #include <boost/program_options.hpp> #include <hadesmem/detail/warning_disable_suffix.hpp> #include <windows.h> #include <hadesmem/error.hpp> #include <hadesmem/module.hpp> #include <hadesmem/region.hpp> #include <hadesmem/process.hpp> #include <hadesmem/module_list.hpp> #include <hadesmem/region_list.hpp> #include <hadesmem/pelib/export.hpp> #include <hadesmem/process_list.hpp> #include <hadesmem/process_entry.hpp> #include <hadesmem/pelib/pe_file.hpp> #include <hadesmem/pelib/import_dir.hpp> #include <hadesmem/detail/initialize.hpp> #include <hadesmem/pelib/export_list.hpp> #include <hadesmem/pelib/import_thunk.hpp> #include <hadesmem/pelib/import_dir_list.hpp> #include <hadesmem/pelib/import_thunk_list.hpp> namespace { std::wstring PtrToString(void const* const ptr) { std::wostringstream str; str.imbue(std::locale::classic()); str << std::hex << reinterpret_cast<DWORD_PTR>(ptr); return str.str(); } void DumpRegions(hadesmem::Process const& process) { std::wcout << "\nRegions:\n"; hadesmem::RegionList const regions(process); for (auto const& region : regions) { std::wcout << "\n"; std::wcout << "\tBase: " << PtrToString(region.GetBase()) << "\n"; std::wcout << "\tAllocation Base: " << PtrToString(region.GetAllocBase()) << "\n"; std::wcout << "\tAllocation Protect: " << std::hex << region.GetAllocProtect() << std::dec << "\n"; std::wcout << "\tSize: " << std::hex << region.GetSize() << std::dec << "\n"; std::wcout << "\tState: " << std::hex << region.GetState() << std::dec << "\n"; std::wcout << "\tProtect: " << std::hex << region.GetProtect() << std::dec << "\n"; std::wcout << "\tType: " << std::hex << region.GetType() << std::dec << "\n"; } } void DumpExports(hadesmem::Process const& process, hadesmem::Module const& module) { std::wcout << "\n\tExports:\n"; hadesmem::PeFile pe_file(process, module.GetHandle(), hadesmem::PeFileType::Image); hadesmem::ExportList exports(process, pe_file); for (auto const& e : exports) { std::wcout << std::boolalpha; std::wcout << "\n"; std::wcout << "\t\tRVA: " << std::hex << e.GetRva() << std::dec << "\n"; std::wcout << "\t\tVA: " << PtrToString(e.GetVa()) << "\n"; std::wcout << "\t\tName: " << e.GetName().c_str() << "\n"; std::wcout << "\t\tOrdinal: " << e.GetOrdinal() << "\n"; std::wcout << "\t\tByName: " << e.ByName() << "\n"; std::wcout << "\t\tByOrdinal: " << e.ByOrdinal() << "\n"; std::wcout << "\t\tIsForwarded: " << e.IsForwarded() << "\n"; if (e.IsForwarded()) { std::wcout << "\t\tForwarder: " << e.GetForwarder().c_str() << "\n"; std::wcout << "\t\tForwarderModule: " << e.GetForwarderModule().c_str() << "\n"; std::wcout << "\t\tForwarderFunction: " << e.GetForwarderFunction().c_str() << "\n"; std::wcout << "\t\tIsForwardedByOrdinal: " << e.IsForwardedByOrdinal() << "\n"; if (e.IsForwardedByOrdinal()) { try { std::wcout << "\t\tForwarderOrdinal: " << e.GetForwarderOrdinal() << "\n"; } catch (std::exception const& /*e*/) { std::wcout << "\t\tForwarderOrdinal Invalid.\n"; } } } std::wcout << std::noboolalpha; } } void DumpImports(hadesmem::Process const& process, hadesmem::Module const& module) { std::wcout << "\n\tImport Dirs:\n"; hadesmem::PeFile pe_file(process, module.GetHandle(), hadesmem::PeFileType::Image); hadesmem::ImportDirList import_dirs(process, pe_file); for (auto const& dir : import_dirs) { std::wcout << std::boolalpha; std::wcout << "\n"; std::wcout << "\t\tOriginalFirstThunk: " << std::hex << dir.GetOriginalFirstThunk() << std::dec << "\n"; std::wcout << "\t\tTimeDateStamp: " << dir.GetTimeDateStamp() << "\n"; std::wcout << "\t\tForwarderChain: " << dir.GetForwarderChain() << "\n"; std::wcout << "\t\tName (Raw): " << std::hex << dir.GetNameRaw() << std::dec << "\n"; std::wcout << "\t\tName: " << dir.GetName().c_str() << "\n"; std::wcout << "\t\tFirstThunk: " << std::hex << dir.GetFirstThunk() << std::dec << "\n"; std::wcout << "\n\t\tImport Thunks:\n"; // Images without an INT are valid, but after an image like this is loaded // it is impossible to recover the name table. if (!dir.GetOriginalFirstThunk()) { std::wcout << "\n\t\t\tWARNING! No INT for this module.\n"; continue; } // Some modules (packed modules are the only ones I've found so far) have // import directories where the IAT RVA is the same as the INT RVA which // effectively means there is no INT once the module is loaded. if (dir.GetOriginalFirstThunk() == dir.GetFirstThunk()) { std::wcout << "\n\t\t\tWARNING! IAT is same as INT for this module.\n"; continue; } hadesmem::ImportThunkList import_thunks(process, pe_file, dir.GetOriginalFirstThunk()); for (auto const& thunk : import_thunks) { std::wcout << "\n"; std::wcout << "\t\t\tAddressOfData: " << std::hex << thunk.GetAddressOfData() << std::dec << "\n"; std::wcout << "\t\t\tOrdinalRaw: " << thunk.GetOrdinalRaw() << "\n"; std::wcout << "\t\t\tByOrdinal: " << thunk.ByOrdinal() << "\n"; if (thunk.ByOrdinal()) { std::wcout << "\t\t\tOrdinal: " << thunk.GetOrdinal() << "\n"; } else { std::wcout << "\t\t\tHint: " << thunk.GetHint() << "\n"; std::wcout << "\t\t\tName: " << thunk.GetName().c_str() << "\n"; } std::wcout << "\t\t\tFunction: " << std::hex << thunk.GetFunction() << std::dec << "\n"; } std::wcout << std::noboolalpha; } } void DumpModules(hadesmem::Process const& process) { std::wcout << "\nModules:\n"; hadesmem::ModuleList const modules(process); for (auto const& module : modules) { std::wcout << "\n"; std::wcout << "\tHandle: " << PtrToString(module.GetHandle()) << "\n"; std::wcout << "\tSize: " << std::hex << module.GetSize() << std::dec << "\n"; std::wcout << "\tName: " << module.GetName() << "\n"; std::wcout << "\tPath: " << module.GetPath() << "\n"; DumpExports(process, module); DumpImports(process, module); } } void DumpProcessEntry(hadesmem::ProcessEntry const& process_entry) { std::wcout << "\n"; std::wcout << "ID: " << process_entry.GetId() << "\n"; std::wcout << "Threads: " << process_entry.GetThreads() << "\n"; std::wcout << "Parent: " << process_entry.GetParentId() << "\n"; std::wcout << "Priority: " << process_entry.GetPriority() << "\n"; std::wcout << "Name: " << process_entry.GetName() << "\n"; std::unique_ptr<hadesmem::Process> process; try { process.reset(new hadesmem::Process(process_entry.GetId())); } catch (std::exception const& /*e*/) { std::wcout << "\nCould not open process for further inspection.\n\n"; return; } std::wcout << "Path: " << hadesmem::GetPath(*process) << "\n"; std::wcout << "WoW64: " << (hadesmem::IsWoW64(*process) ? "Yes" : "No") << "\n"; DumpModules(*process); DumpRegions(*process); } } int main(int /*argc*/, char* /*argv*/[]) { try { hadesmem::detail::DisableUserModeCallbackExceptionFilter(); hadesmem::detail::EnableCrtDebugFlags(); hadesmem::detail::EnableTerminationOnHeapCorruption(); hadesmem::detail::EnableBottomUpRand(); hadesmem::detail::ImbueAllDefault(); std::cout << "HadesMem Dumper\n"; boost::program_options::options_description opts_desc( "General options"); opts_desc.add_options() ("help", "produce help message") ("pid", boost::program_options::value<DWORD>(), "process id") ; std::vector<std::wstring> const args = boost::program_options:: split_winmain(GetCommandLine()); boost::program_options::variables_map var_map; boost::program_options::store(boost::program_options::wcommand_line_parser( args).options(opts_desc).run(), var_map); boost::program_options::notify(var_map); if (var_map.count("help")) { std::cout << '\n' << opts_desc << '\n'; return 1; } DWORD pid = 0; if (var_map.count("pid")) { pid = var_map["pid"].as<DWORD>(); } try { hadesmem::GetSeDebugPrivilege(); std::wcout << "\nAcquired SeDebugPrivilege.\n"; } catch (std::exception const& /*e*/) { std::wcout << "\nFailed to acquire SeDebugPrivilege.\n"; } if (pid) { hadesmem::ProcessList const processes; auto iter = std::find_if(std::begin(processes), std::end(processes), [pid] (hadesmem::ProcessEntry const& process_entry) { return process_entry.GetId() == pid; }); if (iter != std::end(processes)) { DumpProcessEntry(*iter); } else { HADESMEM_THROW_EXCEPTION(hadesmem::Error() << hadesmem::ErrorString("Failed to find requested process.")); } } else { std::wcout << "\nProcesses:\n"; hadesmem::ProcessList const processes; for (auto const& process_entry : processes) { DumpProcessEntry(process_entry); } } return 0; } catch (std::exception const& e) { std::cerr << "\nError!\n"; std::cerr << boost::diagnostic_information(e) << '\n'; return 1; } } <commit_msg>* Add file dumping support. * Cleanup output a bit.<commit_after>// Copyright (C) 2010-2013 Joshua Boyce. // See the file COPYING for copying permission. #include <memory> #include <string> #include <vector> #include <sstream> #include <iostream> #include <algorithm> #include <hadesmem/detail/warning_disable_prefix.hpp> #include <boost/filesystem.hpp> #include <boost/program_options.hpp> #include <hadesmem/detail/warning_disable_suffix.hpp> #include <windows.h> #include <hadesmem/error.hpp> #include <hadesmem/module.hpp> #include <hadesmem/region.hpp> #include <hadesmem/process.hpp> #include <hadesmem/module_list.hpp> #include <hadesmem/region_list.hpp> #include <hadesmem/pelib/export.hpp> #include <hadesmem/process_list.hpp> #include <hadesmem/process_entry.hpp> #include <hadesmem/pelib/pe_file.hpp> #include <hadesmem/pelib/dos_header.hpp> #include <hadesmem/pelib/import_dir.hpp> #include <hadesmem/pelib/nt_headers.hpp> #include <hadesmem/detail/self_path.hpp> #include <hadesmem/detail/initialize.hpp> #include <hadesmem/pelib/export_list.hpp> #include <hadesmem/pelib/import_thunk.hpp> #include <hadesmem/pelib/import_dir_list.hpp> #include <hadesmem/pelib/import_thunk_list.hpp> namespace { std::wstring PtrToString(void const* const ptr) { std::wostringstream str; str.imbue(std::locale::classic()); str << std::hex << reinterpret_cast<DWORD_PTR>(ptr); return str.str(); } void DumpRegions(hadesmem::Process const& process) { std::wcout << "\nRegions:\n"; hadesmem::RegionList const regions(process); for (auto const& region : regions) { std::wcout << "\n"; std::wcout << "\tBase: " << PtrToString(region.GetBase()) << "\n"; std::wcout << "\tAllocation Base: " << PtrToString(region.GetAllocBase()) << "\n"; std::wcout << "\tAllocation Protect: " << std::hex << region.GetAllocProtect() << std::dec << "\n"; std::wcout << "\tSize: " << std::hex << region.GetSize() << std::dec << "\n"; std::wcout << "\tState: " << std::hex << region.GetState() << std::dec << "\n"; std::wcout << "\tProtect: " << std::hex << region.GetProtect() << std::dec << "\n"; std::wcout << "\tType: " << std::hex << region.GetType() << std::dec << "\n"; } } void DumpExports(hadesmem::Process const& process, PVOID module, hadesmem::PeFileType type) { std::wcout << "\n\tExports:\n"; hadesmem::PeFile pe_file(process, module, type); hadesmem::ExportList exports(process, pe_file); for (auto const& e : exports) { std::wcout << std::boolalpha; std::wcout << "\n"; std::wcout << "\t\tRVA: " << std::hex << e.GetRva() << std::dec << "\n"; std::wcout << "\t\tVA: " << PtrToString(e.GetVa()) << "\n"; if (e.ByName()) { std::wcout << "\t\tName: " << e.GetName().c_str() << "\n"; } else if (e.ByOrdinal()) { std::wcout << "\t\tOrdinal: " << e.GetOrdinal() << "\n"; } else { std::wcout << "\t\tWARNING! Entry not exported by name or ordinal.\n"; } if (e.IsForwarded()) { std::wcout << "\t\tForwarder: " << e.GetForwarder().c_str() << "\n"; std::wcout << "\t\tForwarderModule: " << e.GetForwarderModule().c_str() << "\n"; std::wcout << "\t\tForwarderFunction: " << e.GetForwarderFunction().c_str() << "\n"; std::wcout << "\t\tIsForwardedByOrdinal: " << e.IsForwardedByOrdinal() << "\n"; if (e.IsForwardedByOrdinal()) { try { std::wcout << "\t\tForwarderOrdinal: " << e.GetForwarderOrdinal() << "\n"; } catch (std::exception const& /*e*/) { std::wcout << "\t\tForwarderOrdinal Invalid.\n"; } } } std::wcout << std::noboolalpha; } } void DumpImports(hadesmem::Process const& process, PVOID module, hadesmem::PeFileType type) { std::wcout << "\n\tImport Dirs:\n"; hadesmem::PeFile pe_file(process, module, type); hadesmem::ImportDirList import_dirs(process, pe_file); for (auto const& dir : import_dirs) { std::wcout << std::boolalpha; std::wcout << "\n"; std::wcout << "\t\tOriginalFirstThunk: " << std::hex << dir.GetOriginalFirstThunk() << std::dec << "\n"; std::wcout << "\t\tTimeDateStamp: " << dir.GetTimeDateStamp() << "\n"; std::wcout << "\t\tForwarderChain: " << dir.GetForwarderChain() << "\n"; std::wcout << "\t\tName (Raw): " << std::hex << dir.GetNameRaw() << std::dec << "\n"; std::wcout << "\t\tName: " << dir.GetName().c_str() << "\n"; std::wcout << "\t\tFirstThunk: " << std::hex << dir.GetFirstThunk() << std::dec << "\n"; std::wcout << "\n\t\tImport Thunks:\n"; // Certain information gets destroyed by the Windows PE loader in // some circumstances. Nothing we can do but ignore it or resort to // reading the original data from disk. if (type == hadesmem::PeFileType::Image) { // Images without an INT are valid, but after an image like this is loaded // it is impossible to recover the name table. if (!dir.GetOriginalFirstThunk()) { std::wcout << "\n\t\t\tWARNING! No INT for this module.\n"; continue; } // Some modules (packed modules are the only ones I've found so far) have // import directories where the IAT RVA is the same as the INT RVA which // effectively means there is no INT once the module is loaded. if (dir.GetOriginalFirstThunk() == dir.GetFirstThunk()) { std::wcout << "\n\t\t\tWARNING! IAT is same as INT for this module.\n"; continue; } } hadesmem::ImportThunkList import_thunks(process, pe_file, dir.GetOriginalFirstThunk()); for (auto const& thunk : import_thunks) { std::wcout << "\n"; std::wcout << "\t\t\tAddressOfData: " << std::hex << thunk.GetAddressOfData() << std::dec << "\n"; std::wcout << "\t\t\tOrdinalRaw: " << thunk.GetOrdinalRaw() << "\n"; if (thunk.ByOrdinal()) { std::wcout << "\t\t\tOrdinal: " << thunk.GetOrdinal() << "\n"; } else { std::wcout << "\t\t\tHint: " << thunk.GetHint() << "\n"; std::wcout << "\t\t\tName: " << thunk.GetName().c_str() << "\n"; } std::wcout << "\t\t\tFunction: " << std::hex << thunk.GetFunction() << std::dec << "\n"; } std::wcout << std::noboolalpha; } } void DumpModules(hadesmem::Process const& process) { std::wcout << "\nModules:\n"; hadesmem::ModuleList const modules(process); for (auto const& module : modules) { std::wcout << "\n"; std::wcout << "\tHandle: " << PtrToString(module.GetHandle()) << "\n"; std::wcout << "\tSize: " << std::hex << module.GetSize() << std::dec << "\n"; std::wcout << "\tName: " << module.GetName() << "\n"; std::wcout << "\tPath: " << module.GetPath() << "\n"; DumpExports(process, module.GetHandle(), hadesmem::PeFileType::Image); DumpImports(process, module.GetHandle(), hadesmem::PeFileType::Image); } } void DumpProcessEntry(hadesmem::ProcessEntry const& process_entry) { std::wcout << "\n"; std::wcout << "ID: " << process_entry.GetId() << "\n"; std::wcout << "Threads: " << process_entry.GetThreads() << "\n"; std::wcout << "Parent: " << process_entry.GetParentId() << "\n"; std::wcout << "Priority: " << process_entry.GetPriority() << "\n"; std::wcout << "Name: " << process_entry.GetName() << "\n"; std::unique_ptr<hadesmem::Process> process; try { process.reset(new hadesmem::Process(process_entry.GetId())); } catch (std::exception const& /*e*/) { std::wcout << "\nCould not open process for further inspection.\n\n"; return; } std::wcout << "Path: " << hadesmem::GetPath(*process) << "\n"; std::wcout << "WoW64: " << (hadesmem::IsWoW64(*process) ? "Yes" : "No") << "\n"; DumpModules(*process); DumpRegions(*process); } // TODO: Cleanup. void DumpFile(boost::filesystem::path const& path) { std::ifstream file(path.c_str(), std::ios::binary | std::ios::ate); if (!file) { std::wcout << "\nFailed to open file.\n"; return; } std::streampos const size = file.tellg(); if (!size || size < 0) { std::wcout << "\nEmpty or invalid file.\n"; return; } if (!file.seekg(0)) { std::wcout << "\nWARNING! Seeking to beginning of file failed.\n"; return; } // Pick some arbitrary maximum size // TODO: Fix this. Ideally we should only peek the first N bytes (however // big the PE headers are) and check if it's a valid target or not, then read // the rest of the file. if (static_cast<long long>(size) > 0x40000000LL) // 1GB { std::wcout << "\nFile too big.\n"; return; } // TODO: Fix all the unsafe integer downcasting. std::vector<char> buf(static_cast<std::size_t>(size)); if (!file.read(buf.data(), static_cast<std::streamsize>(size))) { std::wcout << "\nWARNING! Failed to read file data.\n"; return; } if (buf.size() != static_cast<std::size_t>(size)) { std::wcout << "\nWARNING! Buffer size does not match file size.\n"; return; } hadesmem::Process const process(GetCurrentProcessId()); try { hadesmem::PeFile const pe_file(process, buf.data(), hadesmem::PeFileType::Data); hadesmem::NtHeaders const nt_hdr(process, pe_file); #if defined(HADESMEM_ARCH_X86) if (nt_hdr.GetMachine() != IMAGE_FILE_MACHINE_I386) #elif defined(HADESMEM_ARCH_X64) if (nt_hdr.GetMachine() != IMAGE_FILE_MACHINE_AMD64) #else #error [HadesMem] Unsupported architecture. #endif { return; } } catch (std::exception const& /*e*/) { return; } DumpExports(process, buf.data(), hadesmem::PeFileType::Data); DumpImports(process, buf.data(), hadesmem::PeFileType::Data); } // Doing directory recursion 'manually' because recursive_directory_iterator // throws on increment, even when you construct it as no-throw. void DumpDir(boost::filesystem::path const& path) { std::wcout << "\nEntering dir: " << path << ".\n"; boost::system::error_code ec; boost::filesystem::directory_iterator iter(path, ec); boost::filesystem::directory_iterator end; while (iter != end && !ec); { auto const& cur_path = *iter; std::wcout << "\nCurrent path: " << cur_path << ".\n"; if (boost::filesystem::is_directory(cur_path) && !boost::filesystem::is_symlink(cur_path)) { DumpDir(cur_path); } if (boost::filesystem::is_regular_file(cur_path)) { DumpFile(cur_path); } ++iter; } } } int main(int /*argc*/, char* /*argv*/[]) { try { hadesmem::detail::DisableUserModeCallbackExceptionFilter(); hadesmem::detail::EnableCrtDebugFlags(); hadesmem::detail::EnableTerminationOnHeapCorruption(); hadesmem::detail::EnableBottomUpRand(); hadesmem::detail::ImbueAllDefault(); std::cout << "HadesMem Dumper\n"; boost::program_options::options_description opts_desc( "General options"); opts_desc.add_options() ("help", "produce help message") ("pid", boost::program_options::value<DWORD>(), "process id") ; std::vector<std::wstring> const args = boost::program_options:: split_winmain(GetCommandLine()); boost::program_options::variables_map var_map; boost::program_options::store(boost::program_options::wcommand_line_parser( args).options(opts_desc).run(), var_map); boost::program_options::notify(var_map); if (var_map.count("help")) { std::cout << '\n' << opts_desc << '\n'; return 1; } DWORD pid = 0; if (var_map.count("pid")) { pid = var_map["pid"].as<DWORD>(); } try { hadesmem::GetSeDebugPrivilege(); std::wcout << "\nAcquired SeDebugPrivilege.\n"; } catch (std::exception const& /*e*/) { std::wcout << "\nFailed to acquire SeDebugPrivilege.\n"; } if (pid) { hadesmem::ProcessList const processes; auto iter = std::find_if(std::begin(processes), std::end(processes), [pid] (hadesmem::ProcessEntry const& process_entry) { return process_entry.GetId() == pid; }); if (iter != std::end(processes)) { DumpProcessEntry(*iter); } else { HADESMEM_THROW_EXCEPTION(hadesmem::Error() << hadesmem::ErrorString("Failed to find requested process.")); } } else { std::wcout << "\nProcesses:\n"; hadesmem::ProcessList const processes; for (auto const& process_entry : processes) { DumpProcessEntry(process_entry); } std::wcout << "\nFiles:\n"; boost::filesystem::path const self_path = hadesmem::detail::GetSelfPath(); boost::filesystem::path const root_dir = self_path.root_path(); DumpDir(root_dir); } return 0; } catch (std::exception const& e) { std::cerr << "\nError!\n"; std::cerr << boost::diagnostic_information(e) << '\n'; return 1; } } <|endoftext|>
<commit_before>/* Copyright (C) 2004 by Jorrit Tyberghein (C) 2004 by Frank Richter This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "cssysdef.h" #include "csutil/databuf.h" #include "csutil/scanstr.h" #include "csutil/stringquote.h" #include "csutil/util.h" #include "csutil/xmltiny.h" #include "csgfx/shaderexp.h" #include "imap/services.h" #include "iutil/verbositymanager.h" #include "iutil/vfs.h" #include "ivaria/reporter.h" #include "csplugincommon/shader/shaderprogram.h" void csShaderProgram::ProgramParam::SetValue (float val) { var.AttachNew (new csShaderVariable (CS::InvalidShaderVarStringID)); var->SetValue (val); valid = true; } void csShaderProgram::ProgramParam::SetValue (const csVector4& val) { var.AttachNew (new csShaderVariable (CS::InvalidShaderVarStringID)); var->SetValue (val); valid = true; } //--------------------------------------------------------------------------- CS_LEAKGUARD_IMPLEMENT (csShaderProgram); csShaderProgram::csShaderProgram (iObjectRegistry* objectReg) : scfImplementationType (this) { InitCommonTokens (commonTokens); csShaderProgram::objectReg = objectReg; synsrv = csQueryRegistry<iSyntaxService> (objectReg); stringsSvName = csQueryRegistryTagInterface<iShaderVarStringSet> (objectReg, "crystalspace.shader.variablenameset"); csRef<iVerbosityManager> verbosemgr ( csQueryRegistry<iVerbosityManager> (objectReg)); if (verbosemgr) doVerbose = verbosemgr->Enabled("renderer.shader"); else doVerbose = false; } csShaderProgram::~csShaderProgram () { } bool csShaderProgram::ProgramParamParser::ParseProgramParam ( iDocumentNode* node, ProgramParam& param, uint types) { const char* type = node->GetAttributeValue ("type"); if (type == 0) { synsrv->Report ("crystalspace.graphics3d.shader.common", CS_REPORTER_SEVERITY_WARNING, node, "No %s attribute", CS::Quote::Single ("type")); return false; } // Var for static data csRef<csShaderVariable> var; var.AttachNew (new csShaderVariable (CS::InvalidShaderVarStringID)); ProgramParamType paramType = ParamInvalid; if (strcmp (type, "shadervar") == 0) { const char* value = node->GetContentsValue(); if (!value) { synsrv->Report ("crystalspace.graphics3d.shader.common", CS_REPORTER_SEVERITY_WARNING, node, "Node has no contents"); return false; } CS::Graphics::ShaderVarNameParser nameParse (value); param.name = stringsSvName->Request (nameParse.GetShaderVarName()); for (size_t n = 0; n < nameParse.GetIndexNum(); n++) { param.indices.Push (nameParse.GetIndexValue (n)); } param.valid = true; return true; } else if (strcmp (type, "int") == 0) { paramType = ParamInt; } else if (strcmp (type, "float") == 0) { paramType = ParamFloat; } else if (strcmp (type, "vector2") == 0) { paramType = ParamVector2; } else if (strcmp (type, "vector3") == 0) { paramType = ParamVector3; } else if (strcmp (type, "vector4") == 0) { paramType = ParamVector4; } else if (strcmp (type, "matrix") == 0) { paramType = ParamMatrix; } else if (strcmp (type, "transform") == 0) { paramType = ParamTransform; } else if ((strcmp (type, "expression") == 0) || (strcmp (type, "expr") == 0)) { // Parse exp and save it csRef<iShaderVariableAccessor> acc = synsrv->ParseShaderVarExpr (node); var->SetAccessor (acc); param.var = var; param.valid = true; return true; } else if (strcmp (type, "array") == 0) { csArray<ProgramParam> allParams; ProgramParam tmpParam; csRef<iDocumentNodeIterator> it = node->GetNodes (); while (it->HasNext ()) { csRef<iDocumentNode> child = it->Next (); ParseProgramParam (child, tmpParam, types & 0x3F); allParams.Push (tmpParam); } //Save the params var->SetType (csShaderVariable::ARRAY); var->SetArraySize (allParams.GetSize ()); for (uint i = 0; i < allParams.GetSize (); i++) { var->SetArrayElement (i, allParams[i].var); } paramType = ParamArray; } else { synsrv->Report ("crystalspace.graphics3d.shader.common", CS_REPORTER_SEVERITY_WARNING, node, "Unknown type %s", CS::Quote::Single (type)); return false; } if (!(types & paramType)) { synsrv->Report ("crystalspace.graphics3d.shader.common", CS_REPORTER_SEVERITY_WARNING, node, "Type %s not supported by this parameter", CS::Quote::Single (type)); return false; } const uint directValueTypes = ParamInt | ParamFloat | ParamVector2 | ParamVector3 | ParamVector4 | ParamMatrix | ParamTransform; switch (paramType & directValueTypes) { case ParamInvalid: return false; break; case ParamInt: { int x = node->GetContentsValueAsInt (); var->SetValue (x); } break; case ParamFloat: { float x = node->GetContentsValueAsFloat (); var->SetValue (x); } break; case ParamVector2: { float x, y; const char* value = node->GetContentsValue(); if (!value) { synsrv->Report ("crystalspace.graphics3d.shader.common", CS_REPORTER_SEVERITY_WARNING, node, "Node has no contents"); return false; } if (csScanStr (value, "%f,%f", &x, &y) != 2) { synsrv->Report ("crystalspace.graphics3d.shader.common", CS_REPORTER_SEVERITY_WARNING, node, "Couldn't parse vector2 %s", CS::Quote::Single (value)); return false; } var->SetValue (csVector2 (x,y)); } break; case ParamVector3: { float x, y, z; const char* value = node->GetContentsValue(); if (!value) { synsrv->Report ("crystalspace.graphics3d.shader.common", CS_REPORTER_SEVERITY_WARNING, node, "Node has no contents"); return false; } if (csScanStr (value, "%f,%f,%f", &x, &y, &z) != 3) { synsrv->Report ("crystalspace.graphics3d.shader.common", CS_REPORTER_SEVERITY_WARNING, node, "Couldn't parse vector3 %s", CS::Quote::Single (value)); return false; } var->SetValue (csVector3 (x,y,z)); } break; case ParamVector4: { float x, y, z, w; const char* value = node->GetContentsValue(); if (!value) { synsrv->Report ("crystalspace.graphics3d.shader.common", CS_REPORTER_SEVERITY_WARNING, node, "Node has no contents"); return false; } if (csScanStr (value, "%f,%f,%f,%f", &x, &y, &z, &w) != 4) { synsrv->Report ("crystalspace.graphics3d.shader.common", CS_REPORTER_SEVERITY_WARNING, node, "Couldn't parse vector4 %s", CS::Quote::Single (value)); return false; } var->SetValue (csVector4 (x,y,z,w)); } break; case ParamMatrix: { csMatrix3 matrix; if (!synsrv->ParseMatrix (node, matrix)) return false; var->SetValue (matrix); } break; case ParamTransform: { csReversibleTransform t; csRef<iDocumentNode> matrix_node = node->GetNode ("matrix"); if (matrix_node) { csMatrix3 m; if (!synsrv->ParseMatrix (matrix_node, m)) return false; t.SetT2O (m); } csRef<iDocumentNode> vector_node = node->GetNode ("v"); if (vector_node) { csVector3 v; if (!synsrv->ParseVector (vector_node, v)) return false; t.SetOrigin (v); } var->SetValue (t); } break; } param.var = var; param.valid = true; return true; } bool csShaderProgram::ParseCommon (iDocumentNode* child) { const char* value = child->GetValue (); csStringID id = commonTokens.Request (value); switch (id) { case XMLTOKEN_VARIABLEMAP: { //@@ REWRITE const char* destname = child->GetAttributeValue ("destination"); if (!destname) { synsrv->Report ("crystalspace.graphics3d.shader.common", CS_REPORTER_SEVERITY_WARNING, child, "<variablemap> has no %s attribute", CS::Quote::Single ("destination")); return false; } const char* varname = child->GetAttributeValue ("variable"); if (!varname) { // "New style" variable mapping VariableMapEntry vme (CS::InvalidShaderVarStringID, destname); if (!ParseProgramParam (child, vme.mappingParam, ParamInt | ParamFloat | ParamVector2 | ParamVector3 | ParamVector4)) return false; variablemap.Push (vme); } else { // "Classic" variable mapping CS::Graphics::ShaderVarNameParser nameParse (varname); VariableMapEntry vme ( stringsSvName->Request (nameParse.GetShaderVarName()), destname); for (size_t n = 0; n < nameParse.GetIndexNum(); n++) { vme.mappingParam.indices.Push (nameParse.GetIndexValue (n)); } variablemap.Push (vme); } } break; case XMLTOKEN_PROGRAM: { const char* filename = child->GetAttributeValue ("file"); if (filename != 0) { programFileName = filename; csRef<iVFS> vfs = csQueryRegistry<iVFS> (objectReg); csRef<iFile> file = vfs->Open (filename, VFS_FILE_READ); if (!file.IsValid()) { synsrv->Report ("crystalspace.graphics3d.shader.common", CS_REPORTER_SEVERITY_WARNING, child, "Could not open %s", CS::Quote::Single (filename)); return false; } programFile = file; } else programNode = child; } break; case XMLTOKEN_DESCRIPTION: description = child->GetContentsValue(); break; default: synsrv->ReportBadToken (child); return false; } return true; } #include "csutil/custom_new_disable.h" iDocumentNode* csShaderProgram::GetProgramNode () { if (programNode.IsValid ()) return programNode; if (programFile.IsValid ()) { csRef<iDocumentSystem> docsys = csQueryRegistry<iDocumentSystem> (objectReg); if (!docsys) docsys.AttachNew (new csTinyDocumentSystem ()); csRef<iDocument> doc (docsys->CreateDocument ()); const char* err = doc->Parse (programFile, true); if (err != 0) { csReport (objectReg, CS_REPORTER_SEVERITY_WARNING, "crystalspace.graphics3d.shader.common", "Error parsing %s: %s", programFileName.GetData(), err); return 0; } programNode = doc->GetRoot (); programFile = 0; return programNode; } return 0; } csPtr<iDataBuffer> csShaderProgram::GetProgramData () { if (programFile.IsValid()) { return programFile->GetAllData (); } if (programNode.IsValid()) { char* data = CS::StrDup (programNode->GetContentsValue ()); csRef<iDataBuffer> newbuff; newbuff.AttachNew (new CS::DataBuffer<> (data, data ? strlen (data) : 0)); return csPtr<iDataBuffer> (newbuff); } return 0; } #include "csutil/custom_new_enable.h" void csShaderProgram::DumpProgramInfo (csString& output) { output << "Program description: " << (description.Length () ? description.GetData () : "<none>") << "\n"; output << "Program file name: " << programFileName << "\n"; } void csShaderProgram::DumpVariableMappings (csString& output) { for (size_t v = 0; v < variablemap.GetSize (); v++) { const VariableMapEntry& vme = variablemap[v]; output << stringsSvName->Request (vme.name); output << '(' << vme.name << ") -> "; output << vme.destination << ' '; output << vme.userVal << ' '; output << '\n'; } } void csShaderProgram::GetUsedShaderVarsFromVariableMappings ( csBitArray& bits) const { for (size_t i = 0; i < variablemap.GetSize(); i++) { TryAddUsedShaderVarName (variablemap[i].name, bits); } } void csShaderProgram::GetUsedShaderVars (csBitArray& bits) const { GetUsedShaderVarsFromVariableMappings (bits); } iShaderProgram::CacheLoadResult csShaderProgram::LoadFromCache ( iHierarchicalCache* cache, iBase* previous, iDocumentNode* programNode, csRef<iString>* failReason, csRef<iString>* tag) { csRef<iShaderDestinationResolver> resolver = scfQueryInterfaceSafe<iShaderDestinationResolver> (previous); if (Load (resolver, programNode) && Compile (0, tag)) return loadSuccessShaderValid; else return loadSuccessShaderInvalid; } <commit_msg>- Made sure that program file/node are invalidated when parsing subsequent times.<commit_after>/* Copyright (C) 2004 by Jorrit Tyberghein (C) 2004 by Frank Richter This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "cssysdef.h" #include "csutil/databuf.h" #include "csutil/scanstr.h" #include "csutil/stringquote.h" #include "csutil/util.h" #include "csutil/xmltiny.h" #include "csgfx/shaderexp.h" #include "imap/services.h" #include "iutil/verbositymanager.h" #include "iutil/vfs.h" #include "ivaria/reporter.h" #include "csplugincommon/shader/shaderprogram.h" void csShaderProgram::ProgramParam::SetValue (float val) { var.AttachNew (new csShaderVariable (CS::InvalidShaderVarStringID)); var->SetValue (val); valid = true; } void csShaderProgram::ProgramParam::SetValue (const csVector4& val) { var.AttachNew (new csShaderVariable (CS::InvalidShaderVarStringID)); var->SetValue (val); valid = true; } //--------------------------------------------------------------------------- CS_LEAKGUARD_IMPLEMENT (csShaderProgram); csShaderProgram::csShaderProgram (iObjectRegistry* objectReg) : scfImplementationType (this) { InitCommonTokens (commonTokens); csShaderProgram::objectReg = objectReg; synsrv = csQueryRegistry<iSyntaxService> (objectReg); stringsSvName = csQueryRegistryTagInterface<iShaderVarStringSet> (objectReg, "crystalspace.shader.variablenameset"); csRef<iVerbosityManager> verbosemgr ( csQueryRegistry<iVerbosityManager> (objectReg)); if (verbosemgr) doVerbose = verbosemgr->Enabled("renderer.shader"); else doVerbose = false; } csShaderProgram::~csShaderProgram () { } bool csShaderProgram::ProgramParamParser::ParseProgramParam ( iDocumentNode* node, ProgramParam& param, uint types) { const char* type = node->GetAttributeValue ("type"); if (type == 0) { synsrv->Report ("crystalspace.graphics3d.shader.common", CS_REPORTER_SEVERITY_WARNING, node, "No %s attribute", CS::Quote::Single ("type")); return false; } // Var for static data csRef<csShaderVariable> var; var.AttachNew (new csShaderVariable (CS::InvalidShaderVarStringID)); ProgramParamType paramType = ParamInvalid; if (strcmp (type, "shadervar") == 0) { const char* value = node->GetContentsValue(); if (!value) { synsrv->Report ("crystalspace.graphics3d.shader.common", CS_REPORTER_SEVERITY_WARNING, node, "Node has no contents"); return false; } CS::Graphics::ShaderVarNameParser nameParse (value); param.name = stringsSvName->Request (nameParse.GetShaderVarName()); for (size_t n = 0; n < nameParse.GetIndexNum(); n++) { param.indices.Push (nameParse.GetIndexValue (n)); } param.valid = true; return true; } else if (strcmp (type, "int") == 0) { paramType = ParamInt; } else if (strcmp (type, "float") == 0) { paramType = ParamFloat; } else if (strcmp (type, "vector2") == 0) { paramType = ParamVector2; } else if (strcmp (type, "vector3") == 0) { paramType = ParamVector3; } else if (strcmp (type, "vector4") == 0) { paramType = ParamVector4; } else if (strcmp (type, "matrix") == 0) { paramType = ParamMatrix; } else if (strcmp (type, "transform") == 0) { paramType = ParamTransform; } else if ((strcmp (type, "expression") == 0) || (strcmp (type, "expr") == 0)) { // Parse exp and save it csRef<iShaderVariableAccessor> acc = synsrv->ParseShaderVarExpr (node); var->SetAccessor (acc); param.var = var; param.valid = true; return true; } else if (strcmp (type, "array") == 0) { csArray<ProgramParam> allParams; ProgramParam tmpParam; csRef<iDocumentNodeIterator> it = node->GetNodes (); while (it->HasNext ()) { csRef<iDocumentNode> child = it->Next (); ParseProgramParam (child, tmpParam, types & 0x3F); allParams.Push (tmpParam); } //Save the params var->SetType (csShaderVariable::ARRAY); var->SetArraySize (allParams.GetSize ()); for (uint i = 0; i < allParams.GetSize (); i++) { var->SetArrayElement (i, allParams[i].var); } paramType = ParamArray; } else { synsrv->Report ("crystalspace.graphics3d.shader.common", CS_REPORTER_SEVERITY_WARNING, node, "Unknown type %s", CS::Quote::Single (type)); return false; } if (!(types & paramType)) { synsrv->Report ("crystalspace.graphics3d.shader.common", CS_REPORTER_SEVERITY_WARNING, node, "Type %s not supported by this parameter", CS::Quote::Single (type)); return false; } const uint directValueTypes = ParamInt | ParamFloat | ParamVector2 | ParamVector3 | ParamVector4 | ParamMatrix | ParamTransform; switch (paramType & directValueTypes) { case ParamInvalid: return false; break; case ParamInt: { int x = node->GetContentsValueAsInt (); var->SetValue (x); } break; case ParamFloat: { float x = node->GetContentsValueAsFloat (); var->SetValue (x); } break; case ParamVector2: { float x, y; const char* value = node->GetContentsValue(); if (!value) { synsrv->Report ("crystalspace.graphics3d.shader.common", CS_REPORTER_SEVERITY_WARNING, node, "Node has no contents"); return false; } if (csScanStr (value, "%f,%f", &x, &y) != 2) { synsrv->Report ("crystalspace.graphics3d.shader.common", CS_REPORTER_SEVERITY_WARNING, node, "Couldn't parse vector2 %s", CS::Quote::Single (value)); return false; } var->SetValue (csVector2 (x,y)); } break; case ParamVector3: { float x, y, z; const char* value = node->GetContentsValue(); if (!value) { synsrv->Report ("crystalspace.graphics3d.shader.common", CS_REPORTER_SEVERITY_WARNING, node, "Node has no contents"); return false; } if (csScanStr (value, "%f,%f,%f", &x, &y, &z) != 3) { synsrv->Report ("crystalspace.graphics3d.shader.common", CS_REPORTER_SEVERITY_WARNING, node, "Couldn't parse vector3 %s", CS::Quote::Single (value)); return false; } var->SetValue (csVector3 (x,y,z)); } break; case ParamVector4: { float x, y, z, w; const char* value = node->GetContentsValue(); if (!value) { synsrv->Report ("crystalspace.graphics3d.shader.common", CS_REPORTER_SEVERITY_WARNING, node, "Node has no contents"); return false; } if (csScanStr (value, "%f,%f,%f,%f", &x, &y, &z, &w) != 4) { synsrv->Report ("crystalspace.graphics3d.shader.common", CS_REPORTER_SEVERITY_WARNING, node, "Couldn't parse vector4 %s", CS::Quote::Single (value)); return false; } var->SetValue (csVector4 (x,y,z,w)); } break; case ParamMatrix: { csMatrix3 matrix; if (!synsrv->ParseMatrix (node, matrix)) return false; var->SetValue (matrix); } break; case ParamTransform: { csReversibleTransform t; csRef<iDocumentNode> matrix_node = node->GetNode ("matrix"); if (matrix_node) { csMatrix3 m; if (!synsrv->ParseMatrix (matrix_node, m)) return false; t.SetT2O (m); } csRef<iDocumentNode> vector_node = node->GetNode ("v"); if (vector_node) { csVector3 v; if (!synsrv->ParseVector (vector_node, v)) return false; t.SetOrigin (v); } var->SetValue (t); } break; } param.var = var; param.valid = true; return true; } bool csShaderProgram::ParseCommon (iDocumentNode* child) { const char* value = child->GetValue (); csStringID id = commonTokens.Request (value); switch (id) { case XMLTOKEN_VARIABLEMAP: { //@@ REWRITE const char* destname = child->GetAttributeValue ("destination"); if (!destname) { synsrv->Report ("crystalspace.graphics3d.shader.common", CS_REPORTER_SEVERITY_WARNING, child, "<variablemap> has no %s attribute", CS::Quote::Single ("destination")); return false; } const char* varname = child->GetAttributeValue ("variable"); if (!varname) { // "New style" variable mapping VariableMapEntry vme (CS::InvalidShaderVarStringID, destname); if (!ParseProgramParam (child, vme.mappingParam, ParamInt | ParamFloat | ParamVector2 | ParamVector3 | ParamVector4)) return false; variablemap.Push (vme); } else { // "Classic" variable mapping CS::Graphics::ShaderVarNameParser nameParse (varname); VariableMapEntry vme ( stringsSvName->Request (nameParse.GetShaderVarName()), destname); for (size_t n = 0; n < nameParse.GetIndexNum(); n++) { vme.mappingParam.indices.Push (nameParse.GetIndexValue (n)); } variablemap.Push (vme); } } break; case XMLTOKEN_PROGRAM: { const char* filename = child->GetAttributeValue ("file"); if (filename != 0) { programFileName = filename; csRef<iVFS> vfs = csQueryRegistry<iVFS> (objectReg); csRef<iFile> file = vfs->Open (filename, VFS_FILE_READ); if (!file.IsValid()) { synsrv->Report ("crystalspace.graphics3d.shader.common", CS_REPORTER_SEVERITY_WARNING, child, "Could not open %s", CS::Quote::Single (filename)); return false; } programFile = file; programNode.Invalidate (); } else { programNode = child; programFile.Invalidate (); } } break; case XMLTOKEN_DESCRIPTION: description = child->GetContentsValue(); break; default: synsrv->ReportBadToken (child); return false; } return true; } #include "csutil/custom_new_disable.h" iDocumentNode* csShaderProgram::GetProgramNode () { if (programNode.IsValid ()) return programNode; if (programFile.IsValid ()) { csRef<iDocumentSystem> docsys = csQueryRegistry<iDocumentSystem> (objectReg); if (!docsys) docsys.AttachNew (new csTinyDocumentSystem ()); csRef<iDocument> doc (docsys->CreateDocument ()); const char* err = doc->Parse (programFile, true); if (err != 0) { csReport (objectReg, CS_REPORTER_SEVERITY_WARNING, "crystalspace.graphics3d.shader.common", "Error parsing %s: %s", programFileName.GetData(), err); return 0; } programNode = doc->GetRoot (); programFile = 0; return programNode; } return 0; } csPtr<iDataBuffer> csShaderProgram::GetProgramData () { if (programFile.IsValid()) { return programFile->GetAllData (); } if (programNode.IsValid()) { char* data = CS::StrDup (programNode->GetContentsValue ()); csRef<iDataBuffer> newbuff; newbuff.AttachNew (new CS::DataBuffer<> (data, data ? strlen (data) : 0)); return csPtr<iDataBuffer> (newbuff); } return 0; } #include "csutil/custom_new_enable.h" void csShaderProgram::DumpProgramInfo (csString& output) { output << "Program description: " << (description.Length () ? description.GetData () : "<none>") << "\n"; output << "Program file name: " << programFileName << "\n"; } void csShaderProgram::DumpVariableMappings (csString& output) { for (size_t v = 0; v < variablemap.GetSize (); v++) { const VariableMapEntry& vme = variablemap[v]; output << stringsSvName->Request (vme.name); output << '(' << vme.name << ") -> "; output << vme.destination << ' '; output << vme.userVal << ' '; output << '\n'; } } void csShaderProgram::GetUsedShaderVarsFromVariableMappings ( csBitArray& bits) const { for (size_t i = 0; i < variablemap.GetSize(); i++) { TryAddUsedShaderVarName (variablemap[i].name, bits); } } void csShaderProgram::GetUsedShaderVars (csBitArray& bits) const { GetUsedShaderVarsFromVariableMappings (bits); } iShaderProgram::CacheLoadResult csShaderProgram::LoadFromCache ( iHierarchicalCache* cache, iBase* previous, iDocumentNode* programNode, csRef<iString>* failReason, csRef<iString>* tag) { csRef<iShaderDestinationResolver> resolver = scfQueryInterfaceSafe<iShaderDestinationResolver> (previous); if (Load (resolver, programNode) && Compile (0, tag)) return loadSuccessShaderValid; else return loadSuccessShaderInvalid; } <|endoftext|>
<commit_before>/* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 "mbed.h" #include "nRF51822n.h" #include "TMP102.h" nRF51822n nrf; /* BLE radio driver */ DigitalOut led1(LED1); DigitalOut led2(LED2); Serial pc(USBTX,USBRX); TMP102 healthThemometer(p22, p20, 0x90); /* Device Information service */ uint8_t manufacturerName[4] = { 'm', 'b', 'e', 'd' }; GattService deviceInformationService ( GattService::UUID_DEVICE_INFORMATION_SERVICE ); GattCharacteristic deviceManufacturer ( GattCharacteristic::UUID_MANUFACTURER_NAME_STRING_CHAR, sizeof(manufacturerName), sizeof(manufacturerName), GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_READ); /* Battery Level Service */ uint8_t batt = 100; /* Battery level */ uint8_t read_batt = 0; /* Variable to hold battery level reads */ GattService battService ( GattService::UUID_BATTERY_SERVICE ); GattCharacteristic battLevel ( GattCharacteristic::UUID_BATTERY_LEVEL_CHAR, 1, 1, GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY | GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_READ); /* Health Thermometer Service */ uint8_t thermTempPayload[5] = { 0, 0, 0, 0, 0 }; GattService thermService (GattService::UUID_HEALTH_THERMOMETER_SERVICE); GattCharacteristic thermTemp (GattCharacteristic::UUID_TEMPERATURE_MEASUREMENT_CHAR, 5, 5, GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_INDICATE); /* Advertising data and parameters */ GapAdvertisingData advData; GapAdvertisingData scanResponse; GapAdvertisingParams advParams ( GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED ); uint16_t uuid16_list[] = { GattService::UUID_BATTERY_SERVICE, GattService::UUID_DEVICE_INFORMATION_SERVICE, GattService::UUID_HEALTH_THERMOMETER_SERVICE }; uint32_t quick_ieee11073_from_float(float temperature); void updateServiceValues(void); /**************************************************************************/ /*! @brief This custom class can be used to override any GapEvents that you are interested in handling on an application level. */ /**************************************************************************/ class GapEventHandler : public GapEvents { virtual void onTimeout(void) { pc.printf("Advertising Timeout!\n\r"); // Restart the advertising process with a much slower interval, // only start advertising again after a button press, etc. } virtual void onConnected(void) { pc.printf("Connected!\n\r"); } virtual void onDisconnected(void) { pc.printf("Disconnected!\n\r"); pc.printf("Restarting the advertising process\n\r"); nrf.getGap().startAdvertising(advParams); } }; /**************************************************************************/ /*! @brief This custom class can be used to override any GattServerEvents that you are interested in handling on an application level. */ /**************************************************************************/ class GattServerEventHandler : public GattServerEvents { //virtual void onDataSent(void) {} //virtual void onDataWritten(void) {} virtual void onUpdatesEnabled(uint16_t charHandle) { if (charHandle == thermTemp.handle) { pc.printf("Temperature indication enabled\n\r"); } } virtual void onUpdatesDisabled(uint16_t charHandle) { if (charHandle == thermTemp.handle) { pc.printf("Temperature indication disabled\n\r"); } } virtual void onConfirmationReceived(uint16_t charHandle) { if (charHandle == thermTemp.handle) { pc.printf("Temperature indication received\n\r"); } } }; /**************************************************************************/ /*! @brief Program entry point */ /**************************************************************************/ int main(void) { pc.baud(115200); /* Setup blinky: led1 is toggled in main, led2 is toggled via Ticker */ led1=1; led2=1; /* Setup the local GAP/GATT event handlers */ nrf.getGap().setEventHandler(new GapEventHandler()); nrf.getGattServer().setEventHandler(new GattServerEventHandler()); /* Initialise the nRF51822 */ pc.printf("Initialising the nRF51822\n\r"); nrf.init(); /* Make sure we get a clean start */ nrf.reset(); /* Add BLE-Only flag and complete service list to the advertising data */ advData.addFlags(GapAdvertisingData::BREDR_NOT_SUPPORTED); advData.addData(GapAdvertisingData::COMPLETE_LIST_16BIT_SERVICE_IDS, (uint8_t*)uuid16_list, sizeof(uuid16_list)); advData.addAppearance(GapAdvertisingData::GENERIC_THERMOMETER); nrf.getGap().setAdvertisingData(advData, scanResponse); /* Add the Battery Level service */ battService.addCharacteristic(battLevel); nrf.getGattServer().addService(battService); /* Add the Device Information service */ deviceInformationService.addCharacteristic(deviceManufacturer); nrf.getGattServer().addService(deviceInformationService); /* Health Thermometer Service */ thermService.addCharacteristic(thermTemp); nrf.getGattServer().addService(thermService); /* Start advertising (make sure you've added all your data first) */ nrf.getGap().startAdvertising(advParams); /* Now that we're live, update the battery level characteristic, and */ /* change the device manufacturer characteristic to 'mbed' */ nrf.getGattServer().updateValue(battLevel.handle, (uint8_t*)&batt, sizeof(batt)); nrf.getGattServer().updateValue(deviceManufacturer.handle, manufacturerName, sizeof(manufacturerName)); nrf.getGattServer().updateValue(thermTemp.handle, thermTempPayload, sizeof(thermTempPayload)); for (;;) { wait(1); updateServiceValues(); } } /**************************************************************************/ /*! @brief Ticker callback to switch led2 state */ /**************************************************************************/ void updateServiceValues(void) { /* Toggle the LED */ led1 = !led1; /* Update battery level */ nrf.getGattServer().updateValue(battLevel.handle, (uint8_t*)&batt, sizeof(batt)); /* Update the temperature */ float temperature = healthThemometer.read(); uint32_t temp_ieee11073 = quick_ieee11073_from_float(temperature); memcpy(thermTempPayload+1, &temp_ieee11073, 4); nrf.getGattServer().updateValue(thermTemp.handle, thermTempPayload, sizeof(thermTempPayload)); printf("Temperature: %f Celsius\r\n", temperature); } /** * @brief A very quick conversion between a float temperature and 11073-20601 FLOAT-Type. * @param temperature The temperature as a float. * @return The temperature in 11073-20601 FLOAT-Type format. */ uint32_t quick_ieee11073_from_float(float temperature) { uint8_t exponent = 0xFF; //exponent is -1 uint32_t mantissa = (uint32_t)(temperature*10); return ( ((uint32_t)exponent) << 24) | mantissa; } <commit_msg>Update Health_Thermometer example to latest revision<commit_after>/* mbed Microcontroller Library * Copyright (c) 2006-2014 ARM Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 "mbed.h" #include "TMP102.h" #include "nRF51822n.h" nRF51822n nrf; /* BLE radio driver */ TMP102 healthThemometer(p22, p20, 0x90); /* The TMP102 connected to our board */ /* LEDs for indication: */ DigitalOut oneSecondLed(LED1); /* LED1 is toggled every second. */ DigitalOut advertisingStateLed(LED2); /* LED2 is on when we are advertising, otherwise off. */ /* Health Thermometer Service */ uint8_t thermTempPayload[5] = { 0, 0, 0, 0, 0 }; GattService thermService (GattService::UUID_HEALTH_THERMOMETER_SERVICE); GattCharacteristic thermTemp (GattCharacteristic::UUID_TEMPERATURE_MEASUREMENT_CHAR, 5, 5, GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_INDICATE); /* Battery Level Service */ uint8_t batt = 100; /* Battery level */ uint8_t read_batt = 0; /* Variable to hold battery level reads */ GattService battService ( GattService::UUID_BATTERY_SERVICE ); GattCharacteristic battLevel ( GattCharacteristic::UUID_BATTERY_LEVEL_CHAR, 1, 1, GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY | GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_READ); /* Advertising data and parameters */ GapAdvertisingData advData; GapAdvertisingData scanResponse; GapAdvertisingParams advParams ( GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED ); uint16_t uuid16_list[] = {GattService::UUID_HEALTH_THERMOMETER_SERVICE, GattService::UUID_BATTERY_SERVICE}; uint32_t quick_ieee11073_from_float(float temperature); void updateServiceValues(void); /**************************************************************************/ /*! @brief This custom class can be used to override any GapEvents that you are interested in handling on an application level. */ /**************************************************************************/ class GapEventHandler : public GapEvents { //virtual void onTimeout(void) {} virtual void onConnected(void) { advertisingStateLed = 0; } /* When a client device disconnects we need to start advertising again. */ virtual void onDisconnected(void) { nrf.getGap().startAdvertising(advParams); advertisingStateLed = 1; } }; /**************************************************************************/ /*! @brief Program entry point */ /**************************************************************************/ int main(void) { /* Setup blinky led */ oneSecondLed=1; /* Setup an event handler for GAP events i.e. Client/Server connection events. */ nrf.getGap().setEventHandler(new GapEventHandler()); /* Initialise the nRF51822 */ nrf.init(); /* Make sure we get a clean start */ nrf.reset(); /* Add BLE-Only flag and complete service list to the advertising data */ advData.addFlags(GapAdvertisingData::BREDR_NOT_SUPPORTED); advData.addData(GapAdvertisingData::COMPLETE_LIST_16BIT_SERVICE_IDS, (uint8_t*)uuid16_list, sizeof(uuid16_list)); advData.addAppearance(GapAdvertisingData::GENERIC_THERMOMETER); nrf.getGap().setAdvertisingData(advData, scanResponse); /* Health Thermometer Service */ thermService.addCharacteristic(thermTemp); nrf.getGattServer().addService(thermService); /* Add the Battery Level service */ battService.addCharacteristic(battLevel); nrf.getGattServer().addService(battService); /* Start advertising (make sure you've added all your data first) */ nrf.getGap().startAdvertising(advParams); advertisingStateLed = 1; for (;;) { /* Now that we're live, update the battery level & temperature characteristics */ updateServiceValues(); wait(1); } } /**************************************************************************/ /*! @brief Ticker callback to switch advertisingStateLed state */ /**************************************************************************/ void updateServiceValues(void) { /* Toggle the one second LEDs */ oneSecondLed = !oneSecondLed; /* Update battery level */ nrf.getGattServer().updateValue(battLevel.handle, (uint8_t*)&batt, sizeof(batt)); /* Decrement the battery level. */ batt <=50 ? batt=100 : batt--;; /* Update the temperature. Note that we need to convert to an ieee11073 format float. */ float temperature = healthThemometer.read(); uint32_t temp_ieee11073 = quick_ieee11073_from_float(temperature); memcpy(thermTempPayload+1, &temp_ieee11073, 4); nrf.getGattServer().updateValue(thermTemp.handle, thermTempPayload, sizeof(thermTempPayload)); } /** * @brief A very quick conversion between a float temperature and 11073-20601 FLOAT-Type. * @param temperature The temperature as a float. * @return The temperature in 11073-20601 FLOAT-Type format. */ uint32_t quick_ieee11073_from_float(float temperature) { uint8_t exponent = 0xFF; //exponent is -1 uint32_t mantissa = (uint32_t)(temperature*10); return ( ((uint32_t)exponent) << 24) | mantissa; } <|endoftext|>
<commit_before> #include <log4cplus/logger.h> #include <log4cplus/configurator.h> #include <log4cplus/helpers/loglog.h> #include <log4cplus/helpers/stringhelper.h> using namespace std; using namespace log4cplus; using namespace log4cplus::helpers; Logger log_1 = Logger::getInstance("test.log_1"); Logger log_2 = Logger::getInstance("test.log_2"); Logger log_3 = Logger::getInstance("test.log_3"); void printMsgs(Logger& logger) { LOG4CPLUS_TRACE_METHOD(logger, "printMsgs()"); LOG4CPLUS_DEBUG(logger, "printMsgs()"); LOG4CPLUS_INFO(logger, "printMsgs()"); LOG4CPLUS_WARN(logger, "printMsgs()"); LOG4CPLUS_ERROR(logger, "printMsgs()"); } int main() { cout << "Entering main()..." << endl; LogLog::getLogLog()->setInternalDebugging(true); Logger root = Logger::getRoot(); try { ConfigureAndWatchThread configureThread("log4cplus.properties", 5 * 1000); LOG4CPLUS_WARN(root, "Testing....") for(int i=0; i<100; ++i) { printMsgs(log_1); printMsgs(log_2); printMsgs(log_3); sleep(1); } } catch(...) { cout << "Exception..." << endl; LOG4CPLUS_FATAL(root, "Exception occured...") } cout << "Exiting main()..." << endl; return 0; } <commit_msg>Now specify the sleep() method to use.<commit_after> #include <log4cplus/logger.h> #include <log4cplus/configurator.h> #include <log4cplus/helpers/loglog.h> #include <log4cplus/helpers/stringhelper.h> using namespace std; using namespace log4cplus; using namespace log4cplus::helpers; Logger log_1 = Logger::getInstance("test.log_1"); Logger log_2 = Logger::getInstance("test.log_2"); Logger log_3 = Logger::getInstance("test.log_3"); void printMsgs(Logger& logger) { LOG4CPLUS_TRACE_METHOD(logger, "printMsgs()"); LOG4CPLUS_DEBUG(logger, "printMsgs()"); LOG4CPLUS_INFO(logger, "printMsgs()"); LOG4CPLUS_WARN(logger, "printMsgs()"); LOG4CPLUS_ERROR(logger, "printMsgs()"); } int main() { cout << "Entering main()..." << endl; LogLog::getLogLog()->setInternalDebugging(true); Logger root = Logger::getRoot(); try { ConfigureAndWatchThread configureThread("log4cplus.properties", 5 * 1000); LOG4CPLUS_WARN(root, "Testing....") for(int i=0; i<100; ++i) { printMsgs(log_1); printMsgs(log_2); printMsgs(log_3); log4cplus::helpers::sleep(1); } } catch(...) { cout << "Exception..." << endl; LOG4CPLUS_FATAL(root, "Exception occured...") } cout << "Exiting main()..." << endl; return 0; } <|endoftext|>
<commit_before>#include "slave.hpp" #include <stdint.h> #include "net_structs.hpp" #include "arch/linux/coroutines.hpp" namespace replication { // TODO unit test offsets slave_t::slave_t(store_t *internal_store, replication_config_t replication_config, failover_config_t failover_config) : internal_store(internal_store), replication_config(replication_config), failover_config(failover_config), conn(NULL), shutting_down(false), failover_script(failover_config.failover_script_path), timeout(INITIAL_TIMEOUT), timer_token(NULL), failover_reset_control(std::string("failover reset"), this), new_master_control(std::string("new master"), this) { coro_t::spawn(&run, this); } slave_t::~slave_t() { shutting_down = true; coro_t::move_to_thread(home_thread); kill_conn(); /* cancel the timer */ if(timer_token) cancel_timer(timer_token); } void slave_t::kill_conn() { struct : public message_parser_t::message_parser_shutdown_callback_t, public cond_t { void on_parser_shutdown() { pulse(); } } parser_shutdown_cb; { on_thread_t thread_switch(home_thread); if (!parser.shutdown(&parser_shutdown_cb)) parser_shutdown_cb.wait(); } { //on_thread_t scope on_thread_t thread_switch(get_num_threads() - 2); if (conn) { delete conn; conn = NULL; } } } store_t::get_result_t slave_t::get(store_key_t *key) { return internal_store->get(key); } store_t::get_result_t slave_t::get_cas(store_key_t *key, cas_t proposed_cas) { // TODO: ask joe why this used get(key) before (back when we did not have proposed_cas). return internal_store->get_cas(key, proposed_cas); } store_t::set_result_t slave_t::set(store_key_t *key, data_provider_t *data, mcflags_t flags, exptime_t exptime, cas_t proposed_cas) { if (respond_to_queries) return internal_store->set(key, data, flags, exptime, proposed_cas); else return store_t::sr_not_allowed; } store_t::set_result_t slave_t::add(store_key_t *key, data_provider_t *data, mcflags_t flags, exptime_t exptime, cas_t proposed_cas) { return internal_store->add(key, data, flags, exptime, proposed_cas); } store_t::set_result_t slave_t::replace(store_key_t *key, data_provider_t *data, mcflags_t flags, exptime_t exptime, cas_t proposed_cas) { if (respond_to_queries) return internal_store->replace(key, data, flags, exptime, proposed_cas); else return store_t::sr_not_allowed; } store_t::set_result_t slave_t::cas(store_key_t *key, data_provider_t *data, mcflags_t flags, exptime_t exptime, cas_t unique, cas_t proposed_cas) { if (respond_to_queries) return internal_store->cas(key, data, flags, exptime, unique, proposed_cas); else return store_t::sr_not_allowed; } store_t::incr_decr_result_t slave_t::incr(store_key_t *key, unsigned long long amount, cas_t proposed_cas) { if (respond_to_queries) return internal_store->incr(key, amount, proposed_cas); else return store_t::incr_decr_result_t::idr_not_allowed; } store_t::incr_decr_result_t slave_t::decr(store_key_t *key, unsigned long long amount, cas_t proposed_cas) { if (respond_to_queries) return internal_store->decr(key, amount, proposed_cas); else return store_t::incr_decr_result_t::idr_not_allowed; } store_t::append_prepend_result_t slave_t::append(store_key_t *key, data_provider_t *data, cas_t proposed_cas) { if (respond_to_queries) return internal_store->append(key, data, proposed_cas); else return store_t::apr_not_allowed; } store_t::append_prepend_result_t slave_t::prepend(store_key_t *key, data_provider_t *data, cas_t proposed_cas) { if (respond_to_queries) return internal_store->prepend(key, data, proposed_cas); else return store_t::apr_not_allowed; } store_t::delete_result_t slave_t::delete_key(store_key_t *key) { if (respond_to_queries) return internal_store->delete_key(key); else return dr_not_allowed; } std::string slave_t::failover_reset() { on_thread_t thread_switch(get_num_threads() - 2); give_up.reset(); timeout = INITIAL_TIMEOUT; if (timer_token) { cancel_timer(timer_token); timer_token = NULL; } if (conn) kill_conn(); //this will cause a notify else coro->notify(); return std::string("Reseting failover\n"); } /* message_callback_t interface */ void slave_t::hello(boost::scoped_ptr<hello_message_t>& message) {} void slave_t::send(boost::scoped_ptr<backfill_message_t>& message) {} void slave_t::send(boost::scoped_ptr<announce_message_t>& message) {} void slave_t::send(boost::scoped_ptr<set_message_t>& message) {} void slave_t::send(boost::scoped_ptr<append_message_t>& message) {} void slave_t::send(boost::scoped_ptr<prepend_message_t>& message) {} void slave_t::send(boost::scoped_ptr<nop_message_t>& message) {} void slave_t::send(boost::scoped_ptr<ack_message_t>& message) {} void slave_t::send(boost::scoped_ptr<shutting_down_message_t>& message) {} void slave_t::send(boost::scoped_ptr<goodbye_message_t>& message) {} void slave_t::conn_closed() { coro->notify(); } /* failover driving functions */ void slave_t::reconnect_timer_callback(void *ctx) { slave_t *self = static_cast<slave_t*>(ctx); self->coro->notify(); } /* give_up_t interface: the give_up_t struct keeps track of the last N times * the server failed. If it's failing to frequently then it will tell us to * give up on the server and stop trying to reconnect */ void slave_t::give_up_t::on_reconnect() { succesful_reconnects.push(ticks_to_secs(get_ticks())); limit_to(MAX_RECONNECTS_PER_N_SECONDS); } bool slave_t::give_up_t::give_up() { limit_to(MAX_RECONNECTS_PER_N_SECONDS); return (succesful_reconnects.size() == MAX_RECONNECTS_PER_N_SECONDS && (succesful_reconnects.back() - ticks_to_secs(get_ticks())) < N_SECONDS); } void slave_t::give_up_t::reset() { limit_to(0); } void slave_t::give_up_t::limit_to(unsigned int limit) { while (succesful_reconnects.size() > limit) succesful_reconnects.pop(); } /* failover callback */ void slave_t::on_failure() { respond_to_queries = true; } void slave_t::on_resume() { respond_to_queries = false; } void run(slave_t *slave) { slave->coro = coro_t::self(); slave->failover.add_callback(slave); slave->respond_to_queries = false; bool first_connect = true; while (!slave->shutting_down) { try { if (slave->conn) { delete slave->conn; slave->conn = NULL; } coro_t::move_to_thread(get_num_threads() - 2); logINF("Attempting to connect as slave to: %s:%d\n", slave->replication_config.hostname, slave->replication_config.port); slave->conn = new tcp_conn_t(slave->replication_config.hostname, slave->replication_config.port); slave->timeout = INITIAL_TIMEOUT; slave->give_up.on_reconnect(); slave->parser.parse_messages(slave->conn, slave); if (!first_connect) //UGLY :( but it's either this or code duplication slave->failover.on_resume(); //Call on_resume if we've failed before first_connect = false; logINF("Connected as slave to: %s:%d\n", slave->replication_config.hostname, slave->replication_config.port); coro_t::wait(); //wait for things to fail slave->failover.on_failure(); if (slave->shutting_down) break; } catch (tcp_conn_t::connect_failed_exc_t& e) { //Presumably if the master doesn't even accept an initial //connection then this is a user error rather than some sort of //failure if (first_connect) crash("Master at %s:%d is not responding :(. Perhaps you haven't brought it up yet. But what do I know I'm just a database\n", slave->replication_config.hostname, slave->replication_config.port); } /* The connection has failed. Let's see what se should do */ if (!slave->give_up.give_up()) { slave->timer_token = fire_timer_once(slave->timeout, &slave->reconnect_timer_callback, slave); slave->timeout *= TIMEOUT_GROWTH_FACTOR; coro_t::wait(); //waiting on a timer slave->timer_token = NULL; } else { logINF("Master at %s:%d has failed %d times in the last %d seconds," \ "going rogue. To resume slave behavior send the command" \ "\"rethinkdb failover reset\" (over telnet)\n", slave->replication_config.hostname, slave->replication_config.port, MAX_RECONNECTS_PER_N_SECONDS, N_SECONDS); coro_t::wait(); //the only thing that can save us now is a reset } } } std::string slave_t::new_master(std::string args) { std::string host = args.substr(0, args.find(' ')); if (host.length() > MAX_HOSTNAME_LEN - 1) return std::string("That hostname is soo long, use a shorter one\n"); /* redo the replication_config info */ strcpy(replication_config.hostname, host.c_str()); replication_config.port = atoi(strip_spaces(args.substr(args.find(' ') + 1)).c_str()); //TODO this is ugly failover_reset(); return std::string("New master set\n"); } std::string slave_t::failover_reset_control_t::call(std::string) { return slave->failover_reset(); } std::string slave_t::new_master_control_t::call(std::string args) { return slave->new_master(args); } } // namespace replication <commit_msg>Fixed compilation error with slave.cc when MOCK_CACHE_CHECK=1 DEBUG=1.<commit_after>#include "slave.hpp" #include <stdint.h> #include "arch/linux/coroutines.hpp" #include "logger.hpp" #include "net_structs.hpp" namespace replication { // TODO unit test offsets slave_t::slave_t(store_t *internal_store, replication_config_t replication_config, failover_config_t failover_config) : internal_store(internal_store), replication_config(replication_config), failover_config(failover_config), conn(NULL), shutting_down(false), failover_script(failover_config.failover_script_path), timeout(INITIAL_TIMEOUT), timer_token(NULL), failover_reset_control(std::string("failover reset"), this), new_master_control(std::string("new master"), this) { coro_t::spawn(&run, this); } slave_t::~slave_t() { shutting_down = true; coro_t::move_to_thread(home_thread); kill_conn(); /* cancel the timer */ if(timer_token) cancel_timer(timer_token); } void slave_t::kill_conn() { struct : public message_parser_t::message_parser_shutdown_callback_t, public cond_t { void on_parser_shutdown() { pulse(); } } parser_shutdown_cb; { on_thread_t thread_switch(home_thread); if (!parser.shutdown(&parser_shutdown_cb)) parser_shutdown_cb.wait(); } { //on_thread_t scope on_thread_t thread_switch(get_num_threads() - 2); if (conn) { delete conn; conn = NULL; } } } store_t::get_result_t slave_t::get(store_key_t *key) { return internal_store->get(key); } store_t::get_result_t slave_t::get_cas(store_key_t *key, cas_t proposed_cas) { // TODO: ask joe why this used get(key) before (back when we did not have proposed_cas). return internal_store->get_cas(key, proposed_cas); } store_t::set_result_t slave_t::set(store_key_t *key, data_provider_t *data, mcflags_t flags, exptime_t exptime, cas_t proposed_cas) { if (respond_to_queries) return internal_store->set(key, data, flags, exptime, proposed_cas); else return store_t::sr_not_allowed; } store_t::set_result_t slave_t::add(store_key_t *key, data_provider_t *data, mcflags_t flags, exptime_t exptime, cas_t proposed_cas) { return internal_store->add(key, data, flags, exptime, proposed_cas); } store_t::set_result_t slave_t::replace(store_key_t *key, data_provider_t *data, mcflags_t flags, exptime_t exptime, cas_t proposed_cas) { if (respond_to_queries) return internal_store->replace(key, data, flags, exptime, proposed_cas); else return store_t::sr_not_allowed; } store_t::set_result_t slave_t::cas(store_key_t *key, data_provider_t *data, mcflags_t flags, exptime_t exptime, cas_t unique, cas_t proposed_cas) { if (respond_to_queries) return internal_store->cas(key, data, flags, exptime, unique, proposed_cas); else return store_t::sr_not_allowed; } store_t::incr_decr_result_t slave_t::incr(store_key_t *key, unsigned long long amount, cas_t proposed_cas) { if (respond_to_queries) return internal_store->incr(key, amount, proposed_cas); else return store_t::incr_decr_result_t::idr_not_allowed; } store_t::incr_decr_result_t slave_t::decr(store_key_t *key, unsigned long long amount, cas_t proposed_cas) { if (respond_to_queries) return internal_store->decr(key, amount, proposed_cas); else return store_t::incr_decr_result_t::idr_not_allowed; } store_t::append_prepend_result_t slave_t::append(store_key_t *key, data_provider_t *data, cas_t proposed_cas) { if (respond_to_queries) return internal_store->append(key, data, proposed_cas); else return store_t::apr_not_allowed; } store_t::append_prepend_result_t slave_t::prepend(store_key_t *key, data_provider_t *data, cas_t proposed_cas) { if (respond_to_queries) return internal_store->prepend(key, data, proposed_cas); else return store_t::apr_not_allowed; } store_t::delete_result_t slave_t::delete_key(store_key_t *key) { if (respond_to_queries) return internal_store->delete_key(key); else return dr_not_allowed; } std::string slave_t::failover_reset() { on_thread_t thread_switch(get_num_threads() - 2); give_up.reset(); timeout = INITIAL_TIMEOUT; if (timer_token) { cancel_timer(timer_token); timer_token = NULL; } if (conn) kill_conn(); //this will cause a notify else coro->notify(); return std::string("Reseting failover\n"); } /* message_callback_t interface */ void slave_t::hello(boost::scoped_ptr<hello_message_t>& message) {} void slave_t::send(boost::scoped_ptr<backfill_message_t>& message) {} void slave_t::send(boost::scoped_ptr<announce_message_t>& message) {} void slave_t::send(boost::scoped_ptr<set_message_t>& message) {} void slave_t::send(boost::scoped_ptr<append_message_t>& message) {} void slave_t::send(boost::scoped_ptr<prepend_message_t>& message) {} void slave_t::send(boost::scoped_ptr<nop_message_t>& message) {} void slave_t::send(boost::scoped_ptr<ack_message_t>& message) {} void slave_t::send(boost::scoped_ptr<shutting_down_message_t>& message) {} void slave_t::send(boost::scoped_ptr<goodbye_message_t>& message) {} void slave_t::conn_closed() { coro->notify(); } /* failover driving functions */ void slave_t::reconnect_timer_callback(void *ctx) { slave_t *self = static_cast<slave_t*>(ctx); self->coro->notify(); } /* give_up_t interface: the give_up_t struct keeps track of the last N times * the server failed. If it's failing to frequently then it will tell us to * give up on the server and stop trying to reconnect */ void slave_t::give_up_t::on_reconnect() { succesful_reconnects.push(ticks_to_secs(get_ticks())); limit_to(MAX_RECONNECTS_PER_N_SECONDS); } bool slave_t::give_up_t::give_up() { limit_to(MAX_RECONNECTS_PER_N_SECONDS); return (succesful_reconnects.size() == MAX_RECONNECTS_PER_N_SECONDS && (succesful_reconnects.back() - ticks_to_secs(get_ticks())) < N_SECONDS); } void slave_t::give_up_t::reset() { limit_to(0); } void slave_t::give_up_t::limit_to(unsigned int limit) { while (succesful_reconnects.size() > limit) succesful_reconnects.pop(); } /* failover callback */ void slave_t::on_failure() { respond_to_queries = true; } void slave_t::on_resume() { respond_to_queries = false; } void run(slave_t *slave) { slave->coro = coro_t::self(); slave->failover.add_callback(slave); slave->respond_to_queries = false; bool first_connect = true; while (!slave->shutting_down) { try { if (slave->conn) { delete slave->conn; slave->conn = NULL; } coro_t::move_to_thread(get_num_threads() - 2); logINF("Attempting to connect as slave to: %s:%d\n", slave->replication_config.hostname, slave->replication_config.port); slave->conn = new tcp_conn_t(slave->replication_config.hostname, slave->replication_config.port); slave->timeout = INITIAL_TIMEOUT; slave->give_up.on_reconnect(); slave->parser.parse_messages(slave->conn, slave); if (!first_connect) //UGLY :( but it's either this or code duplication slave->failover.on_resume(); //Call on_resume if we've failed before first_connect = false; logINF("Connected as slave to: %s:%d\n", slave->replication_config.hostname, slave->replication_config.port); coro_t::wait(); //wait for things to fail slave->failover.on_failure(); if (slave->shutting_down) break; } catch (tcp_conn_t::connect_failed_exc_t& e) { //Presumably if the master doesn't even accept an initial //connection then this is a user error rather than some sort of //failure if (first_connect) crash("Master at %s:%d is not responding :(. Perhaps you haven't brought it up yet. But what do I know I'm just a database\n", slave->replication_config.hostname, slave->replication_config.port); } /* The connection has failed. Let's see what se should do */ if (!slave->give_up.give_up()) { slave->timer_token = fire_timer_once(slave->timeout, &slave->reconnect_timer_callback, slave); slave->timeout *= TIMEOUT_GROWTH_FACTOR; coro_t::wait(); //waiting on a timer slave->timer_token = NULL; } else { logINF("Master at %s:%d has failed %d times in the last %d seconds," \ "going rogue. To resume slave behavior send the command" \ "\"rethinkdb failover reset\" (over telnet)\n", slave->replication_config.hostname, slave->replication_config.port, MAX_RECONNECTS_PER_N_SECONDS, N_SECONDS); coro_t::wait(); //the only thing that can save us now is a reset } } } std::string slave_t::new_master(std::string args) { std::string host = args.substr(0, args.find(' ')); if (host.length() > MAX_HOSTNAME_LEN - 1) return std::string("That hostname is soo long, use a shorter one\n"); /* redo the replication_config info */ strcpy(replication_config.hostname, host.c_str()); replication_config.port = atoi(strip_spaces(args.substr(args.find(' ') + 1)).c_str()); //TODO this is ugly failover_reset(); return std::string("New master set\n"); } std::string slave_t::failover_reset_control_t::call(std::string) { return slave->failover_reset(); } std::string slave_t::new_master_control_t::call(std::string args) { return slave->new_master(args); } } // namespace replication <|endoftext|>
<commit_before>/* Resembla: Word-based Japanese similar sentence search library https://github.com/tuem/resembla Copyright 2017 Takashi Uemura 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 "resembla_with_id.hpp" #include <fstream> #include <algorithm> namespace resembla { ResemblaWithId::ResemblaWithId(const std::shared_ptr<ResemblaInterface> resembla, std::string corpus_path, size_t id_col, size_t text_col): resembla(resembla) { loadCorpus(corpus_path, id_col, text_col); } std::vector<ResemblaWithId::output_type> ResemblaWithId::find(const string_type& query, double threshold, size_t max_response) const { std::vector<output_type> results; for(auto raw_result: resembla->find(query, threshold, max_response)){ results.push_back({raw_result, ids.at(raw_result.text)}); } return results; } std::vector<ResemblaWithId::output_type> ResemblaWithId::eval(const string_type& query, const std::vector<string_type>& targets, double threshold, size_t max_response) const { std::vector<output_type> results; for(auto raw_result: resembla->eval(query, targets, threshold, max_response)){ auto i = ids.find(raw_result.text); results.push_back({raw_result, i != ids.end() ? i->second : id_type{0}}); } return results; } void ResemblaWithId::loadCorpus(const std::string& corpus_path, size_t id_col, size_t text_col) { id_type max_id = 0; std::ifstream ifs(corpus_path); if(ifs.fail()){ throw std::runtime_error("input file is not available: " + corpus_path); } while(ifs.good()){ std::string line; std::getline(ifs, line); if(ifs.eof() || line.length() == 0){ break; } auto columns = split(line, column_delimiter<>()); if(text_col - 1 < columns.size()){ auto text = cast_string<string_type>(columns[text_col - 1]); auto i = ids.find(text); if(i == std::end(ids)){ id_type id; if(id_col == 0 || id_col > columns.size()){ id = ++max_id; } else{ id = std::stoi(columns[id_col - 1]); max_id = std::max(id, max_id); } ids[text] = id; } } } } } <commit_msg>use csv_reader in resembla_with_id<commit_after>/* Resembla: Word-based Japanese similar sentence search library https://github.com/tuem/resembla Copyright 2017 Takashi Uemura 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 "resembla_with_id.hpp" #include <algorithm> #include "csv_reader.hpp" namespace resembla { ResemblaWithId::ResemblaWithId(const std::shared_ptr<ResemblaInterface> resembla, std::string corpus_path, size_t id_col, size_t text_col): resembla(resembla) { loadCorpus(corpus_path, id_col, text_col); } std::vector<ResemblaWithId::output_type> ResemblaWithId::find(const string_type& query, double threshold, size_t max_response) const { std::vector<output_type> results; for(auto raw_result: resembla->find(query, threshold, max_response)){ results.push_back({raw_result, ids.at(raw_result.text)}); } return results; } std::vector<ResemblaWithId::output_type> ResemblaWithId::eval(const string_type& query, const std::vector<string_type>& targets, double threshold, size_t max_response) const { std::vector<output_type> results; for(auto raw_result: resembla->eval(query, targets, threshold, max_response)){ auto i = ids.find(raw_result.text); results.push_back({raw_result, i != ids.end() ? i->second : id_type{0}}); } return results; } void ResemblaWithId::loadCorpus(const std::string& corpus_path, size_t id_col, size_t text_col) { id_type max_id{0}; for(const auto& columns: CsvReader<string_type>(corpus_path, text_col)){ const auto& text = cast_string<string_type>(columns[text_col - 1]); auto i = ids.find(text); if(i == std::end(ids)){ id_type id; if(id_col == 0 || id_col > columns.size()){ id = ++max_id; } else{ id = std::stoi(columns[id_col - 1]); max_id = std::max(id, max_id); } ids[text] = id; } } } } <|endoftext|>
<commit_before>#include <os.h> #include <x86.h> /* Stack pointer */ extern u32 * stack_ptr; /* Current cpu name */ static char cpu_name[512] = "x86-noname"; /* Detect the type of processor */ char* Architecture::detect(){ cpu_vendor_name(cpu_name); return cpu_name; } /* Start and initialize the architecture */ void Architecture::init(){ io.print("Architecture x86, cpu=%s \n", detect()); io.print("Loading GDT \n"); init_gdt(); asm(" movw $0x18, %%ax \n \ movw %%ax, %%ss \n \ movl %0, %%esp"::"i" (KERN_STACK)); io.print("Loading IDT \n"); init_idt(); io.print("Configure PIC \n"); init_pic(); io.print("Loading Task Register \n"); asm(" movw $0x38, %ax; ltr %ax"); } /* Initialise the list of processus */ void Architecture::initProc(){ firstProc= new Process("kernel"); firstProc->setState(ZOMBIE); firstProc->addFile(fsm.path("/dev/tty"),0); firstProc->addFile(fsm.path("/dev/tty"),0); firstProc->addFile(fsm.path("/dev/tty"),0); plist=firstProc; pcurrent=firstProc; pcurrent->setPNext(NULL); process_st* current=pcurrent->getPInfo(); current->regs.cr3 = (u32) pd0; } /* Reboot the computer */ void Architecture::reboot(){ u8 good = 0x02; while ((good & 0x02) != 0) good = io.inb(0x64); io.outb(0x64, 0xFE); } /* Shutdown the computer */ void Architecture::shutdown(){ // todo } /* Install a interruption handler */ void Architecture::install_irq(int_handler h){ // todo } /* Add a process to the scheduler */ void Architecture::addProcess(Process* p){ p->setPNext(plist); plist=p; } /* Fork a process */ int Architecture::fork(process_st* info,process_st* father){ memcpy((char*)info,(char*)father,sizeof(process_st)); info->pd = pd_copy(father->pd); } /* Initialise a new process */ int Architecture::createProc(process_st* info, char* file, int argc, char** argv){ page *kstack; process_st *previous; process_st *current; char **param, **uparam; u32 stackp; u32 e_entry; int pid; int i; pid = 1; info->pid = pid; if (argc) { param = (char**) kmalloc(sizeof(char*) * (argc+1)); for (i=0 ; i<argc ; i++) { param[i] = (char*) kmalloc(strlen(argv[i]) + 1); strcpy(param[i], argv[i]); } param[i] = 0; } info->pd = pd_create(); INIT_LIST_HEAD(&(info->pglist)); previous = arch.pcurrent->getPInfo(); current=info; asm("mov %0, %%eax; mov %%eax, %%cr3"::"m"((info->pd)->base->p_addr)); e_entry = (u32) load_elf(file,info); if (e_entry == 0) { for (i=0 ; i<argc ; i++) kfree(param[i]); kfree(param); arch.pcurrent = (Process*) previous->vinfo; current=arch.pcurrent->getPInfo(); asm("mov %0, %%eax ;mov %%eax, %%cr3"::"m" (current->regs.cr3)); pd_destroy(info->pd); return -1; } stackp = USER_STACK - 16; if (argc) { uparam = (char**) kmalloc(sizeof(char*) * argc); for (i=0 ; i<argc ; i++) { stackp -= (strlen(param[i]) + 1); strcpy((char*) stackp, param[i]); uparam[i] = (char*) stackp; } stackp &= 0xFFFFFFF0; // Creation des arguments de main() : argc, argv[]... stackp -= sizeof(char*); *((char**) stackp) = 0; for (i=argc-1 ; i>=0 ; i--) { stackp -= sizeof(char*); *((char**) stackp) = uparam[i]; } stackp -= sizeof(char*); *((char**) stackp) = (char*) (stackp + 4); stackp -= sizeof(char*); *((int*) stackp) = argc; stackp -= sizeof(char*); for (i=0 ; i<argc ; i++) kfree(param[i]); kfree(param); kfree(uparam); } kstack = get_page_from_heap(); // Initialise le reste des registres et des attributs info->regs.ss = 0x33; info->regs.esp = stackp; info->regs.eflags = 0x0; info->regs.cs = 0x23; info->regs.eip = e_entry; info->regs.ds = 0x2B; info->regs.es = 0x2B; info->regs.fs = 0x2B; info->regs.gs = 0x2B; info->regs.cr3 = (u32) info->pd->base->p_addr; info->kstack.ss0 = 0x18; info->kstack.esp0 = (u32) kstack->v_addr + PAGESIZE - 16; info->regs.eax = 0; info->regs.ecx = 0; info->regs.edx = 0; info->regs.ebx = 0; info->regs.ebp = 0; info->regs.esi = 0; info->regs.edi = 0; info->b_heap = (char*) ((u32) info->e_bss & 0xFFFFF000) + PAGESIZE; info->e_heap = info->b_heap; info->signal = 0; for(i=0 ; i<32 ; i++) info->sigfn[i] = (char*) SIG_DFL; arch.pcurrent = (Process*) previous->vinfo; current=arch.pcurrent->getPInfo(); asm("mov %0, %%eax ;mov %%eax, %%cr3":: "m"(current->regs.cr3)); return 1; } // Destroy a process void Architecture::destroy_process(Process* pp){ disable_interrupt(); u16 kss; u32 kesp; u32 accr3; list_head *p, *n; page *pg; process_st *proccurrent=(arch.pcurrent)->getPInfo(); process_st *pidproc=pp->getPInfo(); // Switch page to the process to destroy asm("mov %0, %%eax ;mov %%eax, %%cr3"::"m" (pidproc->regs.cr3)); // Free process memory: // - pages used by the executable code // - user stack // - kernel stack // - pages directory // Free process memory list_for_each_safe(p, n, &pidproc->pglist) { pg = list_entry(p, struct page, list); release_page_frame(pg->p_addr); list_del(p); kfree(pg); } release_page_from_heap((char *) ((u32)pidproc->kstack.esp0 & 0xFFFFF000)); // Free pages directory asm("mov %0, %%eax; mov %%eax, %%cr3"::"m"(pd0)); pd_destroy(pidproc->pd); asm("mov %0, %%eax ;mov %%eax, %%cr3"::"m" (proccurrent->regs.cr3)); // Remove from the list if (plist==pp){ plist=pp->getPNext(); } else{ Process* l=plist; Process*ol=plist; while (l!=NULL){ if (l==pp){ ol->setPNext(pp->getPNext()); } ol=l; l=l->getPNext(); } } enable_interrupt(); } void Architecture::change_process_father(Process* pe, Process* pere){ Process* p=plist; Process* pn=NULL; while (p!=NULL){ pn=p->getPNext(); if (p->getPParent()==pe){ p->setPParent(pere); } p=pn; } } void Architecture::destroy_all_zombie(){ Process* p=plist; Process* pn=NULL; while (p!=NULL){ pn=p->getPNext(); if (p->getState()==ZOMBIE && p->getPid()!=1){ destroy_process(p); delete p; } p=pn; } } /* Set the syscall arguments */ void Architecture::setParam(u32 ret, u32 ret1, u32 ret2, u32 ret3,u32 ret4){ ret_reg[0]=ret; ret_reg[1]=ret1; ret_reg[2]=ret2; ret_reg[3]=ret3; ret_reg[4]=ret4; } /* Enable the interruption */ void Architecture::enable_interrupt(){ asm ("sti"); } /* Disable the interruption */ void Architecture::disable_interrupt(){ asm ("cli"); } /* Get a syscall argument */ u32 Architecture::getArg(u32 n){ if (n<5) return ret_reg[n]; else return 0; } /* Set the return value of syscall */ void Architecture::setRet(u32 ret){ stack_ptr[14] = ret; } <commit_msg>Update architecture.cc<commit_after>#include <os.h> #include <x86.h> /* Stack pointer */ extern u32 * stack_ptr; /* Current cpu name */ static char cpu_name[512] = "x86-noname"; /* Detect the type of processor */ char* Architecture::detect(){ cpu_vendor_name(cpu_name); return cpu_name; } /* Start and initialize the architecture */ void Architecture::init(){ io.print("Architecture x86, cpu=%s \n", detect()); io.print("Loading GDT \n"); init_gdt(); asm(" movw $0x18, %%ax \n \ movw %%ax, %%ss \n \ movl %0, %%esp"::"i" (KERN_STACK)); io.print("Loading IDT \n"); init_idt(); io.print("Configure PIC \n"); init_pic(); io.print("Loading Task Register \n"); asm(" movw $0x38, %ax; ltr %ax"); } /* Initialise the list of processus */ void Architecture::initProc(){ firstProc= new Process("kernel"); firstProc->setState(ZOMBIE); firstProc->addFile(fsm.path("/suriyaa/tty"),0); firstProc->addFile(fsm.path("/suriyaa/tty"),0); firstProc->addFile(fsm.path("/suriyaa/tty"),0); plist=firstProc; pcurrent=firstProc; pcurrent->setPNext(NULL); process_st* current=pcurrent->getPInfo(); current->regs.cr3 = (u32) pd0; } /* Reboot the computer */ void Architecture::reboot(){ u8 good = 0x02; while ((good & 0x02) != 0) good = io.inb(0x64); io.outb(0x64, 0xFE); } /* Shutdown the computer */ void Architecture::shutdown(){ // todo } /* Install a interruption handler */ void Architecture::install_irq(int_handler h){ // todo } /* Add a process to the scheduler */ void Architecture::addProcess(Process* p){ p->setPNext(plist); plist=p; } /* Fork a process */ int Architecture::fork(process_st* info,process_st* father){ memcpy((char*)info,(char*)father,sizeof(process_st)); info->pd = pd_copy(father->pd); } /* Initialise a new process */ int Architecture::createProc(process_st* info, char* file, int argc, char** argv){ page *kstack; process_st *previous; process_st *current; char **param, **uparam; u32 stackp; u32 e_entry; int pid; int i; pid = 1; info->pid = pid; if (argc) { param = (char**) kmalloc(sizeof(char*) * (argc+1)); for (i=0 ; i<argc ; i++) { param[i] = (char*) kmalloc(strlen(argv[i]) + 1); strcpy(param[i], argv[i]); } param[i] = 0; } info->pd = pd_create(); INIT_LIST_HEAD(&(info->pglist)); previous = arch.pcurrent->getPInfo(); current=info; asm("mov %0, %%eax; mov %%eax, %%cr3"::"m"((info->pd)->base->p_addr)); e_entry = (u32) load_elf(file,info); if (e_entry == 0) { for (i=0 ; i<argc ; i++) kfree(param[i]); kfree(param); arch.pcurrent = (Process*) previous->vinfo; current=arch.pcurrent->getPInfo(); asm("mov %0, %%eax ;mov %%eax, %%cr3"::"m" (current->regs.cr3)); pd_destroy(info->pd); return -1; } stackp = USER_STACK - 16; if (argc) { uparam = (char**) kmalloc(sizeof(char*) * argc); for (i=0 ; i<argc ; i++) { stackp -= (strlen(param[i]) + 1); strcpy((char*) stackp, param[i]); uparam[i] = (char*) stackp; } stackp &= 0xFFFFFFF0; // Creation des arguments de main() : argc, argv[]... stackp -= sizeof(char*); *((char**) stackp) = 0; for (i=argc-1 ; i>=0 ; i--) { stackp -= sizeof(char*); *((char**) stackp) = uparam[i]; } stackp -= sizeof(char*); *((char**) stackp) = (char*) (stackp + 4); stackp -= sizeof(char*); *((int*) stackp) = argc; stackp -= sizeof(char*); for (i=0 ; i<argc ; i++) kfree(param[i]); kfree(param); kfree(uparam); } kstack = get_page_from_heap(); // Initialise le reste des registres et des attributs info->regs.ss = 0x33; info->regs.esp = stackp; info->regs.eflags = 0x0; info->regs.cs = 0x23; info->regs.eip = e_entry; info->regs.ds = 0x2B; info->regs.es = 0x2B; info->regs.fs = 0x2B; info->regs.gs = 0x2B; info->regs.cr3 = (u32) info->pd->base->p_addr; info->kstack.ss0 = 0x18; info->kstack.esp0 = (u32) kstack->v_addr + PAGESIZE - 16; info->regs.eax = 0; info->regs.ecx = 0; info->regs.edx = 0; info->regs.ebx = 0; info->regs.ebp = 0; info->regs.esi = 0; info->regs.edi = 0; info->b_heap = (char*) ((u32) info->e_bss & 0xFFFFF000) + PAGESIZE; info->e_heap = info->b_heap; info->signal = 0; for(i=0 ; i<32 ; i++) info->sigfn[i] = (char*) SIG_DFL; arch.pcurrent = (Process*) previous->vinfo; current=arch.pcurrent->getPInfo(); asm("mov %0, %%eax ;mov %%eax, %%cr3":: "m"(current->regs.cr3)); return 1; } // Destroy a process void Architecture::destroy_process(Process* pp){ disable_interrupt(); u16 kss; u32 kesp; u32 accr3; list_head *p, *n; page *pg; process_st *proccurrent=(arch.pcurrent)->getPInfo(); process_st *pidproc=pp->getPInfo(); // Switch page to the process to destroy asm("mov %0, %%eax ;mov %%eax, %%cr3"::"m" (pidproc->regs.cr3)); // Free process memory: // - pages used by the executable code // - user stack // - kernel stack // - pages directory // Free process memory list_for_each_safe(p, n, &pidproc->pglist) { pg = list_entry(p, struct page, list); release_page_frame(pg->p_addr); list_del(p); kfree(pg); } release_page_from_heap((char *) ((u32)pidproc->kstack.esp0 & 0xFFFFF000)); // Free pages directory asm("mov %0, %%eax; mov %%eax, %%cr3"::"m"(pd0)); pd_destroy(pidproc->pd); asm("mov %0, %%eax ;mov %%eax, %%cr3"::"m" (proccurrent->regs.cr3)); // Remove from the list if (plist==pp){ plist=pp->getPNext(); } else{ Process* l=plist; Process*ol=plist; while (l!=NULL){ if (l==pp){ ol->setPNext(pp->getPNext()); } ol=l; l=l->getPNext(); } } enable_interrupt(); } void Architecture::change_process_father(Process* pe, Process* pere){ Process* p=plist; Process* pn=NULL; while (p!=NULL){ pn=p->getPNext(); if (p->getPParent()==pe){ p->setPParent(pere); } p=pn; } } void Architecture::destroy_all_zombie(){ Process* p=plist; Process* pn=NULL; while (p!=NULL){ pn=p->getPNext(); if (p->getState()==ZOMBIE && p->getPid()!=1){ destroy_process(p); delete p; } p=pn; } } /* Set the syscall arguments */ void Architecture::setParam(u32 ret, u32 ret1, u32 ret2, u32 ret3,u32 ret4){ ret_reg[0]=ret; ret_reg[1]=ret1; ret_reg[2]=ret2; ret_reg[3]=ret3; ret_reg[4]=ret4; } /* Enable the interruption */ void Architecture::enable_interrupt(){ asm ("sti"); } /* Disable the interruption */ void Architecture::disable_interrupt(){ asm ("cli"); } /* Get a syscall argument */ u32 Architecture::getArg(u32 n){ if (n<5) return ret_reg[n]; else return 0; } /* Set the return value of syscall */ void Architecture::setRet(u32 ret){ stack_ptr[14] = ret; } <|endoftext|>
<commit_before>// This file is part of BlueSky // // BlueSky 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 3 // of the License, or (at your option) any later version. // // BlueSky 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 BlueSky; if not, see <http://www.gnu.org/licenses/>. #include "py_bs_log.h" #include "py_bs_exports.h" #include "py_bs_object_base.h" #include "bs_kernel.h" #include <bs_exception.h> #include <boost/python/call_method.hpp> #include <boost/python/enum.hpp> using namespace boost::python; namespace blue_sky { namespace python { BS_API const sp_channel &bs_end2(const sp_channel &r) { //r.lock()->set_can_output(true); //r.lock()->send_to_subscribers(); return r; } py_bs_log::py_bs_log() : //py_bs_messaging(sp_log(new bs_log(give_log::Instance()))) l(BS_KERNEL.get_log ()) {} //py_bs_channel *py_bs_log::get(const std::string &name_) const { // return new py_bs_channel(l[name_]); //} // //const sp_channel& py_bs_log::operator[](const std::string &name_) const { // return l[name_]; //} py_bs_channel py_bs_log::add_channel(const py_bs_channel &ch) { return py_bs_channel(l.add_channel(ch.c)); } bool py_bs_log::rem_channel(const std::string &ch_name) { return l.rem_channel(ch_name); } void stream_wrapper::write(const std::string &str) const { boost::python::call_method<void>(obj.ptr(), "write", str); } // void py_stream::write(const std::string &str) const { // try { // if (override f = this->get_override("write")) // f(str); // else // BSERROR << "Function write does not exists, or is not correct!" << bs_end; // } // catch(...) { // throw bs_exception("py_stream","May be member function \"void write(const std::string&) const\" is not overriden!"); // } // } py_bs_channel::py_bs_channel(const std::string &a) : c(new bs_channel(a)),auto_newline(true) {} py_bs_channel::py_bs_channel(const sp_channel &s) : c(s),auto_newline(true) {} void py_bs_channel::write(const char *str) const { //if (auto_newline) // *c.lock() << str << bs_end; //else // bs_end2(*c.lock() << str); } bool py_bs_channel::attach(const py_stream &s) const { return c.lock()->attach(s.spstream); } bool py_bs_channel::detach(const py_stream &s) const { return c.lock()->detach(s.spstream); } std::string py_bs_channel::get_name() const { return c.lock()->get_name(); } void py_bs_channel::set_output_time() const { c.lock()->set_output_time(); } void py_bs_channel::set_wait_end() const { //c.lock()->set_wait_end(); } void py_bs_channel::set_auto_newline(bool nl = false) { auto_newline = nl; } py_thread_log::py_thread_log() : l(BS_KERNEL.get_tlog ()) {} py_bs_channel py_thread_log::add_log_channel(const std::string &name) { return py_bs_channel(l.add_log_channel(name)); } bool py_thread_log::add_log_stream(const std::string &ch_name, const py_stream &pstream) { return l.add_log_stream(ch_name,pstream.spstream); } bool py_thread_log::rem_log_channel(const std::string &ch_name) { return l.rem_log_channel(ch_name); } bool py_thread_log::rem_log_stream(const std::string &ch_name, const py_stream &pstream) { return l.rem_log_stream(ch_name,pstream.spstream); } //const py_bs_channel *py_thread_log::get(const std::string &ch_name) const { // return new py_bs_channel(l[ch_name]); //} //const sp_channel &py_thread_log::operator[](const std::string &ch_name) const { // return l[ch_name]; //} bool py_bs_log::subscribe(int signal_code, const python_slot& slot) const { return l.subscribe(signal_code,slot.spslot); } bool py_bs_log::unsubscribe(int signal_code, const python_slot& slot) const { return l.unsubscribe(signal_code,slot.spslot); } ulong py_bs_log::num_slots(int signal_code) const { return l.num_slots(signal_code); } bool py_bs_log::fire_signal(int signal_code, const py_objbase* param) const { return l.fire_signal(signal_code,param->sp); } std::vector< int > py_bs_log::get_signal_list() const { return l.get_signal_list(); } //std::list< std::string > py_bs_log::get_ch_list() const { // return l.channel_list(); //} void py_export_log() { class_<py_bs_log, /*bases<py_bs_messaging>,*/ noncopyable>("log") .def("add_channel",&py_bs_log::add_channel) .def("rem_channel",&py_bs_log::rem_channel) //.def("get",&py_bs_log::get, return_value_policy<manage_new_object>()) .def("subscribe",&py_bs_log::subscribe) .def("unsubscribe",&py_bs_log::unsubscribe) .def("num_slots",&py_bs_log::num_slots) .def("fire_signal",&py_bs_log::fire_signal) .def("get_signal_list",&py_bs_log::get_signal_list) //.def("get_ch_list",&py_bs_log::get_ch_list) ; class_<py_thread_log, noncopyable>("thread_log") .def("add_log_channel",&py_thread_log::add_log_channel) .def("rem_log_channel",&py_thread_log::rem_log_channel) .def("add_log_stream",&py_thread_log::add_log_stream) .def("rem_log_stream",&py_thread_log::rem_log_stream) //.def("get",&py_thread_log::get, return_value_policy<manage_new_object>()) ; //class_<py_stream, noncopyable>("stream") //.def("write",pure_virtual(&bs_stream::write)); class_<stream_wrapper, noncopyable>("stream", init<const std::string &, const boost::python::object&>()) .def("write", &stream_wrapper::write); class_<py_stream, noncopyable>("wstream", init<const std::string &, const boost::python::object&>()); class_<py_bs_channel>("channel", init <const std::string &> ()) .def(init<std::string>()) .def("attach",&py_bs_channel::attach) .def("detach",&py_bs_channel::detach) .def("get_name",&py_bs_channel::get_name) .def("write",&py_bs_channel::write) .def("set_output_time",&py_bs_channel::set_output_time) .def("set_wait_end",&py_bs_channel::set_wait_end) .def("set_auto_newline",&py_bs_channel::set_auto_newline); enum_<bs_log::signal_codes>("log_signal_codes") .value("log_channel_added",bs_log::log_channel_added) .value("log_channel_removed",bs_log::log_channel_removed) .export_values(); } } //namespace blue_sky::python } //namespace blue_sky <commit_msg>Fix: Output in log in python was broken<commit_after>// This file is part of BlueSky // // BlueSky 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 3 // of the License, or (at your option) any later version. // // BlueSky 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 BlueSky; if not, see <http://www.gnu.org/licenses/>. #include "py_bs_log.h" #include "py_bs_exports.h" #include "py_bs_object_base.h" #include "bs_kernel.h" #include <bs_exception.h> #include <boost/python/call_method.hpp> #include <boost/python/enum.hpp> using namespace boost::python; namespace blue_sky { namespace python { py_bs_log::py_bs_log() : //py_bs_messaging(sp_log(new bs_log(give_log::Instance()))) l(BS_KERNEL.get_log ()) {} //py_bs_channel *py_bs_log::get(const std::string &name_) const { // return new py_bs_channel(l[name_]); //} // //const sp_channel& py_bs_log::operator[](const std::string &name_) const { // return l[name_]; //} py_bs_channel py_bs_log::add_channel(const py_bs_channel &ch) { return py_bs_channel(l.add_channel(ch.c)); } bool py_bs_log::rem_channel(const std::string &ch_name) { return l.rem_channel(ch_name); } void stream_wrapper::write(const std::string &str) const { boost::python::call_method<void>(obj.ptr(), "write", str); } // void py_stream::write(const std::string &str) const { // try { // if (override f = this->get_override("write")) // f(str); // else // BSERROR << "Function write does not exists, or is not correct!" << bs_end; // } // catch(...) { // throw bs_exception("py_stream","May be member function \"void write(const std::string&) const\" is not overriden!"); // } // } py_bs_channel::py_bs_channel(const std::string &a) : c(new bs_channel(a)),auto_newline(true) {} py_bs_channel::py_bs_channel(const sp_channel &s) : c(s),auto_newline(true) {} void py_bs_channel::write(const char *str) const { locked_channel (c, __FILE__, __LINE__) << str << bs_end; } bool py_bs_channel::attach(const py_stream &s) const { return c.lock()->attach(s.spstream); } bool py_bs_channel::detach(const py_stream &s) const { return c.lock()->detach(s.spstream); } std::string py_bs_channel::get_name() const { return c.lock()->get_name(); } void py_bs_channel::set_output_time() const { c.lock()->set_output_time(); } py_thread_log::py_thread_log() : l(BS_KERNEL.get_tlog ()) {} py_bs_channel py_thread_log::add_log_channel(const std::string &name) { return py_bs_channel(l.add_log_channel(name)); } bool py_thread_log::add_log_stream(const std::string &ch_name, const py_stream &pstream) { return l.add_log_stream(ch_name,pstream.spstream); } bool py_thread_log::rem_log_channel(const std::string &ch_name) { return l.rem_log_channel(ch_name); } bool py_thread_log::rem_log_stream(const std::string &ch_name, const py_stream &pstream) { return l.rem_log_stream(ch_name,pstream.spstream); } //const py_bs_channel *py_thread_log::get(const std::string &ch_name) const { // return new py_bs_channel(l[ch_name]); //} //const sp_channel &py_thread_log::operator[](const std::string &ch_name) const { // return l[ch_name]; //} bool py_bs_log::subscribe(int signal_code, const python_slot& slot) const { return l.subscribe(signal_code,slot.spslot); } bool py_bs_log::unsubscribe(int signal_code, const python_slot& slot) const { return l.unsubscribe(signal_code,slot.spslot); } ulong py_bs_log::num_slots(int signal_code) const { return l.num_slots(signal_code); } bool py_bs_log::fire_signal(int signal_code, const py_objbase* param) const { return l.fire_signal(signal_code,param->sp); } std::vector< int > py_bs_log::get_signal_list() const { return l.get_signal_list(); } //std::list< std::string > py_bs_log::get_ch_list() const { // return l.channel_list(); //} void py_export_log() { class_<py_bs_log, /*bases<py_bs_messaging>,*/ noncopyable>("log") .def("add_channel",&py_bs_log::add_channel) .def("rem_channel",&py_bs_log::rem_channel) //.def("get",&py_bs_log::get, return_value_policy<manage_new_object>()) .def("subscribe",&py_bs_log::subscribe) .def("unsubscribe",&py_bs_log::unsubscribe) .def("num_slots",&py_bs_log::num_slots) .def("fire_signal",&py_bs_log::fire_signal) .def("get_signal_list",&py_bs_log::get_signal_list) //.def("get_ch_list",&py_bs_log::get_ch_list) ; class_<py_thread_log, noncopyable>("thread_log") .def("add_log_channel",&py_thread_log::add_log_channel) .def("rem_log_channel",&py_thread_log::rem_log_channel) .def("add_log_stream",&py_thread_log::add_log_stream) .def("rem_log_stream",&py_thread_log::rem_log_stream) //.def("get",&py_thread_log::get, return_value_policy<manage_new_object>()) ; //class_<py_stream, noncopyable>("stream") //.def("write",pure_virtual(&bs_stream::write)); class_<stream_wrapper, noncopyable>("stream", init<const std::string &, const boost::python::object&>()) .def("write", &stream_wrapper::write); class_<py_stream, noncopyable>("wstream", init<const std::string &, const boost::python::object&>()); class_<py_bs_channel>("channel", init <const std::string &> ()) .def(init<std::string>()) .def("attach",&py_bs_channel::attach) .def("detach",&py_bs_channel::detach) .def("get_name",&py_bs_channel::get_name) .def("write",&py_bs_channel::write) .def("set_output_time",&py_bs_channel::set_output_time) ; enum_<bs_log::signal_codes>("log_signal_codes") .value("log_channel_added",bs_log::log_channel_added) .value("log_channel_removed",bs_log::log_channel_removed) .export_values(); } } //namespace blue_sky::python } //namespace blue_sky <|endoftext|>
<commit_before> #include "numerics/quadrature.hpp" #include <limits> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "quantities/elementary_functions.hpp" #include "testing_utilities/almost_equals.hpp" #include "testing_utilities/is_near.hpp" #include "testing_utilities/numerics_matchers.hpp" namespace principia { namespace numerics { namespace quadrature { using quantities::Angle; using quantities::Cos; using quantities::Sin; using quantities::si::Radian; using testing_utilities::AlmostEquals; using testing_utilities::IsNear; using testing_utilities::RelativeErrorFrom; using testing_utilities::operator""_⑴; using ::testing::AnyOf; using ::testing::Eq; class QuadratureTest : public ::testing::Test {}; TEST_F(QuadratureTest, Sin) { int evaluations = 0; auto const f = [&evaluations](Angle const x) { ++evaluations; return Sin(x); }; auto const ʃf = (Cos(2.0 * Radian) - Cos(5.0 * Radian)) * Radian; EXPECT_THAT(GaussLegendre<1>(f, -2.0 * Radian, 5.0 * Radian), RelativeErrorFrom(ʃf, IsNear(10_⑴))); EXPECT_THAT(GaussLegendre<2>(f, -2.0 * Radian, 5.0 * Radian), RelativeErrorFrom(ʃf, IsNear(3.3_⑴))); EXPECT_THAT(GaussLegendre<3>(f, -2.0 * Radian, 5.0 * Radian), RelativeErrorFrom(ʃf, IsNear(4.0e-1_⑴))); EXPECT_THAT(GaussLegendre<4>(f, -2.0 * Radian, 5.0 * Radian), RelativeErrorFrom(ʃf, IsNear(2.4e-2_⑴))); EXPECT_THAT(GaussLegendre<5>(f, -2.0 * Radian, 5.0 * Radian), RelativeErrorFrom(ʃf, IsNear(8.6e-4_⑴))); EXPECT_THAT(GaussLegendre<6>(f, -2.0 * Radian, 5.0 * Radian), RelativeErrorFrom(ʃf, IsNear(2.1e-5_⑴))); EXPECT_THAT(GaussLegendre<7>(f, -2.0 * Radian, 5.0 * Radian), RelativeErrorFrom(ʃf, IsNear(3.6e-7_⑴))); EXPECT_THAT(GaussLegendre<8>(f, -2.0 * Radian, 5.0 * Radian), RelativeErrorFrom(ʃf, IsNear(4.7e-9_⑴))); EXPECT_THAT(GaussLegendre<9>(f, -2.0 * Radian, 5.0 * Radian), RelativeErrorFrom(ʃf, IsNear(4.8e-11_⑴))); EXPECT_THAT(GaussLegendre<10>(f, -2.0 * Radian, 5.0 * Radian), AlmostEquals(ʃf, 2495, 2498)); EXPECT_THAT(GaussLegendre<11>(f, -2.0 * Radian, 5.0 * Radian), AlmostEquals(ʃf, 20)); EXPECT_THAT(GaussLegendre<12>(f, -2.0 * Radian, 5.0 * Radian), AlmostEquals(ʃf, 6, 7)); EXPECT_THAT(GaussLegendre<13>(f, -2.0 * Radian, 5.0 * Radian), AlmostEquals(ʃf, 0, 1)); EXPECT_THAT(GaussLegendre<14>(f, -2.0 * Radian, 5.0 * Radian), AlmostEquals(ʃf, 1, 2)); EXPECT_THAT(GaussLegendre<15>(f, -2.0 * Radian, 5.0 * Radian), AlmostEquals(ʃf, 3, 4)); evaluations = 0; EXPECT_THAT(AutomaticClenshawCurtis( f, -2.0 * Radian, 5.0 * Radian, /*max_relative_error=*/std::numeric_limits<double>::epsilon(), /*max_points=*/std::nullopt), AlmostEquals(ʃf, 3, 4)); EXPECT_THAT(evaluations, Eq(65)); } TEST_F(QuadratureTest, Sin2) { auto const f = [](Angle const x) { return Sin(2 * x); }; auto const ʃf = (Cos(4 * Radian) - Cos(10 * Radian)) / 2 * Radian; EXPECT_THAT(GaussLegendre<1>(f, -2.0 * Radian, 5.0 * Radian), RelativeErrorFrom(ʃf, IsNear(9.7_⑴))); EXPECT_THAT(GaussLegendre<2>(f, -2.0 * Radian, 5.0 * Radian), RelativeErrorFrom(ʃf, IsNear(7.6_⑴))); EXPECT_THAT(GaussLegendre<3>(f, -2.0 * Radian, 5.0 * Radian), RelativeErrorFrom(ʃf, IsNear(7.6_⑴))); EXPECT_THAT(GaussLegendre<4>(f, -2.0 * Radian, 5.0 * Radian), RelativeErrorFrom(ʃf, IsNear(2.4_⑴))); EXPECT_THAT(GaussLegendre<5>(f, -2.0 * Radian, 5.0 * Radian), RelativeErrorFrom(ʃf, IsNear(4.2e-1_⑴))); EXPECT_THAT(GaussLegendre<6>(f, -2.0 * Radian, 5.0 * Radian), RelativeErrorFrom(ʃf, IsNear(4.6e-2_⑴))); EXPECT_THAT(GaussLegendre<7>(f, -2.0 * Radian, 5.0 * Radian), RelativeErrorFrom(ʃf, IsNear(3.5e-3_⑴))); EXPECT_THAT(GaussLegendre<8>(f, -2.0 * Radian, 5.0 * Radian), RelativeErrorFrom(ʃf, IsNear(2.0e-4_⑴))); EXPECT_THAT(GaussLegendre<9>(f, -2.0 * Radian, 5.0 * Radian), RelativeErrorFrom(ʃf, IsNear(8.5e-6_⑴))); EXPECT_THAT(GaussLegendre<10>(f, -2.0 * Radian, 5.0 * Radian), RelativeErrorFrom(ʃf, IsNear(2.9e-7_⑴)));; EXPECT_THAT(GaussLegendre<11>(f, -2.0 * Radian, 5.0 * Radian), RelativeErrorFrom(ʃf, IsNear(8.1e-9_⑴))); EXPECT_THAT(GaussLegendre<12>(f, -2.0 * Radian, 5.0 * Radian), RelativeErrorFrom(ʃf, IsNear(1.9e-10_⑴))); EXPECT_THAT(GaussLegendre<13>(f, -2.0 * Radian, 5.0 * Radian), RelativeErrorFrom(ʃf, IsNear(3.7e-12_⑴))); EXPECT_THAT(GaussLegendre<14>(f, -2.0 * Radian, 5.0 * Radian), AlmostEquals(ʃf, 422, 425)); EXPECT_THAT(GaussLegendre<15>(f, -2.0 * Radian, 5.0 * Radian), AlmostEquals(ʃf, 36, 50)); EXPECT_THAT(GaussLegendre<16>(f, -2.0 * Radian, 5.0 * Radian), AlmostEquals(ʃf, 152, 159)); } TEST_F(QuadratureTest, Sin10) { int evaluations = 0; auto const f = [&evaluations](Angle const x) { ++evaluations; return Sin(10 * x); }; auto const ʃf = (Cos(20 * Radian) - Cos(50 * Radian)) / 10 * Radian; EXPECT_THAT(AutomaticClenshawCurtis( f, -2.0 * Radian, 5.0 * Radian, /*max_relative_error=*/std::numeric_limits<double>::epsilon(), /*max_points=*/std::nullopt), AlmostEquals(ʃf, 2, 20)); EXPECT_THAT(evaluations, AnyOf(Eq(65537), Eq(262145))); } } // namespace quadrature } // namespace numerics } // namespace principia <commit_msg>Adjust number of iterations for Linux and macOS.<commit_after> #include "numerics/quadrature.hpp" #include <limits> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "quantities/elementary_functions.hpp" #include "testing_utilities/almost_equals.hpp" #include "testing_utilities/is_near.hpp" #include "testing_utilities/numerics_matchers.hpp" namespace principia { namespace numerics { namespace quadrature { using quantities::Angle; using quantities::Cos; using quantities::Sin; using quantities::si::Radian; using testing_utilities::AlmostEquals; using testing_utilities::IsNear; using testing_utilities::RelativeErrorFrom; using testing_utilities::operator""_⑴; using ::testing::AnyOf; using ::testing::Eq; class QuadratureTest : public ::testing::Test {}; TEST_F(QuadratureTest, Sin) { int evaluations = 0; auto const f = [&evaluations](Angle const x) { ++evaluations; return Sin(x); }; auto const ʃf = (Cos(2.0 * Radian) - Cos(5.0 * Radian)) * Radian; EXPECT_THAT(GaussLegendre<1>(f, -2.0 * Radian, 5.0 * Radian), RelativeErrorFrom(ʃf, IsNear(10_⑴))); EXPECT_THAT(GaussLegendre<2>(f, -2.0 * Radian, 5.0 * Radian), RelativeErrorFrom(ʃf, IsNear(3.3_⑴))); EXPECT_THAT(GaussLegendre<3>(f, -2.0 * Radian, 5.0 * Radian), RelativeErrorFrom(ʃf, IsNear(4.0e-1_⑴))); EXPECT_THAT(GaussLegendre<4>(f, -2.0 * Radian, 5.0 * Radian), RelativeErrorFrom(ʃf, IsNear(2.4e-2_⑴))); EXPECT_THAT(GaussLegendre<5>(f, -2.0 * Radian, 5.0 * Radian), RelativeErrorFrom(ʃf, IsNear(8.6e-4_⑴))); EXPECT_THAT(GaussLegendre<6>(f, -2.0 * Radian, 5.0 * Radian), RelativeErrorFrom(ʃf, IsNear(2.1e-5_⑴))); EXPECT_THAT(GaussLegendre<7>(f, -2.0 * Radian, 5.0 * Radian), RelativeErrorFrom(ʃf, IsNear(3.6e-7_⑴))); EXPECT_THAT(GaussLegendre<8>(f, -2.0 * Radian, 5.0 * Radian), RelativeErrorFrom(ʃf, IsNear(4.7e-9_⑴))); EXPECT_THAT(GaussLegendre<9>(f, -2.0 * Radian, 5.0 * Radian), RelativeErrorFrom(ʃf, IsNear(4.8e-11_⑴))); EXPECT_THAT(GaussLegendre<10>(f, -2.0 * Radian, 5.0 * Radian), AlmostEquals(ʃf, 2495, 2498)); EXPECT_THAT(GaussLegendre<11>(f, -2.0 * Radian, 5.0 * Radian), AlmostEquals(ʃf, 20)); EXPECT_THAT(GaussLegendre<12>(f, -2.0 * Radian, 5.0 * Radian), AlmostEquals(ʃf, 6, 7)); EXPECT_THAT(GaussLegendre<13>(f, -2.0 * Radian, 5.0 * Radian), AlmostEquals(ʃf, 0, 1)); EXPECT_THAT(GaussLegendre<14>(f, -2.0 * Radian, 5.0 * Radian), AlmostEquals(ʃf, 1, 2)); EXPECT_THAT(GaussLegendre<15>(f, -2.0 * Radian, 5.0 * Radian), AlmostEquals(ʃf, 3, 4)); evaluations = 0; EXPECT_THAT(AutomaticClenshawCurtis( f, -2.0 * Radian, 5.0 * Radian, /*max_relative_error=*/std::numeric_limits<double>::epsilon(), /*max_points=*/std::nullopt), AlmostEquals(ʃf, 3, 4)); EXPECT_THAT(evaluations, Eq(65)); } TEST_F(QuadratureTest, Sin2) { auto const f = [](Angle const x) { return Sin(2 * x); }; auto const ʃf = (Cos(4 * Radian) - Cos(10 * Radian)) / 2 * Radian; EXPECT_THAT(GaussLegendre<1>(f, -2.0 * Radian, 5.0 * Radian), RelativeErrorFrom(ʃf, IsNear(9.7_⑴))); EXPECT_THAT(GaussLegendre<2>(f, -2.0 * Radian, 5.0 * Radian), RelativeErrorFrom(ʃf, IsNear(7.6_⑴))); EXPECT_THAT(GaussLegendre<3>(f, -2.0 * Radian, 5.0 * Radian), RelativeErrorFrom(ʃf, IsNear(7.6_⑴))); EXPECT_THAT(GaussLegendre<4>(f, -2.0 * Radian, 5.0 * Radian), RelativeErrorFrom(ʃf, IsNear(2.4_⑴))); EXPECT_THAT(GaussLegendre<5>(f, -2.0 * Radian, 5.0 * Radian), RelativeErrorFrom(ʃf, IsNear(4.2e-1_⑴))); EXPECT_THAT(GaussLegendre<6>(f, -2.0 * Radian, 5.0 * Radian), RelativeErrorFrom(ʃf, IsNear(4.6e-2_⑴))); EXPECT_THAT(GaussLegendre<7>(f, -2.0 * Radian, 5.0 * Radian), RelativeErrorFrom(ʃf, IsNear(3.5e-3_⑴))); EXPECT_THAT(GaussLegendre<8>(f, -2.0 * Radian, 5.0 * Radian), RelativeErrorFrom(ʃf, IsNear(2.0e-4_⑴))); EXPECT_THAT(GaussLegendre<9>(f, -2.0 * Radian, 5.0 * Radian), RelativeErrorFrom(ʃf, IsNear(8.5e-6_⑴))); EXPECT_THAT(GaussLegendre<10>(f, -2.0 * Radian, 5.0 * Radian), RelativeErrorFrom(ʃf, IsNear(2.9e-7_⑴)));; EXPECT_THAT(GaussLegendre<11>(f, -2.0 * Radian, 5.0 * Radian), RelativeErrorFrom(ʃf, IsNear(8.1e-9_⑴))); EXPECT_THAT(GaussLegendre<12>(f, -2.0 * Radian, 5.0 * Radian), RelativeErrorFrom(ʃf, IsNear(1.9e-10_⑴))); EXPECT_THAT(GaussLegendre<13>(f, -2.0 * Radian, 5.0 * Radian), RelativeErrorFrom(ʃf, IsNear(3.7e-12_⑴))); EXPECT_THAT(GaussLegendre<14>(f, -2.0 * Radian, 5.0 * Radian), AlmostEquals(ʃf, 422, 425)); EXPECT_THAT(GaussLegendre<15>(f, -2.0 * Radian, 5.0 * Radian), AlmostEquals(ʃf, 36, 50)); EXPECT_THAT(GaussLegendre<16>(f, -2.0 * Radian, 5.0 * Radian), AlmostEquals(ʃf, 152, 159)); } TEST_F(QuadratureTest, Sin10) { int evaluations = 0; auto const f = [&evaluations](Angle const x) { ++evaluations; return Sin(10 * x); }; auto const ʃf = (Cos(20 * Radian) - Cos(50 * Radian)) / 10 * Radian; EXPECT_THAT(AutomaticClenshawCurtis( f, -2.0 * Radian, 5.0 * Radian, /*max_relative_error=*/std::numeric_limits<double>::epsilon(), /*max_points=*/std::nullopt), AlmostEquals(ʃf, 2, 20)); EXPECT_THAT(evaluations, AnyOf(Eq(32769), Eq(65537), Eq(262145), Eq(524289))); } } // namespace quadrature } // namespace numerics } // namespace principia <|endoftext|>
<commit_before>#include "HalideRuntime.h" // Structs are annoying to deal with from within Halide Stmts. These // utility functions are for dealing with buffer_t in that // context. They are not intended for use outside of Halide code, and // not exposed in HalideRuntime.h. The symbols are private to the // module and should be inlined and then stripped. Definitions here // are repeated in CodeGen_C.cpp, so changes here should be reflected // there too. extern "C" { __attribute__((always_inline, weak)) uint8_t *_halide_buffer_get_host(const buffer_t *buf) { return buf->host; } __attribute__((always_inline, weak)) uint64_t _halide_buffer_get_dev(const buffer_t *buf) { return buf->dev; } __attribute__((always_inline, weak)) int _halide_buffer_get_min(const buffer_t *buf, int d) { return buf->min[d]; } __attribute__((always_inline, weak)) int _halide_buffer_get_max(const buffer_t *buf, int d) { return buf->min[d] + buf->extent[d] - 1; } __attribute__((always_inline, weak)) bool _halide_buffer_get_host_dirty(buffer_t *buf) { return buf->host_dirty; } __attribute__((always_inline, weak)) bool _halide_buffer_get_dev_dirty(buffer_t *buf) { return buf->dev_dirty; } __attribute__((always_inline, weak)) int _halide_buffer_set_host_dirty(buffer_t *buf, bool val) { buf->host_dirty = val; return 0; } __attribute__((always_inline, weak)) int _halide_buffer_set_dev_dirty(buffer_t *buf, bool val) { buf->dev_dirty = val; return 0; } __attribute__((always_inline, weak)) buffer_t *_halide_buffer_init(buffer_t *dst, uint8_t *host, uint64_t dev, int /*type_code*/, int type_bits, int dimensions, const int *min, const int *extent, const int *stride, bool host_dirty, bool dev_dirty) { dst->host = host; dst->dev = dev; dst->elem_size = (type_bits + 7) / 8; dst->host_dirty = host_dirty; dst->dev_dirty = dev_dirty; for (int i = 0; i < dimensions; i++) { dst->min[i] = min[i]; dst->extent[i] = extent[i]; dst->stride[i] = stride[i]; } for (int i = dimensions; i < 4; i++) { dst->min[i] = 0; dst->extent[i] = 0; dst->stride[i] = 0; } return dst; } } <commit_msg>Making arguments const for new buffer_get_*<commit_after>#include "HalideRuntime.h" // Structs are annoying to deal with from within Halide Stmts. These // utility functions are for dealing with buffer_t in that // context. They are not intended for use outside of Halide code, and // not exposed in HalideRuntime.h. The symbols are private to the // module and should be inlined and then stripped. Definitions here // are repeated in CodeGen_C.cpp, so changes here should be reflected // there too. extern "C" { __attribute__((always_inline, weak)) uint8_t *_halide_buffer_get_host(const buffer_t *buf) { return buf->host; } __attribute__((always_inline, weak)) uint64_t _halide_buffer_get_dev(const buffer_t *buf) { return buf->dev; } __attribute__((always_inline, weak)) int _halide_buffer_get_min(const buffer_t *buf, int d) { return buf->min[d]; } __attribute__((always_inline, weak)) int _halide_buffer_get_max(const buffer_t *buf, int d) { return buf->min[d] + buf->extent[d] - 1; } __attribute__((always_inline, weak)) bool _halide_buffer_get_host_dirty(const buffer_t *buf) { return buf->host_dirty; } __attribute__((always_inline, weak)) bool _halide_buffer_get_dev_dirty(const buffer_t *buf) { return buf->dev_dirty; } __attribute__((always_inline, weak)) int _halide_buffer_set_host_dirty(buffer_t *buf, bool val) { buf->host_dirty = val; return 0; } __attribute__((always_inline, weak)) int _halide_buffer_set_dev_dirty(buffer_t *buf, bool val) { buf->dev_dirty = val; return 0; } __attribute__((always_inline, weak)) buffer_t *_halide_buffer_init(buffer_t *dst, uint8_t *host, uint64_t dev, int /*type_code*/, int type_bits, int dimensions, const int *min, const int *extent, const int *stride, bool host_dirty, bool dev_dirty) { dst->host = host; dst->dev = dev; dst->elem_size = (type_bits + 7) / 8; dst->host_dirty = host_dirty; dst->dev_dirty = dev_dirty; for (int i = 0; i < dimensions; i++) { dst->min[i] = min[i]; dst->extent[i] = extent[i]; dst->stride[i] = stride[i]; } for (int i = dimensions; i < 4; i++) { dst->min[i] = 0; dst->extent[i] = 0; dst->stride[i] = 0; } return dst; } } <|endoftext|>
<commit_before>#include <locale> #include <scope_macro.h> #include <str_util.h> #include <shl_exception.h> namespace shl { string expand_macro(const string& token, const string& text, const Match& match) { if (token[0] != '$') return token; if (token[1] == '{') { if (token.back() != '}') throw InvalidSourceException("scope macro not properly closed"); string num_command = token.substr(2, token.size() - 3); vector<string> num_command_pair = strtok(num_command, [](char c) { return c == ':';}); int group_num = atoi(num_command_pair[0].c_str()); if (group_num >= match.size()) throw InvalidSourceException("capture group number in scope name out of range"); string expanded = match[group_num].substr(text); std::locale loc; if (num_command_pair[1] == "/downcase") { return tolower(expanded, loc); } else if (num_command_pair[1] == "/upcase") { return std::toupper(expanded, loc); } else { throw InvalidSourceException("unknown expansion function " + num_command_pair[1]); } } else { int group_num = atoi(token.c_str() + 1); if (group_num >= match.size()) throw InvalidSourceException("capture group number in scope name out of range"); return match[group_num].substr(text); } } } <commit_msg>fix bugs<commit_after>#include <scope_macro.h> #include <str_util.h> #include <shl_exception.h> namespace shl { static string lower(const string& str) { string tmp = str; for(size_t pos = 0; pos < tmp.size(); ++pos) tmp[pos] = tolower(tmp[pos]); return tmp; } static string upper(const string& str) { string tmp = str; for(size_t pos = 0; pos < tmp.size(); ++pos) tmp[pos] = toupper(tmp[pos]); return tmp; } string expand_macro(const string& token, const string& text, const Match& match) { if (token[0] != '$') return token; if (token[1] == '{') { if (token.back() != '}') throw InvalidSourceException("scope macro not properly closed"); string num_command = token.substr(2, token.size() - 3); vector<string> num_command_pair = strtok(num_command, [](char c) { return c == ':';}); int group_num = atoi(num_command_pair[0].c_str()); if (group_num >= match.size()) throw InvalidSourceException("capture group number in scope name out of range"); string expanded = match[group_num].substr(text); if (num_command_pair.size() == 1) return expanded; if (num_command_pair[1] == "/downcase") { return lower(expanded); } else if (num_command_pair[1] == "/upcase") { return upper(expanded); } else { throw InvalidSourceException("unknown expansion function " + num_command_pair[1]); } } else { int group_num = atoi(token.c_str() + 1); if (group_num >= match.size()) throw InvalidSourceException("capture group number in scope name out of range"); return match[group_num].substr(text); } } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: brwhead.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: hr $ $Date: 2007-06-27 21:08:04 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svtools.hxx" #include <svtools/brwhead.hxx> #include <svtools/brwbox.hxx> #ifndef GCC #endif //=================================================================== BrowserHeader::BrowserHeader( BrowseBox* pParent, WinBits nWinBits ) :HeaderBar( pParent, nWinBits ) ,_pBrowseBox( pParent ) { long nHeight = pParent->IsZoom() ? pParent->CalcZoom(pParent->GetTitleHeight()) : pParent->GetTitleHeight(); SetPosSizePixel( Point( 0, 0), Size( pParent->GetOutputSizePixel().Width(), nHeight ) ); Show(); } //------------------------------------------------------------------- void BrowserHeader::Command( const CommandEvent& rCEvt ) { if ( !GetCurItemId() && COMMAND_CONTEXTMENU == rCEvt.GetCommand() ) { Point aPos( rCEvt.GetMousePosPixel() ); if ( _pBrowseBox->IsFrozen(0) ) aPos.X() += _pBrowseBox->GetColumnWidth(0); _pBrowseBox->GetDataWindow().Command( CommandEvent( Point( aPos.X(), aPos.Y() - GetSizePixel().Height() ), COMMAND_CONTEXTMENU, rCEvt.IsMouseEvent() ) ); } } //------------------------------------------------------------------- void BrowserHeader::Select() { HeaderBar::Select(); } //------------------------------------------------------------------- void BrowserHeader::EndDrag() { // call before other actions, it looks more nice in most cases HeaderBar::EndDrag(); Update(); // not aborted? USHORT nId = GetCurItemId(); if ( nId ) { // Handle-Column? if ( nId == USHRT_MAX-1 ) nId = 0; if ( !IsItemMode() ) { // column resize _pBrowseBox->SetColumnWidth( nId, GetItemSize( nId ) ); _pBrowseBox->ColumnResized( nId ); SetItemSize( nId, _pBrowseBox->GetColumnWidth( nId ) ); } else { // column drag // Hat sich die Position eigentlich veraendert // Handlecolumn beruecksichtigen USHORT nOldPos = _pBrowseBox->GetColumnPos(nId), nNewPos = GetItemPos( nId ); if (!_pBrowseBox->GetColumnId(0)) // Handle nNewPos++; if (nOldPos != nNewPos) { _pBrowseBox->SetColumnPos( nId, nNewPos ); _pBrowseBox->ColumnMoved( nId ); } } } } // ----------------------------------------------------------------------------- <commit_msg>INTEGRATION: CWS changefileheader (1.7.246); FILE MERGED 2008/03/31 13:01:20 rt 1.7.246.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: brwhead.cxx,v $ * $Revision: 1.8 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svtools.hxx" #include <svtools/brwhead.hxx> #include <svtools/brwbox.hxx> #ifndef GCC #endif //=================================================================== BrowserHeader::BrowserHeader( BrowseBox* pParent, WinBits nWinBits ) :HeaderBar( pParent, nWinBits ) ,_pBrowseBox( pParent ) { long nHeight = pParent->IsZoom() ? pParent->CalcZoom(pParent->GetTitleHeight()) : pParent->GetTitleHeight(); SetPosSizePixel( Point( 0, 0), Size( pParent->GetOutputSizePixel().Width(), nHeight ) ); Show(); } //------------------------------------------------------------------- void BrowserHeader::Command( const CommandEvent& rCEvt ) { if ( !GetCurItemId() && COMMAND_CONTEXTMENU == rCEvt.GetCommand() ) { Point aPos( rCEvt.GetMousePosPixel() ); if ( _pBrowseBox->IsFrozen(0) ) aPos.X() += _pBrowseBox->GetColumnWidth(0); _pBrowseBox->GetDataWindow().Command( CommandEvent( Point( aPos.X(), aPos.Y() - GetSizePixel().Height() ), COMMAND_CONTEXTMENU, rCEvt.IsMouseEvent() ) ); } } //------------------------------------------------------------------- void BrowserHeader::Select() { HeaderBar::Select(); } //------------------------------------------------------------------- void BrowserHeader::EndDrag() { // call before other actions, it looks more nice in most cases HeaderBar::EndDrag(); Update(); // not aborted? USHORT nId = GetCurItemId(); if ( nId ) { // Handle-Column? if ( nId == USHRT_MAX-1 ) nId = 0; if ( !IsItemMode() ) { // column resize _pBrowseBox->SetColumnWidth( nId, GetItemSize( nId ) ); _pBrowseBox->ColumnResized( nId ); SetItemSize( nId, _pBrowseBox->GetColumnWidth( nId ) ); } else { // column drag // Hat sich die Position eigentlich veraendert // Handlecolumn beruecksichtigen USHORT nOldPos = _pBrowseBox->GetColumnPos(nId), nNewPos = GetItemPos( nId ); if (!_pBrowseBox->GetColumnId(0)) // Handle nNewPos++; if (nOldPos != nNewPos) { _pBrowseBox->SetColumnPos( nId, nNewPos ); _pBrowseBox->ColumnMoved( nId ); } } } } // ----------------------------------------------------------------------------- <|endoftext|>
<commit_before><commit_msg>sw: Prefix LinesAndTable member variables.<commit_after><|endoftext|>
<commit_before><commit_msg>coverity#705921 Dereference before null check<commit_after><|endoftext|>
<commit_before>// Copyright 2014 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 <iostream> #include <fstream> #include <exception> #include <string> #include <utility> #include <map> #include <iomanip> #include <ArgumentList.hpp> #include <utils.hpp> int main(int argc, char * argv[]) { // DMs unsigned int nrDMs = 0; float firstDM = 0.0f; float stepDM = 0.0f; // Periods unsigned int nrPeriods = 0; unsigned int firstPeriod = 0; unsigned int stepPeriod = 0; // Sampling unsigned int nrSamplesPerSecond = 0; // I/O std::string outFilename; std::ifstream searchFile; std::ofstream outFile; // Data bool exclusive = false; bool * exclusionMapDM = 0; bool * exclusionMapP = 0; float percentile = 0; std::multimap< float, std::pair< unsigned int, unsigned int > > snrList; isa::utils::ArgumentList args(argc, argv); try { exclusive = args.getSwitch("-exclusive"); if ( exclusive ) { nrDMs = args.getSwitchArgument< unsigned int >("-dms"); nrPeriods = args.getSwitchArgument< unsigned int >("-periods"); } outFilename = args.getSwitchArgument< std::string >("-output"); firstDM = args.getSwitchArgument< float >("-dm_first"); stepDM = args.getSwitchArgument< float >("-dm_step"); firstPeriod = args.getSwitchArgument< unsigned int >("-period_first"); stepPeriod = args.getSwitchArgument< unsigned int >("-period_step"); nrSamplesPerSecond = args.getSwitchArgument< unsigned int >("-samples"); percentile = args.getSwitchArgument< float >("-percentile"); } catch ( isa::utils::EmptyCommandLine & err ) { std::cerr << args.getName() << " [-exclusive] -output ... -dm_first ... -dm_step ... -period_first ... -period_step ... -samples ... -percentile ... input" << std::endl; std::cerr << "\t -exclusive -dms ... -periods ..." << std::endl; return 1; } catch ( std::exception & err ) { std::cerr << err.what() << std::endl; return 1; } // Read the SNR data try { while ( true ) { searchFile.open(args.getFirst< std::string >()); while ( ! searchFile.eof() ) { std::string temp; unsigned int splitPoint = 0; unsigned int DM = 0; unsigned int period = 0; float snr = 0.0f; std::getline(searchFile, temp); if ( ! std::isdigit(temp[0]) ) { continue; } splitPoint = temp.find(" "); period = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)); temp = temp.substr(splitPoint + 1); splitPoint = temp.find(" "); DM = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)); temp = temp.substr(splitPoint + 1); splitPoint = temp.find(" "); snr = isa::utils::castToType< std::string, float >(temp); snrList.insert(std::make_pair(snr, std::make_pair(DM, period))); } searchFile.close(); } } catch ( isa::utils::EmptyCommandLine & err ) { } // Print the percentile unsigned int lowerLimit = static_cast< unsigned int >((percentile * snrList.size()) / 100.0); unsigned int counter = snrList.size() - 1; if ( exclusive ) { exclusionMapDM = new bool [nrDMs]; std::memset(reinterpret_cast< void * >(exclusionMapDM, 0, nrDMs * sizeof(bool))); exclusionMapP = new bool [nrPeriods]; std::memset(reinterpret_cast< void * >(exclusionMapP, 0, nrDMs * sizeof(bool))); } outFile.open(outFilename); outFile << std::fixed; outFile << "# DMIndex DM periodIndex period snr" << std::endl; for ( std::multimap< float, std::pair< unsigned int, unsigned int> >::const_reverse_iterator item = snrList.crend(); counter >= lowerLimit; counter-- ) { ++item; if ( exclusive && (exclusionMapDM[(*item).second.first] || exclusionMapP[(*item).second.second]) ) { continue; } else if ( exclusionMapDM[(*item).second.first] || exclusionMapP[(*item).second.second] ) { exclusionMapDM[(*item).second.first] = true; exclusionMapP[(*item).second.second] = true; } outFile << std::setprecision(2); outFile << (*item).second.first << " " << firstDM + ((*item).second.first * stepDM) << " "; outFile << std::setprecision(6); outFile << (*item).second.second << " " << (firstPeriod + ((*item).second.second * stepPeriod)) / static_cast< float >(nrSamplesPerSecond) << " "; outFile << (*item).first << std::endl; } delete [] exclusionMapDM; delete [] exclusionMapP; outFile.close(); return 0; } <commit_msg>Adding header file.<commit_after>// Copyright 2014 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 <iostream> #include <fstream> #include <exception> #include <string> #include <utility> #include <map> #include <iomanip> #include <cstring> #include <ArgumentList.hpp> #include <utils.hpp> int main(int argc, char * argv[]) { // DMs unsigned int nrDMs = 0; float firstDM = 0.0f; float stepDM = 0.0f; // Periods unsigned int nrPeriods = 0; unsigned int firstPeriod = 0; unsigned int stepPeriod = 0; // Sampling unsigned int nrSamplesPerSecond = 0; // I/O std::string outFilename; std::ifstream searchFile; std::ofstream outFile; // Data bool exclusive = false; bool * exclusionMapDM = 0; bool * exclusionMapP = 0; float percentile = 0; std::multimap< float, std::pair< unsigned int, unsigned int > > snrList; isa::utils::ArgumentList args(argc, argv); try { exclusive = args.getSwitch("-exclusive"); if ( exclusive ) { nrDMs = args.getSwitchArgument< unsigned int >("-dms"); nrPeriods = args.getSwitchArgument< unsigned int >("-periods"); } outFilename = args.getSwitchArgument< std::string >("-output"); firstDM = args.getSwitchArgument< float >("-dm_first"); stepDM = args.getSwitchArgument< float >("-dm_step"); firstPeriod = args.getSwitchArgument< unsigned int >("-period_first"); stepPeriod = args.getSwitchArgument< unsigned int >("-period_step"); nrSamplesPerSecond = args.getSwitchArgument< unsigned int >("-samples"); percentile = args.getSwitchArgument< float >("-percentile"); } catch ( isa::utils::EmptyCommandLine & err ) { std::cerr << args.getName() << " [-exclusive] -output ... -dm_first ... -dm_step ... -period_first ... -period_step ... -samples ... -percentile ... input" << std::endl; std::cerr << "\t -exclusive -dms ... -periods ..." << std::endl; return 1; } catch ( std::exception & err ) { std::cerr << err.what() << std::endl; return 1; } // Read the SNR data try { while ( true ) { searchFile.open(args.getFirst< std::string >()); while ( ! searchFile.eof() ) { std::string temp; unsigned int splitPoint = 0; unsigned int DM = 0; unsigned int period = 0; float snr = 0.0f; std::getline(searchFile, temp); if ( ! std::isdigit(temp[0]) ) { continue; } splitPoint = temp.find(" "); period = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)); temp = temp.substr(splitPoint + 1); splitPoint = temp.find(" "); DM = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)); temp = temp.substr(splitPoint + 1); splitPoint = temp.find(" "); snr = isa::utils::castToType< std::string, float >(temp); snrList.insert(std::make_pair(snr, std::make_pair(DM, period))); } searchFile.close(); } } catch ( isa::utils::EmptyCommandLine & err ) { } // Print the percentile unsigned int lowerLimit = static_cast< unsigned int >((percentile * snrList.size()) / 100.0); unsigned int counter = snrList.size() - 1; if ( exclusive ) { exclusionMapDM = new bool [nrDMs]; std::memset(reinterpret_cast< void * >(exclusionMapDM, 0, nrDMs * sizeof(bool))); exclusionMapP = new bool [nrPeriods]; std::memset(reinterpret_cast< void * >(exclusionMapP, 0, nrDMs * sizeof(bool))); } outFile.open(outFilename); outFile << std::fixed; outFile << "# DMIndex DM periodIndex period snr" << std::endl; for ( std::multimap< float, std::pair< unsigned int, unsigned int> >::const_reverse_iterator item = snrList.crend(); counter >= lowerLimit; counter-- ) { ++item; if ( exclusive && (exclusionMapDM[(*item).second.first] || exclusionMapP[(*item).second.second]) ) { continue; } else if ( exclusionMapDM[(*item).second.first] || exclusionMapP[(*item).second.second] ) { exclusionMapDM[(*item).second.first] = true; exclusionMapP[(*item).second.second] = true; } outFile << std::setprecision(2); outFile << (*item).second.first << " " << firstDM + ((*item).second.first * stepDM) << " "; outFile << std::setprecision(6); outFile << (*item).second.second << " " << (firstPeriod + ((*item).second.second * stepPeriod)) / static_cast< float >(nrSamplesPerSecond) << " "; outFile << (*item).first << std::endl; } delete [] exclusionMapDM; delete [] exclusionMapP; outFile.close(); return 0; } <|endoftext|>
<commit_before><commit_msg>sw: remove SwEventListenerContainer in SwXTextCursor<commit_after><|endoftext|>
<commit_before>3f6ce754-2e4e-11e5-9284-b827eb9e62be<commit_msg>3f71f334-2e4e-11e5-9284-b827eb9e62be<commit_after>3f71f334-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before><commit_msg>whops, index swap<commit_after><|endoftext|>
<commit_before>df3bf04c-2e4c-11e5-9284-b827eb9e62be<commit_msg>df595b00-2e4c-11e5-9284-b827eb9e62be<commit_after>df595b00-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>01e539da-2e4f-11e5-9284-b827eb9e62be<commit_msg>01ea2cec-2e4f-11e5-9284-b827eb9e62be<commit_after>01ea2cec-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>#pragma once // `krbn::cf_utility::run_loop_thread` can be used safely in a multi-threaded environment. #include "boost_defs.hpp" #include "dispatcher.hpp" #include "logger.hpp" #include <CoreFoundation/CoreFoundation.h> #include <boost/optional.hpp> #include <mutex> #include <string> #include <thread> namespace krbn { class cf_utility final { public: template <typename T> class deleter final { public: using pointer = T; void operator()(T _Nullable ref) { if (ref) { CFRelease(ref); } } }; // ======================================== // Converts // ======================================== static boost::optional<std::string> to_string(CFTypeRef _Nullable value) { if (!value) { return boost::none; } if (CFStringGetTypeID() != CFGetTypeID(value)) { return boost::none; } auto cfstring = static_cast<CFStringRef>(value); std::string string; if (auto p = CFStringGetCStringPtr(cfstring, kCFStringEncodingUTF8)) { string = p; } else { auto length = CFStringGetLength(cfstring); auto max_size = CFStringGetMaximumSizeForEncoding(length, kCFStringEncodingUTF8) + 1; char* buffer = new char[max_size]; if (CFStringGetCString(cfstring, buffer, max_size, kCFStringEncodingUTF8)) { string = buffer; } delete[] buffer; } return string; } static CFStringRef _Nullable create_cfstring(const std::string& string) { return CFStringCreateWithCString(kCFAllocatorDefault, string.c_str(), kCFStringEncodingUTF8); } static boost::optional<int64_t> to_int64_t(CFTypeRef _Nullable value) { if (!value) { return boost::none; } if (CFNumberGetTypeID() != CFGetTypeID(value)) { return boost::none; } auto cfnumber = static_cast<CFNumberRef>(value); int64_t result; if (CFNumberGetValue(cfnumber, kCFNumberSInt64Type, &result)) { return result; } return boost::none; } // ======================================== // CFArray, CFMutableArray // ======================================== static CFArrayRef _Nonnull create_empty_cfarray(void) { return CFArrayCreate(nullptr, nullptr, 0, &kCFTypeArrayCallBacks); } static CFMutableArrayRef _Nonnull create_cfmutablearray(CFIndex capacity = 0) { return CFArrayCreateMutable(nullptr, capacity, &kCFTypeArrayCallBacks); } template <typename T> static T _Nullable get_value(CFArrayRef _Nonnull array, CFIndex index) { if (array && index < CFArrayGetCount(array)) { return static_cast<T>(const_cast<void*>(CFArrayGetValueAtIndex(array, index))); } return nullptr; } template <typename T> static bool exists(CFArrayRef _Nonnull array, T _Nonnull value) { if (array) { CFRange range = {0, CFArrayGetCount(array)}; if (CFArrayContainsValue(array, range, value)) { return true; } } return false; } // ======================================== // CFDictionary, CFMutableDictionary // ======================================== static CFMutableDictionaryRef _Nonnull create_cfmutabledictionary(CFIndex capacity = 0) { return CFDictionaryCreateMutable(nullptr, capacity, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); } // ======================================== // CFRunLoop // ======================================== /** * Create a thread and then run CFRunLoop on the thread. */ class run_loop_thread final { public: run_loop_thread(void) : run_loop_(nullptr) { running_wait_ = pqrs::dispatcher::make_wait(); thread_ = std::thread([this] { run_loop_ = CFRunLoopGetCurrent(); CFRetain(run_loop_); // Append empty source to prevent immediately quitting of `CFRunLoopRun`. auto context = CFRunLoopSourceContext(); context.perform = perform; auto source = CFRunLoopSourceCreate(kCFAllocatorDefault, 0, &context); CFRunLoopAddSource(run_loop_, source, kCFRunLoopCommonModes); // Run CFRunLoopPerformBlock(run_loop_, kCFRunLoopCommonModes, ^{ running_wait_->notify(); }); CFRunLoopRun(); // Remove source CFRunLoopRemoveSource(run_loop_, source, kCFRunLoopCommonModes); CFRelease(source); }); } ~run_loop_thread(void) { if (thread_.joinable()) { logger::get_logger().error("Call `cf_utility::run_loop_thread::terminate` before destroy `cf_utility::run_loop_thread`"); terminate(); } if (run_loop_) { CFRelease(run_loop_); } } void terminate(void) { enqueue(^{ CFRunLoopStop(run_loop_); }); if (thread_.joinable()) { thread_.join(); } } CFRunLoopRef _Nonnull get_run_loop(void) const { // We wait until running to avoid a segmentation fault which is described in `enqueue`. wait_until_running(); return run_loop_; } void wake(void) const { // Do not touch run_loop_ until `CFRunLoopRun` is called. // A segmentation fault occurs if we touch `run_loop_` while `CFRunLoopRun' is processing. wait_until_running(); CFRunLoopWakeUp(run_loop_); } void enqueue_and_wait(const std::function<void(void)>& function) const { auto wait = pqrs::dispatcher::make_wait(); enqueue(^{ function(); wait->notify(); }); wait->wait_notice(); } private: void enqueue(void (^_Nonnull block)(void)) const { // Do not call `CFRunLoopPerformBlock` until `CFRunLoopRun` is called. // A segmentation fault occurs if we call `CFRunLoopPerformBlock` while `CFRunLoopRun' is processing. wait_until_running(); CFRunLoopPerformBlock(run_loop_, kCFRunLoopCommonModes, block); CFRunLoopWakeUp(run_loop_); } void wait_until_running(void) const { running_wait_->wait_notice(); } static void perform(void* _Nullable info) { } std::thread thread_; CFRunLoopRef _Nullable run_loop_; std::shared_ptr<pqrs::dispatcher::wait> running_wait_; }; }; } // namespace krbn <commit_msg>add cf_utility::set_cfmutabledictionary_value<commit_after>#pragma once // `krbn::cf_utility::run_loop_thread` can be used safely in a multi-threaded environment. #include "boost_defs.hpp" #include "dispatcher.hpp" #include "logger.hpp" #include <CoreFoundation/CoreFoundation.h> #include <boost/optional.hpp> #include <mutex> #include <string> #include <thread> namespace krbn { class cf_utility final { public: template <typename T> class deleter final { public: using pointer = T; void operator()(T _Nullable ref) { if (ref) { CFRelease(ref); } } }; // ======================================== // Converts // ======================================== static boost::optional<std::string> to_string(CFTypeRef _Nullable value) { if (!value) { return boost::none; } if (CFStringGetTypeID() != CFGetTypeID(value)) { return boost::none; } auto cfstring = static_cast<CFStringRef>(value); std::string string; if (auto p = CFStringGetCStringPtr(cfstring, kCFStringEncodingUTF8)) { string = p; } else { auto length = CFStringGetLength(cfstring); auto max_size = CFStringGetMaximumSizeForEncoding(length, kCFStringEncodingUTF8) + 1; char* buffer = new char[max_size]; if (CFStringGetCString(cfstring, buffer, max_size, kCFStringEncodingUTF8)) { string = buffer; } delete[] buffer; } return string; } static CFStringRef _Nullable create_cfstring(const std::string& string) { return CFStringCreateWithCString(kCFAllocatorDefault, string.c_str(), kCFStringEncodingUTF8); } static boost::optional<int64_t> to_int64_t(CFTypeRef _Nullable value) { if (!value) { return boost::none; } if (CFNumberGetTypeID() != CFGetTypeID(value)) { return boost::none; } auto cfnumber = static_cast<CFNumberRef>(value); int64_t result; if (CFNumberGetValue(cfnumber, kCFNumberSInt64Type, &result)) { return result; } return boost::none; } // ======================================== // CFArray, CFMutableArray // ======================================== static CFArrayRef _Nonnull create_empty_cfarray(void) { return CFArrayCreate(nullptr, nullptr, 0, &kCFTypeArrayCallBacks); } static CFMutableArrayRef _Nonnull create_cfmutablearray(CFIndex capacity = 0) { return CFArrayCreateMutable(nullptr, capacity, &kCFTypeArrayCallBacks); } template <typename T> static T _Nullable get_value(CFArrayRef _Nonnull array, CFIndex index) { if (array && index < CFArrayGetCount(array)) { return static_cast<T>(const_cast<void*>(CFArrayGetValueAtIndex(array, index))); } return nullptr; } template <typename T> static bool exists(CFArrayRef _Nonnull array, T _Nonnull value) { if (array) { CFRange range = {0, CFArrayGetCount(array)}; if (CFArrayContainsValue(array, range, value)) { return true; } } return false; } // ======================================== // CFDictionary, CFMutableDictionary // ======================================== static CFMutableDictionaryRef _Nonnull create_cfmutabledictionary(CFIndex capacity = 0) { return CFDictionaryCreateMutable(nullptr, capacity, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); } static void set_cfmutabledictionary_value(CFMutableDictionaryRef _Nonnull dictionary, CFStringRef _Nonnull key, int64_t value) { if (auto number = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt64Type, &value)) { CFDictionarySetValue(dictionary, key, number); CFRelease(number); } } // ======================================== // CFRunLoop // ======================================== /** * Create a thread and then run CFRunLoop on the thread. */ class run_loop_thread final { public: run_loop_thread(void) : run_loop_(nullptr) { running_wait_ = pqrs::dispatcher::make_wait(); thread_ = std::thread([this] { run_loop_ = CFRunLoopGetCurrent(); CFRetain(run_loop_); // Append empty source to prevent immediately quitting of `CFRunLoopRun`. auto context = CFRunLoopSourceContext(); context.perform = perform; auto source = CFRunLoopSourceCreate(kCFAllocatorDefault, 0, &context); CFRunLoopAddSource(run_loop_, source, kCFRunLoopCommonModes); // Run CFRunLoopPerformBlock(run_loop_, kCFRunLoopCommonModes, ^{ running_wait_->notify(); }); CFRunLoopRun(); // Remove source CFRunLoopRemoveSource(run_loop_, source, kCFRunLoopCommonModes); CFRelease(source); }); } ~run_loop_thread(void) { if (thread_.joinable()) { logger::get_logger().error("Call `cf_utility::run_loop_thread::terminate` before destroy `cf_utility::run_loop_thread`"); terminate(); } if (run_loop_) { CFRelease(run_loop_); } } void terminate(void) { enqueue(^{ CFRunLoopStop(run_loop_); }); if (thread_.joinable()) { thread_.join(); } } CFRunLoopRef _Nonnull get_run_loop(void) const { // We wait until running to avoid a segmentation fault which is described in `enqueue`. wait_until_running(); return run_loop_; } void wake(void) const { // Do not touch run_loop_ until `CFRunLoopRun` is called. // A segmentation fault occurs if we touch `run_loop_` while `CFRunLoopRun' is processing. wait_until_running(); CFRunLoopWakeUp(run_loop_); } void enqueue_and_wait(const std::function<void(void)>& function) const { auto wait = pqrs::dispatcher::make_wait(); enqueue(^{ function(); wait->notify(); }); wait->wait_notice(); } private: void enqueue(void (^_Nonnull block)(void)) const { // Do not call `CFRunLoopPerformBlock` until `CFRunLoopRun` is called. // A segmentation fault occurs if we call `CFRunLoopPerformBlock` while `CFRunLoopRun' is processing. wait_until_running(); CFRunLoopPerformBlock(run_loop_, kCFRunLoopCommonModes, block); CFRunLoopWakeUp(run_loop_); } void wait_until_running(void) const { running_wait_->wait_notice(); } static void perform(void* _Nullable info) { } std::thread thread_; CFRunLoopRef _Nullable run_loop_; std::shared_ptr<pqrs::dispatcher::wait> running_wait_; }; }; } // namespace krbn <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: wrtasc.cxx,v $ * * $Revision: 1.11 $ * * last change: $Author: ihi $ $Date: 2007-07-12 10:44:33 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sw.hxx" #ifndef _HINTIDS_HXX #include <hintids.hxx> #endif #ifndef _OSL_ENDIAN_H_ #include <osl/endian.h> #endif #ifndef _STREAM_HXX #include <tools/stream.hxx> #endif #ifndef _PAM_HXX #include <pam.hxx> #endif #ifndef _DOC_HXX #include <doc.hxx> #endif #ifndef _NDTXT_HXX #include <ndtxt.hxx> #endif #ifndef _MDIEXP_HXX #include <mdiexp.hxx> // ...Percent() #endif #ifndef _DOCARY_HXX #include <docary.hxx> #endif #ifndef _FMTCNTNT_HXX //autogen #include <fmtcntnt.hxx> #endif #ifndef _FRMFMT_HXX //autogen #include <frmfmt.hxx> #endif #ifndef _WRTASC_HXX #include <wrtasc.hxx> #endif #ifndef _STATSTR_HRC #include <statstr.hrc> // ResId fuer Statusleiste #endif //----------------------------------------------------------------- SwASCWriter::SwASCWriter( const String& rFltNm ) { SwAsciiOptions aNewOpts; switch( 5 <= rFltNm.Len() ? rFltNm.GetChar( 4 ) : 0 ) { case 'D': #if !defined(PM2) aNewOpts.SetCharSet( RTL_TEXTENCODING_IBM_850 ); aNewOpts.SetParaFlags( LINEEND_CRLF ); #endif if( 5 < rFltNm.Len() ) switch( rFltNm.Copy( 5 ).ToInt32() ) { case 437: aNewOpts.SetCharSet( RTL_TEXTENCODING_IBM_437 ); break; case 850: aNewOpts.SetCharSet( RTL_TEXTENCODING_IBM_850 ); break; case 860: aNewOpts.SetCharSet( RTL_TEXTENCODING_IBM_860 ); break; case 861: aNewOpts.SetCharSet( RTL_TEXTENCODING_IBM_861 ); break; case 863: aNewOpts.SetCharSet( RTL_TEXTENCODING_IBM_863 ); break; case 865: aNewOpts.SetCharSet( RTL_TEXTENCODING_IBM_865 ); break; } break; case 'A': #if !defined(WIN) && !defined(WNT) aNewOpts.SetCharSet( RTL_TEXTENCODING_MS_1252 ); aNewOpts.SetParaFlags( LINEEND_CRLF ); #endif break; case 'M': aNewOpts.SetCharSet( RTL_TEXTENCODING_APPLE_ROMAN ); aNewOpts.SetParaFlags( LINEEND_CR ); break; case 'X': #if !defined(UNX) aNewOpts.SetCharSet( RTL_TEXTENCODING_MS_1252 ); aNewOpts.SetParaFlags( LINEEND_LF ); #endif break; default: if( rFltNm.Copy( 4 ).EqualsAscii( "_DLG" )) { // use the options aNewOpts = GetAsciiOptions(); } } SetAsciiOptions( aNewOpts ); } SwASCWriter::~SwASCWriter() {} ULONG SwASCWriter::WriteStream() { sal_Char cLineEnd[ 3 ]; sal_Char* pCEnd = cLineEnd; if( bASCII_ParaAsCR ) // falls vorgegeben ist. *pCEnd++ = '\015'; else if( bASCII_ParaAsBlanc ) *pCEnd++ = ' '; else switch( GetAsciiOptions().GetParaFlags() ) { case LINEEND_CR: *pCEnd++ = '\015'; break; case LINEEND_LF: *pCEnd++ = '\012'; break; case LINEEND_CRLF: *pCEnd++ = '\015', *pCEnd++ = '\012'; break; } *pCEnd = 0; sLineEnd.AssignAscii( cLineEnd ); long nMaxNode = pDoc->GetNodes().Count(); if( bShowProgress ) ::StartProgress( STR_STATSTR_W4WWRITE, 0, nMaxNode, pDoc->GetDocShell() ); SwPaM* pPam = pOrigPam; BOOL bWriteSttTag = bUCS2_WithStartChar && (RTL_TEXTENCODING_UCS2 == GetAsciiOptions().GetCharSet() || RTL_TEXTENCODING_UTF8 == GetAsciiOptions().GetCharSet()); rtl_TextEncoding eOld = Strm().GetStreamCharSet(); Strm().SetStreamCharSet( GetAsciiOptions().GetCharSet() ); // gebe alle Bereich des Pams in das ASC-File aus. do { BOOL bTstFly = TRUE; while( pCurPam->GetPoint()->nNode.GetIndex() < pCurPam->GetMark()->nNode.GetIndex() || (pCurPam->GetPoint()->nNode.GetIndex() == pCurPam->GetMark()->nNode.GetIndex() && pCurPam->GetPoint()->nContent.GetIndex() <= pCurPam->GetMark()->nContent.GetIndex()) ) { SwTxtNode* pNd = pCurPam->GetPoint()->nNode.GetNode().GetTxtNode(); if( pNd ) { // sollten nur Rahmen vorhanden sein? // (Moeglich, wenn Rahmen-Selektion ins Clipboard // gestellt wurde) if( bTstFly && bWriteAll && // keine Laenge !pNd->GetTxt().Len() && // Rahmen vorhanden pDoc->GetSpzFrmFmts()->Count() && // nur ein Node im Array pDoc->GetNodes().GetEndOfExtras().GetIndex() + 3 == pDoc->GetNodes().GetEndOfContent().GetIndex() && // und genau der ist selektiert pDoc->GetNodes().GetEndOfContent().GetIndex() - 1 == pCurPam->GetPoint()->nNode.GetIndex() ) { // dann den Inhalt vom Rahmen ausgeben. // dieser steht immer an Position 0 !! SwFrmFmt* pFmt = (*pDoc->GetSpzFrmFmts())[ 0 ]; const SwNodeIndex* pIdx = pFmt->GetCntnt().GetCntntIdx(); if( pIdx ) { delete pCurPam; pCurPam = NewSwPaM( *pDoc, pIdx->GetIndex(), pIdx->GetNode().EndOfSectionIndex() ); pCurPam->Exchange(); continue; // while-Schleife neu aufsetzen !! } } else { if (bWriteSttTag) { switch(GetAsciiOptions().GetCharSet()) { case RTL_TEXTENCODING_UTF8: Strm() << BYTE(0xEF) << BYTE(0xBB) << BYTE(0xBF); break; case RTL_TEXTENCODING_UCS2: //Strm().StartWritingUnicodeText(); Strm().SetEndianSwap(FALSE); #ifdef OSL_LITENDIAN Strm() << BYTE(0xFF) << BYTE(0xFE); #else Strm() << BYTE(0xFE) << BYTE(0xFF); #endif break; } bWriteSttTag = FALSE; } Out( aASCNodeFnTab, *pNd, *this ); } bTstFly = FALSE; // eimal Testen reicht } if( !pCurPam->Move( fnMoveForward, fnGoNode ) ) break; if( bShowProgress ) ::SetProgressState( pCurPam->GetPoint()->nNode.GetIndex(), pDoc->GetDocShell() ); // Wie weit ? } } while( CopyNextPam( &pPam ) ); // bis alle Pam bearbeitet Strm().SetStreamCharSet( eOld ); if( bShowProgress ) ::EndProgress( pDoc->GetDocShell() ); return 0; } void GetASCWriter( const String& rFltNm, const String& rBaseURL, WriterRef& xRet ) { xRet = new SwASCWriter( rFltNm ); } <commit_msg>INTEGRATION: CWS swwarnings (1.10.222); FILE MERGED 2007/08/20 15:43:27 tl 1.10.222.2: RESYNC: (1.10-1.11); FILE MERGED 2007/03/15 15:52:03 tl 1.10.222.1: #i69287# warning-free code<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: wrtasc.cxx,v $ * * $Revision: 1.12 $ * * last change: $Author: hr $ $Date: 2007-09-27 09:44:25 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sw.hxx" #ifndef _HINTIDS_HXX #include <hintids.hxx> #endif #ifndef _OSL_ENDIAN_H_ #include <osl/endian.h> #endif #ifndef _STREAM_HXX #include <tools/stream.hxx> #endif #ifndef _PAM_HXX #include <pam.hxx> #endif #ifndef _DOC_HXX #include <doc.hxx> #endif #ifndef _NDTXT_HXX #include <ndtxt.hxx> #endif #ifndef _MDIEXP_HXX #include <mdiexp.hxx> // ...Percent() #endif #ifndef _DOCARY_HXX #include <docary.hxx> #endif #ifndef _FMTCNTNT_HXX //autogen #include <fmtcntnt.hxx> #endif #ifndef _FRMFMT_HXX //autogen #include <frmfmt.hxx> #endif #ifndef _WRTASC_HXX #include <wrtasc.hxx> #endif #ifndef _STATSTR_HRC #include <statstr.hrc> // ResId fuer Statusleiste #endif //----------------------------------------------------------------- SwASCWriter::SwASCWriter( const String& rFltNm ) { SwAsciiOptions aNewOpts; switch( 5 <= rFltNm.Len() ? rFltNm.GetChar( 4 ) : 0 ) { case 'D': #if !defined(PM2) aNewOpts.SetCharSet( RTL_TEXTENCODING_IBM_850 ); aNewOpts.SetParaFlags( LINEEND_CRLF ); #endif if( 5 < rFltNm.Len() ) switch( rFltNm.Copy( 5 ).ToInt32() ) { case 437: aNewOpts.SetCharSet( RTL_TEXTENCODING_IBM_437 ); break; case 850: aNewOpts.SetCharSet( RTL_TEXTENCODING_IBM_850 ); break; case 860: aNewOpts.SetCharSet( RTL_TEXTENCODING_IBM_860 ); break; case 861: aNewOpts.SetCharSet( RTL_TEXTENCODING_IBM_861 ); break; case 863: aNewOpts.SetCharSet( RTL_TEXTENCODING_IBM_863 ); break; case 865: aNewOpts.SetCharSet( RTL_TEXTENCODING_IBM_865 ); break; } break; case 'A': #if !defined(WIN) && !defined(WNT) aNewOpts.SetCharSet( RTL_TEXTENCODING_MS_1252 ); aNewOpts.SetParaFlags( LINEEND_CRLF ); #endif break; case 'M': aNewOpts.SetCharSet( RTL_TEXTENCODING_APPLE_ROMAN ); aNewOpts.SetParaFlags( LINEEND_CR ); break; case 'X': #if !defined(UNX) aNewOpts.SetCharSet( RTL_TEXTENCODING_MS_1252 ); aNewOpts.SetParaFlags( LINEEND_LF ); #endif break; default: if( rFltNm.Copy( 4 ).EqualsAscii( "_DLG" )) { // use the options aNewOpts = GetAsciiOptions(); } } SetAsciiOptions( aNewOpts ); } SwASCWriter::~SwASCWriter() {} ULONG SwASCWriter::WriteStream() { sal_Char cLineEnd[ 3 ]; sal_Char* pCEnd = cLineEnd; if( bASCII_ParaAsCR ) // falls vorgegeben ist. *pCEnd++ = '\015'; else if( bASCII_ParaAsBlanc ) *pCEnd++ = ' '; else switch( GetAsciiOptions().GetParaFlags() ) { case LINEEND_CR: *pCEnd++ = '\015'; break; case LINEEND_LF: *pCEnd++ = '\012'; break; case LINEEND_CRLF: *pCEnd++ = '\015', *pCEnd++ = '\012'; break; } *pCEnd = 0; sLineEnd.AssignAscii( cLineEnd ); long nMaxNode = pDoc->GetNodes().Count(); if( bShowProgress ) ::StartProgress( STR_STATSTR_W4WWRITE, 0, nMaxNode, pDoc->GetDocShell() ); SwPaM* pPam = pOrigPam; BOOL bWriteSttTag = bUCS2_WithStartChar && (RTL_TEXTENCODING_UCS2 == GetAsciiOptions().GetCharSet() || RTL_TEXTENCODING_UTF8 == GetAsciiOptions().GetCharSet()); rtl_TextEncoding eOld = Strm().GetStreamCharSet(); Strm().SetStreamCharSet( GetAsciiOptions().GetCharSet() ); // gebe alle Bereich des Pams in das ASC-File aus. do { BOOL bTstFly = TRUE; while( pCurPam->GetPoint()->nNode.GetIndex() < pCurPam->GetMark()->nNode.GetIndex() || (pCurPam->GetPoint()->nNode.GetIndex() == pCurPam->GetMark()->nNode.GetIndex() && pCurPam->GetPoint()->nContent.GetIndex() <= pCurPam->GetMark()->nContent.GetIndex()) ) { SwTxtNode* pNd = pCurPam->GetPoint()->nNode.GetNode().GetTxtNode(); if( pNd ) { // sollten nur Rahmen vorhanden sein? // (Moeglich, wenn Rahmen-Selektion ins Clipboard // gestellt wurde) if( bTstFly && bWriteAll && // keine Laenge !pNd->GetTxt().Len() && // Rahmen vorhanden pDoc->GetSpzFrmFmts()->Count() && // nur ein Node im Array pDoc->GetNodes().GetEndOfExtras().GetIndex() + 3 == pDoc->GetNodes().GetEndOfContent().GetIndex() && // und genau der ist selektiert pDoc->GetNodes().GetEndOfContent().GetIndex() - 1 == pCurPam->GetPoint()->nNode.GetIndex() ) { // dann den Inhalt vom Rahmen ausgeben. // dieser steht immer an Position 0 !! SwFrmFmt* pFmt = (*pDoc->GetSpzFrmFmts())[ 0 ]; const SwNodeIndex* pIdx = pFmt->GetCntnt().GetCntntIdx(); if( pIdx ) { delete pCurPam; pCurPam = NewSwPaM( *pDoc, pIdx->GetIndex(), pIdx->GetNode().EndOfSectionIndex() ); pCurPam->Exchange(); continue; // while-Schleife neu aufsetzen !! } } else { if (bWriteSttTag) { switch(GetAsciiOptions().GetCharSet()) { case RTL_TEXTENCODING_UTF8: Strm() << BYTE(0xEF) << BYTE(0xBB) << BYTE(0xBF); break; case RTL_TEXTENCODING_UCS2: //Strm().StartWritingUnicodeText(); Strm().SetEndianSwap(FALSE); #ifdef OSL_LITENDIAN Strm() << BYTE(0xFF) << BYTE(0xFE); #else Strm() << BYTE(0xFE) << BYTE(0xFF); #endif break; } bWriteSttTag = FALSE; } Out( aASCNodeFnTab, *pNd, *this ); } bTstFly = FALSE; // eimal Testen reicht } if( !pCurPam->Move( fnMoveForward, fnGoNode ) ) break; if( bShowProgress ) ::SetProgressState( pCurPam->GetPoint()->nNode.GetIndex(), pDoc->GetDocShell() ); // Wie weit ? } } while( CopyNextPam( &pPam ) ); // bis alle Pam bearbeitet Strm().SetStreamCharSet( eOld ); if( bShowProgress ) ::EndProgress( pDoc->GetDocShell() ); return 0; } void GetASCWriter( const String& rFltNm, const String& /*rBaseURL*/, WriterRef& xRet ) { xRet = new SwASCWriter( rFltNm ); } <|endoftext|>
<commit_before>d725d6d2-2e4e-11e5-9284-b827eb9e62be<commit_msg>d72f4910-2e4e-11e5-9284-b827eb9e62be<commit_after>d72f4910-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>#pragma once // `krbn::cf_utility::run_loop_thread` can be used safely in a multi-threaded environment. #include "boost_defs.hpp" #include "logger.hpp" #include <CoreFoundation/CoreFoundation.h> #include <boost/optional.hpp> #include <mutex> #include <string> #include <thread> namespace krbn { class cf_utility final { public: template <typename T> class deleter final { public: using pointer = T; void operator()(T _Nullable ref) { if (ref) { CFRelease(ref); } } }; // ======================================== // Converts // ======================================== static boost::optional<std::string> to_string(CFTypeRef _Nullable value) { if (!value) { return boost::none; } if (CFStringGetTypeID() != CFGetTypeID(value)) { return boost::none; } auto cfstring = static_cast<CFStringRef>(value); std::string string; if (auto p = CFStringGetCStringPtr(cfstring, kCFStringEncodingUTF8)) { string = p; } else { auto length = CFStringGetLength(cfstring); auto max_size = CFStringGetMaximumSizeForEncoding(length, kCFStringEncodingUTF8) + 1; char* buffer = new char[max_size]; if (CFStringGetCString(cfstring, buffer, max_size, kCFStringEncodingUTF8)) { string = buffer; } delete[] buffer; } return string; } static CFStringRef _Nullable create_cfstring(const std::string& string) { return CFStringCreateWithCString(kCFAllocatorDefault, string.c_str(), kCFStringEncodingUTF8); } static boost::optional<int64_t> to_int64_t(CFTypeRef _Nullable value) { if (!value) { return boost::none; } if (CFNumberGetTypeID() != CFGetTypeID(value)) { return boost::none; } auto cfnumber = static_cast<CFNumberRef>(value); int64_t result; if (CFNumberGetValue(cfnumber, kCFNumberSInt64Type, &result)) { return result; } return boost::none; } // ======================================== // CFArray, CFMutableArray // ======================================== static CFArrayRef _Nonnull create_empty_cfarray(void) { return CFArrayCreate(nullptr, nullptr, 0, &kCFTypeArrayCallBacks); } static CFMutableArrayRef _Nonnull create_cfmutablearray(CFIndex capacity = 0) { return CFArrayCreateMutable(nullptr, capacity, &kCFTypeArrayCallBacks); } template <typename T> static T _Nullable get_value(CFArrayRef _Nonnull array, CFIndex index) { if (array && index < CFArrayGetCount(array)) { return static_cast<T>(const_cast<void*>(CFArrayGetValueAtIndex(array, index))); } return nullptr; } template <typename T> static bool exists(CFArrayRef _Nonnull array, T _Nonnull value) { if (array) { CFRange range = {0, CFArrayGetCount(array)}; if (CFArrayContainsValue(array, range, value)) { return true; } } return false; } // ======================================== // CFDictionary, CFMutableDictionary // ======================================== static CFMutableDictionaryRef _Nonnull create_cfmutabledictionary(CFIndex capacity = 0) { return CFDictionaryCreateMutable(nullptr, capacity, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); } // ======================================== // CFRunLoop // ======================================== /** * Create a thread and then run CFRunLoop on the thread. */ class run_loop_thread final { public: run_loop_thread(void) : run_loop_(nullptr), running_(false) { thread_ = std::thread([this] { run_loop_ = CFRunLoopGetCurrent(); CFRetain(run_loop_); // Append empty source to prevent immediately quitting of `CFRunLoopRun`. auto context = CFRunLoopSourceContext(); context.perform = perform; auto source = CFRunLoopSourceCreate(kCFAllocatorDefault, 0, &context); CFRunLoopAddSource(run_loop_, source, kCFRunLoopDefaultMode); // Run CFRunLoopPerformBlock(run_loop_, kCFRunLoopDefaultMode, ^{ { std::lock_guard<std::mutex> lock(running_mutex_); running_ = true; } running_cv_.notify_one(); }); CFRunLoopRun(); // Remove source CFRunLoopRemoveSource(run_loop_, source, kCFRunLoopDefaultMode); CFRelease(source); }); } ~run_loop_thread(void) { if (thread_.joinable()) { logger::get_logger().error("Call `cf_utility::run_loop_thread::terminate` before destroy `cf_utility::run_loop_thread`"); terminate(); } if (run_loop_) { CFRelease(run_loop_); } } void terminate(void) { enqueue(^{ CFRunLoopStop(run_loop_); }); if (thread_.joinable()) { thread_.join(); } } CFRunLoopRef _Nonnull get_run_loop(void) const { // We wait until running to avoid a segmentation fault which is described in `enqueue`. wait_until_running(); return run_loop_; } void enqueue(void (^_Nonnull block)(void)) const { // Do not call `CFRunLoopPerformBlock` until `CFRunLoopRun` is called. // A segmentation fault occurs if we call `CFRunLoopPerformBlock` while `CFRunLoopRun' is processing. wait_until_running(); CFRunLoopPerformBlock(run_loop_, kCFRunLoopDefaultMode, block); CFRunLoopWakeUp(run_loop_); } private: void wait_until_running(void) const { std::unique_lock<std::mutex> lock(running_mutex_); running_cv_.wait(lock, [this] { return running_; }); } static void perform(void* _Nullable info) { } std::thread thread_; CFRunLoopRef _Nullable run_loop_; bool running_; mutable std::mutex running_mutex_; mutable std::condition_variable running_cv_; }; }; } // namespace krbn <commit_msg>add run_loop_thread::wake<commit_after>#pragma once // `krbn::cf_utility::run_loop_thread` can be used safely in a multi-threaded environment. #include "boost_defs.hpp" #include "logger.hpp" #include <CoreFoundation/CoreFoundation.h> #include <boost/optional.hpp> #include <mutex> #include <string> #include <thread> namespace krbn { class cf_utility final { public: template <typename T> class deleter final { public: using pointer = T; void operator()(T _Nullable ref) { if (ref) { CFRelease(ref); } } }; // ======================================== // Converts // ======================================== static boost::optional<std::string> to_string(CFTypeRef _Nullable value) { if (!value) { return boost::none; } if (CFStringGetTypeID() != CFGetTypeID(value)) { return boost::none; } auto cfstring = static_cast<CFStringRef>(value); std::string string; if (auto p = CFStringGetCStringPtr(cfstring, kCFStringEncodingUTF8)) { string = p; } else { auto length = CFStringGetLength(cfstring); auto max_size = CFStringGetMaximumSizeForEncoding(length, kCFStringEncodingUTF8) + 1; char* buffer = new char[max_size]; if (CFStringGetCString(cfstring, buffer, max_size, kCFStringEncodingUTF8)) { string = buffer; } delete[] buffer; } return string; } static CFStringRef _Nullable create_cfstring(const std::string& string) { return CFStringCreateWithCString(kCFAllocatorDefault, string.c_str(), kCFStringEncodingUTF8); } static boost::optional<int64_t> to_int64_t(CFTypeRef _Nullable value) { if (!value) { return boost::none; } if (CFNumberGetTypeID() != CFGetTypeID(value)) { return boost::none; } auto cfnumber = static_cast<CFNumberRef>(value); int64_t result; if (CFNumberGetValue(cfnumber, kCFNumberSInt64Type, &result)) { return result; } return boost::none; } // ======================================== // CFArray, CFMutableArray // ======================================== static CFArrayRef _Nonnull create_empty_cfarray(void) { return CFArrayCreate(nullptr, nullptr, 0, &kCFTypeArrayCallBacks); } static CFMutableArrayRef _Nonnull create_cfmutablearray(CFIndex capacity = 0) { return CFArrayCreateMutable(nullptr, capacity, &kCFTypeArrayCallBacks); } template <typename T> static T _Nullable get_value(CFArrayRef _Nonnull array, CFIndex index) { if (array && index < CFArrayGetCount(array)) { return static_cast<T>(const_cast<void*>(CFArrayGetValueAtIndex(array, index))); } return nullptr; } template <typename T> static bool exists(CFArrayRef _Nonnull array, T _Nonnull value) { if (array) { CFRange range = {0, CFArrayGetCount(array)}; if (CFArrayContainsValue(array, range, value)) { return true; } } return false; } // ======================================== // CFDictionary, CFMutableDictionary // ======================================== static CFMutableDictionaryRef _Nonnull create_cfmutabledictionary(CFIndex capacity = 0) { return CFDictionaryCreateMutable(nullptr, capacity, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); } // ======================================== // CFRunLoop // ======================================== /** * Create a thread and then run CFRunLoop on the thread. */ class run_loop_thread final { public: run_loop_thread(void) : run_loop_(nullptr), running_(false) { thread_ = std::thread([this] { run_loop_ = CFRunLoopGetCurrent(); CFRetain(run_loop_); // Append empty source to prevent immediately quitting of `CFRunLoopRun`. auto context = CFRunLoopSourceContext(); context.perform = perform; auto source = CFRunLoopSourceCreate(kCFAllocatorDefault, 0, &context); CFRunLoopAddSource(run_loop_, source, kCFRunLoopDefaultMode); // Run CFRunLoopPerformBlock(run_loop_, kCFRunLoopDefaultMode, ^{ { std::lock_guard<std::mutex> lock(running_mutex_); running_ = true; } running_cv_.notify_one(); }); CFRunLoopRun(); // Remove source CFRunLoopRemoveSource(run_loop_, source, kCFRunLoopDefaultMode); CFRelease(source); }); } ~run_loop_thread(void) { if (thread_.joinable()) { logger::get_logger().error("Call `cf_utility::run_loop_thread::terminate` before destroy `cf_utility::run_loop_thread`"); terminate(); } if (run_loop_) { CFRelease(run_loop_); } } void terminate(void) { enqueue(^{ CFRunLoopStop(run_loop_); }); if (thread_.joinable()) { thread_.join(); } } CFRunLoopRef _Nonnull get_run_loop(void) const { // We wait until running to avoid a segmentation fault which is described in `enqueue`. wait_until_running(); return run_loop_; } void enqueue(void (^_Nonnull block)(void)) const { // Do not call `CFRunLoopPerformBlock` until `CFRunLoopRun` is called. // A segmentation fault occurs if we call `CFRunLoopPerformBlock` while `CFRunLoopRun' is processing. wait_until_running(); CFRunLoopPerformBlock(run_loop_, kCFRunLoopDefaultMode, block); CFRunLoopWakeUp(run_loop_); } void wake(void) const { // Do not touch run_loop_ until `CFRunLoopRun` is called. // A segmentation fault occurs if we touch `run_loop_` while `CFRunLoopRun' is processing. wait_until_running(); CFRunLoopWakeUp(run_loop_); } private: void wait_until_running(void) const { std::unique_lock<std::mutex> lock(running_mutex_); running_cv_.wait(lock, [this] { return running_; }); } static void perform(void* _Nullable info) { } std::thread thread_; CFRunLoopRef _Nullable run_loop_; bool running_; mutable std::mutex running_mutex_; mutable std::condition_variable running_cv_; }; }; } // namespace krbn <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: wrtasc.hxx,v $ * * $Revision: 1.1.1.1 $ * * last change: $Author: hr $ $Date: 2000-09-18 17:14:53 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _WRTASC_HXX #define _WRTASC_HXX #ifndef _SHELLIO_HXX #include <shellio.hxx> #endif #ifndef _WRT_FN_HXX #include <wrt_fn.hxx> #endif extern SwNodeFnTab aASCNodeFnTab; // der ASC-Writer class SwASCWriter : public Writer { String sLineEnd; virtual ULONG WriteStream(); public: SwASCWriter( const String& rFilterName ); virtual ~SwASCWriter(); const String& GetLineEnd() const { return sLineEnd; } }; #endif // _WRTASC_HXX <commit_msg>INTEGRATION: CWS ooo19126 (1.1.1.1.1462); FILE MERGED 2005/09/05 13:41:53 rt 1.1.1.1.1462.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: wrtasc.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2005-09-09 05:34: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 _WRTASC_HXX #define _WRTASC_HXX #ifndef _SHELLIO_HXX #include <shellio.hxx> #endif #ifndef _WRT_FN_HXX #include <wrt_fn.hxx> #endif extern SwNodeFnTab aASCNodeFnTab; // der ASC-Writer class SwASCWriter : public Writer { String sLineEnd; virtual ULONG WriteStream(); public: SwASCWriter( const String& rFilterName ); virtual ~SwASCWriter(); const String& GetLineEnd() const { return sLineEnd; } }; #endif // _WRTASC_HXX <|endoftext|>
<commit_before>87df65e8-2e4e-11e5-9284-b827eb9e62be<commit_msg>87e482b2-2e4e-11e5-9284-b827eb9e62be<commit_after>87e482b2-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>f3c65b64-2e4d-11e5-9284-b827eb9e62be<commit_msg>f3cb6aaa-2e4d-11e5-9284-b827eb9e62be<commit_after>f3cb6aaa-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>177c3104-2e4f-11e5-9284-b827eb9e62be<commit_msg>17814644-2e4f-11e5-9284-b827eb9e62be<commit_after>17814644-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>/* * Copyright (C) 2008-2013 Communi authors * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #include "usermodel.h" #include "session.h" #include <ircmessage.h> #include <ircsender.h> #include <irc.h> UserModel::UserModel(QObject* parent) : QAbstractListModel(parent) { d.session = qobject_cast<Session*>(parent); } UserModel::~UserModel() { } Session* UserModel::session() const { return d.session; } void UserModel::setSession(Session* session) { d.session = session; clearUsers(); } QString UserModel::channel() const { return d.channel; } void UserModel::setChannel(const QString& channel) { d.channel = channel.toLower(); } QStringList UserModel::users() const { return d.names; } bool UserModel::hasUser(const QString& user) const { return d.names.contains(user, Qt::CaseInsensitive); } void UserModel::addUser(const QString& user) { addUsers(QStringList() << user); } void UserModel::addUsers(const QStringList& users) { QStringList unique; QSet<QString> nameSet = d.names.toSet(); foreach (const QString& user, users) { QString name = d.session->unprefixedUser(user); if (!nameSet.contains(name)) unique += user; } if (!unique.isEmpty()) { beginInsertRows(QModelIndex(), rowCount(), rowCount() + unique.count() - 1); foreach (const QString& user, unique) { QString name = d.session->unprefixedUser(user); d.names += name; d.prefixes.insert(name, d.session->userPrefix(user)); } endInsertRows(); } } void UserModel::removeUser(const QString& user) { QString name = d.session->unprefixedUser(user); int idx = d.names.indexOf(name); if (idx != -1) { beginRemoveRows(QModelIndex(), idx, idx); d.names.removeAt(idx); d.prefixes.remove(name); endRemoveRows(); } } void UserModel::clearUsers() { if (!d.names.isEmpty()) { beginResetModel(); d.names.clear(); endResetModel(); } } void UserModel::renameUser(const QString& from, const QString& to) { int idx = d.names.indexOf(from); if (idx != -1) { d.names[idx] = to; d.prefixes[to] = d.prefixes.take(from); emit dataChanged(index(idx, 0), index(idx, 0)); } } void UserModel::setUserMode(const QString& user, const QString& mode) { int idx = d.names.indexOf(user); if (idx != -1) { bool add = true; IrcSessionInfo info(d.session); QString updated = d.prefixes.value(user); for (int i = 0; i < mode.size(); ++i) { QChar c = mode.at(i); QString p = info.modeToPrefix(c); switch (c.unicode()) { case '+': add = true; break; case '-': add = false; break; default: if (add) { if (!updated.contains(p)) updated += p; } else { updated.remove(p); } break; } } d.prefixes[user] = updated; emit dataChanged(index(idx, 0), index(idx, 0)); } } int UserModel::rowCount(const QModelIndex& parent) const { if (parent.isValid()) return 0; return d.names.count(); } QVariant UserModel::data(const QModelIndex& index, int role) const { if (index.row() < 0 || index.row() >= d.names.count()) return QVariant(); if (role == Qt::DisplayRole || role == Qt::EditRole || role == Qt::UserRole) { QString name = d.names.at(index.row()); if (role == Qt::DisplayRole) return d.prefixes.value(name).left(1) + name; if (role == Qt::UserRole) return d.prefixes.value(name); return name; } return QVariant(); } void UserModel::processMessage(IrcMessage* message) { if (!d.session) { qWarning() << "UserModel::processMessage(): session is null!"; return; } if (message->type() == IrcMessage::Nick) { QString nick = message->sender().name().toLower(); renameUser(nick, static_cast<IrcNickMessage*>(message)->nick()); } else if (message->type() == IrcMessage::Join) { if (message->flags() & IrcMessage::Own) clearUsers(); else addUser(message->sender().name()); } else if (message->type() == IrcMessage::Part) { if (message->flags() & IrcMessage::Own) clearUsers(); else removeUser(message->sender().name()); } else if (message->type() == IrcMessage::Kick) { removeUser(static_cast<IrcKickMessage*>(message)->user()); } else if (message->type() == IrcMessage::Quit) { removeUser(message->sender().name()); } else if (message->type() == IrcMessage::Mode) { IrcModeMessage* modeMsg = static_cast<IrcModeMessage*>(message); if (modeMsg->sender().name() != modeMsg->target() && !modeMsg->argument().isEmpty()) setUserMode(modeMsg->argument(), modeMsg->mode()); } else if (message->type() == IrcMessage::Numeric) { if (static_cast<IrcNumericMessage*>(message)->code() == Irc::RPL_NAMREPLY) { int count = message->parameters().count(); if (!d.channel.isNull() && d.channel == message->parameters().value(count - 2).toLower()) { QString names = message->parameters().value(count - 1); addUsers(names.split(" ", QString::SkipEmptyParts)); } } } } <commit_msg>Fix #5: UserModel goes sometimes out of sync<commit_after>/* * Copyright (C) 2008-2013 Communi authors * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #include "usermodel.h" #include "session.h" #include <ircmessage.h> #include <ircsender.h> #include <irc.h> UserModel::UserModel(QObject* parent) : QAbstractListModel(parent) { d.session = qobject_cast<Session*>(parent); } UserModel::~UserModel() { } Session* UserModel::session() const { return d.session; } void UserModel::setSession(Session* session) { d.session = session; clearUsers(); } QString UserModel::channel() const { return d.channel; } void UserModel::setChannel(const QString& channel) { d.channel = channel.toLower(); } QStringList UserModel::users() const { return d.names; } bool UserModel::hasUser(const QString& user) const { return d.names.contains(user, Qt::CaseInsensitive); } void UserModel::addUser(const QString& user) { addUsers(QStringList() << user); } void UserModel::addUsers(const QStringList& users) { QStringList unique; QSet<QString> nameSet = d.names.toSet(); foreach (const QString& user, users) { QString name = d.session->unprefixedUser(user); if (!nameSet.contains(name)) unique += user; } if (!unique.isEmpty()) { beginInsertRows(QModelIndex(), rowCount(), rowCount() + unique.count() - 1); foreach (const QString& user, unique) { QString name = d.session->unprefixedUser(user); d.names += name; d.prefixes.insert(name, d.session->userPrefix(user)); } endInsertRows(); } } void UserModel::removeUser(const QString& user) { QString name = d.session->unprefixedUser(user); int idx = d.names.indexOf(name); if (idx != -1) { beginRemoveRows(QModelIndex(), idx, idx); d.names.removeAt(idx); d.prefixes.remove(name); endRemoveRows(); } } void UserModel::clearUsers() { if (!d.names.isEmpty()) { beginResetModel(); d.names.clear(); endResetModel(); } } void UserModel::renameUser(const QString& from, const QString& to) { int idx = d.names.indexOf(from); if (idx != -1) { d.names[idx] = to; d.prefixes[to] = d.prefixes.take(from); emit dataChanged(index(idx, 0), index(idx, 0)); } } void UserModel::setUserMode(const QString& user, const QString& mode) { int idx = d.names.indexOf(user); if (idx != -1) { bool add = true; IrcSessionInfo info(d.session); QString updated = d.prefixes.value(user); for (int i = 0; i < mode.size(); ++i) { QChar c = mode.at(i); QString p = info.modeToPrefix(c); switch (c.unicode()) { case '+': add = true; break; case '-': add = false; break; default: if (add) { if (!updated.contains(p)) updated += p; } else { updated.remove(p); } break; } } d.prefixes[user] = updated; emit dataChanged(index(idx, 0), index(idx, 0)); } } int UserModel::rowCount(const QModelIndex& parent) const { if (parent.isValid()) return 0; return d.names.count(); } QVariant UserModel::data(const QModelIndex& index, int role) const { if (index.row() < 0 || index.row() >= d.names.count()) return QVariant(); if (role == Qt::DisplayRole || role == Qt::EditRole || role == Qt::UserRole) { QString name = d.names.at(index.row()); if (role == Qt::DisplayRole) return d.prefixes.value(name).left(1) + name; if (role == Qt::UserRole) return d.prefixes.value(name); return name; } return QVariant(); } void UserModel::processMessage(IrcMessage* message) { if (!d.session) { qWarning() << "UserModel::processMessage(): session is null!"; return; } if (message->type() == IrcMessage::Nick) { QString from = message->sender().name(); QString to = static_cast<IrcNickMessage*>(message)->nick(); renameUser(from, to); } else if (message->type() == IrcMessage::Join) { if (message->flags() & IrcMessage::Own) clearUsers(); else addUser(message->sender().name()); } else if (message->type() == IrcMessage::Part) { if (message->flags() & IrcMessage::Own) clearUsers(); else removeUser(message->sender().name()); } else if (message->type() == IrcMessage::Kick) { removeUser(static_cast<IrcKickMessage*>(message)->user()); } else if (message->type() == IrcMessage::Quit) { removeUser(message->sender().name()); } else if (message->type() == IrcMessage::Mode) { IrcModeMessage* modeMsg = static_cast<IrcModeMessage*>(message); if (modeMsg->sender().name() != modeMsg->target() && !modeMsg->argument().isEmpty()) setUserMode(modeMsg->argument(), modeMsg->mode()); } else if (message->type() == IrcMessage::Numeric) { if (static_cast<IrcNumericMessage*>(message)->code() == Irc::RPL_NAMREPLY) { int count = message->parameters().count(); if (!d.channel.isNull() && d.channel == message->parameters().value(count - 2).toLower()) { QString names = message->parameters().value(count - 1); addUsers(names.split(" ", QString::SkipEmptyParts)); } } } } <|endoftext|>
<commit_before>92f734e8-2e4d-11e5-9284-b827eb9e62be<commit_msg>92fc3312-2e4d-11e5-9284-b827eb9e62be<commit_after>92fc3312-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>/* This file is part of the KDE project Copyright (C) 2006-2007 Matthias Kretz <kretz@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 as published by the Free Software Foundation. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "volumeslider.h" #include "volumeslider_p.h" #include "audiooutput.h" #include "phonondefs_p.h" #include "phononnamespace_p.h" #include "factory.h" namespace Phonon { VolumeSlider::VolumeSlider(QWidget *parent) : QWidget(parent), k_ptr(new VolumeSliderPrivate(this)) { K_D(VolumeSlider); setToolTip(tr("Volume: %1%").arg(100)); setWhatsThis(tr("Use this slider to adjust the volume. The leftmost position is 0%, the rightmost is %1%").arg(100)); connect(&d->slider, SIGNAL(valueChanged(int)), SLOT(_k_sliderChanged(int))); connect(&d->muteButton, SIGNAL(clicked()), SLOT(_k_buttonClicked())); } VolumeSlider::VolumeSlider(AudioOutput *output, QWidget *parent) : QWidget(parent), k_ptr(new VolumeSliderPrivate(this)) { K_D(VolumeSlider); setToolTip(tr("Volume: %1%").arg(100)); setWhatsThis(tr("Use this slider to adjust the volume. The leftmost position is 0%, the rightmost is %1%").arg(100)); connect(&d->slider, SIGNAL(valueChanged(int)), SLOT(_k_sliderChanged(int))); connect(&d->muteButton, SIGNAL(clicked()), SLOT(_k_buttonClicked())); if (output) { d->output = output; d->slider.setValue(qRound(100 * output->volume())); d->slider.setEnabled(true); d->muteButton.setEnabled(true); connect(output, SIGNAL(volumeChanged(qreal)), SLOT(_k_volumeChanged(qreal))); connect(output, SIGNAL(mutedChanged(bool)), SLOT(_k_mutedChanged(bool))); } } VolumeSlider::~VolumeSlider() { delete k_ptr; } bool VolumeSlider::isMuteVisible() const { return k_ptr->muteButton.isVisible(); } void VolumeSlider::setMuteVisible(bool visible) { k_ptr->muteButton.setVisible(visible); } QSize VolumeSlider::iconSize() const { return k_ptr->muteButton.iconSize(); } void VolumeSlider::setIconSize(const QSize &iconSize) { pDebug() << Q_FUNC_INFO << iconSize; k_ptr->muteButton.setIconSize(iconSize); } qreal VolumeSlider::maximumVolume() const { return k_ptr->slider.maximum() * 0.01; } void VolumeSlider::setMaximumVolume(qreal volume) { int max = static_cast<int>(volume * 100); k_ptr->slider.setMaximum(max); setWhatsThis(tr("Use this slider to adjust the volume. The leftmost position is 0%, the rightmost is %1%") .arg(max)); } Qt::Orientation VolumeSlider::orientation() const { return k_ptr->slider.orientation(); } void VolumeSlider::setOrientation(Qt::Orientation o) { K_D(VolumeSlider); Qt::Alignment align = (o == Qt::Horizontal ? Qt::AlignVCenter : Qt::AlignHCenter); d->layout.setAlignment(&d->muteButton, align); d->layout.setAlignment(&d->slider, align); d->layout.setDirection(o == Qt::Horizontal ? QBoxLayout::LeftToRight : QBoxLayout::TopToBottom); d->slider.setOrientation(o); } AudioOutput *VolumeSlider::audioOutput() const { K_D(const VolumeSlider); return d->output; } void VolumeSlider::setAudioOutput(AudioOutput *output) { K_D(VolumeSlider); if (d->output) { disconnect(d->output, 0, this, 0); } d->output = output; if (output) { d->slider.setValue(qRound(100 * output->volume())); d->slider.setEnabled(true); d->muteButton.setEnabled(true); d->_k_volumeChanged(output->volume()); d->_k_mutedChanged(output->isMuted()); connect(output, SIGNAL(volumeChanged(qreal)), SLOT(_k_volumeChanged(qreal))); connect(output, SIGNAL(mutedChanged(bool)), SLOT(_k_mutedChanged(bool))); } else { d->slider.setValue(100); d->slider.setEnabled(false); d->muteButton.setEnabled(false); } } void VolumeSliderPrivate::_k_buttonClicked() { if (output) { output->setMuted(!output->isMuted()); } else { slider.setEnabled(false); muteButton.setEnabled(false); } } void VolumeSliderPrivate::_k_mutedChanged(bool muted) { Q_Q(VolumeSlider); if (muted) { q->setToolTip(VolumeSlider::tr("Muted")); muteButton.setIcon(mutedIcon); } else { q->setToolTip(VolumeSlider::tr("Volume: %1%").arg(static_cast<int>(output->volume() * 100.0))); muteButton.setIcon(volumeIcon); } } void VolumeSliderPrivate::_k_sliderChanged(int value) { Q_Q(VolumeSlider); if (output) { if (!output->isMuted()) { q->setToolTip(VolumeSlider::tr("Volume: %1%").arg(value)); } ignoreVolumeChange = true; output->setVolume((static_cast<qreal>(value)) * 0.01); ignoreVolumeChange = false; } else { slider.setEnabled(false); muteButton.setEnabled(false); } } void VolumeSliderPrivate::_k_volumeChanged(qreal value) { if (!ignoreVolumeChange) { slider.setValue(qRound(100 * value)); } } bool VolumeSlider::hasTracking() const { return k_ptr->slider.hasTracking(); } void VolumeSlider::setTracking(bool tracking) { k_ptr->slider.setTracking(tracking); } int VolumeSlider::pageStep() const { return k_ptr->slider.pageStep(); } void VolumeSlider::setPageStep(int milliseconds) { k_ptr->slider.setPageStep(milliseconds); } int VolumeSlider::singleStep() const { return k_ptr->slider.singleStep(); } void VolumeSlider::setSingleStep(int milliseconds) { k_ptr->slider.setSingleStep(milliseconds); } } // namespace Phonon #include "moc_volumeslider.cpp" // vim: sw=4 et <commit_msg>make the internal slider take focus if VolumeSlider is supposed to take focus<commit_after>/* This file is part of the KDE project Copyright (C) 2006-2007 Matthias Kretz <kretz@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 as published by the Free Software Foundation. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "volumeslider.h" #include "volumeslider_p.h" #include "audiooutput.h" #include "phonondefs_p.h" #include "phononnamespace_p.h" #include "factory.h" namespace Phonon { VolumeSlider::VolumeSlider(QWidget *parent) : QWidget(parent), k_ptr(new VolumeSliderPrivate(this)) { K_D(VolumeSlider); setToolTip(tr("Volume: %1%").arg(100)); setWhatsThis(tr("Use this slider to adjust the volume. The leftmost position is 0%, the rightmost is %1%").arg(100)); connect(&d->slider, SIGNAL(valueChanged(int)), SLOT(_k_sliderChanged(int))); connect(&d->muteButton, SIGNAL(clicked()), SLOT(_k_buttonClicked())); setFocusProxy(&d->slider); } VolumeSlider::VolumeSlider(AudioOutput *output, QWidget *parent) : QWidget(parent), k_ptr(new VolumeSliderPrivate(this)) { K_D(VolumeSlider); setToolTip(tr("Volume: %1%").arg(100)); setWhatsThis(tr("Use this slider to adjust the volume. The leftmost position is 0%, the rightmost is %1%").arg(100)); connect(&d->slider, SIGNAL(valueChanged(int)), SLOT(_k_sliderChanged(int))); connect(&d->muteButton, SIGNAL(clicked()), SLOT(_k_buttonClicked())); if (output) { d->output = output; d->slider.setValue(qRound(100 * output->volume())); d->slider.setEnabled(true); d->muteButton.setEnabled(true); connect(output, SIGNAL(volumeChanged(qreal)), SLOT(_k_volumeChanged(qreal))); connect(output, SIGNAL(mutedChanged(bool)), SLOT(_k_mutedChanged(bool))); } setFocusProxy(&d->slider); } VolumeSlider::~VolumeSlider() { delete k_ptr; } bool VolumeSlider::isMuteVisible() const { return k_ptr->muteButton.isVisible(); } void VolumeSlider::setMuteVisible(bool visible) { k_ptr->muteButton.setVisible(visible); } QSize VolumeSlider::iconSize() const { return k_ptr->muteButton.iconSize(); } void VolumeSlider::setIconSize(const QSize &iconSize) { pDebug() << Q_FUNC_INFO << iconSize; k_ptr->muteButton.setIconSize(iconSize); } qreal VolumeSlider::maximumVolume() const { return k_ptr->slider.maximum() * 0.01; } void VolumeSlider::setMaximumVolume(qreal volume) { int max = static_cast<int>(volume * 100); k_ptr->slider.setMaximum(max); setWhatsThis(tr("Use this slider to adjust the volume. The leftmost position is 0%, the rightmost is %1%") .arg(max)); } Qt::Orientation VolumeSlider::orientation() const { return k_ptr->slider.orientation(); } void VolumeSlider::setOrientation(Qt::Orientation o) { K_D(VolumeSlider); Qt::Alignment align = (o == Qt::Horizontal ? Qt::AlignVCenter : Qt::AlignHCenter); d->layout.setAlignment(&d->muteButton, align); d->layout.setAlignment(&d->slider, align); d->layout.setDirection(o == Qt::Horizontal ? QBoxLayout::LeftToRight : QBoxLayout::TopToBottom); d->slider.setOrientation(o); } AudioOutput *VolumeSlider::audioOutput() const { K_D(const VolumeSlider); return d->output; } void VolumeSlider::setAudioOutput(AudioOutput *output) { K_D(VolumeSlider); if (d->output) { disconnect(d->output, 0, this, 0); } d->output = output; if (output) { d->slider.setValue(qRound(100 * output->volume())); d->slider.setEnabled(true); d->muteButton.setEnabled(true); d->_k_volumeChanged(output->volume()); d->_k_mutedChanged(output->isMuted()); connect(output, SIGNAL(volumeChanged(qreal)), SLOT(_k_volumeChanged(qreal))); connect(output, SIGNAL(mutedChanged(bool)), SLOT(_k_mutedChanged(bool))); } else { d->slider.setValue(100); d->slider.setEnabled(false); d->muteButton.setEnabled(false); } } void VolumeSliderPrivate::_k_buttonClicked() { if (output) { output->setMuted(!output->isMuted()); } else { slider.setEnabled(false); muteButton.setEnabled(false); } } void VolumeSliderPrivate::_k_mutedChanged(bool muted) { Q_Q(VolumeSlider); if (muted) { q->setToolTip(VolumeSlider::tr("Muted")); muteButton.setIcon(mutedIcon); } else { q->setToolTip(VolumeSlider::tr("Volume: %1%").arg(static_cast<int>(output->volume() * 100.0))); muteButton.setIcon(volumeIcon); } } void VolumeSliderPrivate::_k_sliderChanged(int value) { Q_Q(VolumeSlider); if (output) { if (!output->isMuted()) { q->setToolTip(VolumeSlider::tr("Volume: %1%").arg(value)); } ignoreVolumeChange = true; output->setVolume((static_cast<qreal>(value)) * 0.01); ignoreVolumeChange = false; } else { slider.setEnabled(false); muteButton.setEnabled(false); } } void VolumeSliderPrivate::_k_volumeChanged(qreal value) { if (!ignoreVolumeChange) { slider.setValue(qRound(100 * value)); } } bool VolumeSlider::hasTracking() const { return k_ptr->slider.hasTracking(); } void VolumeSlider::setTracking(bool tracking) { k_ptr->slider.setTracking(tracking); } int VolumeSlider::pageStep() const { return k_ptr->slider.pageStep(); } void VolumeSlider::setPageStep(int milliseconds) { k_ptr->slider.setPageStep(milliseconds); } int VolumeSlider::singleStep() const { return k_ptr->slider.singleStep(); } void VolumeSlider::setSingleStep(int milliseconds) { k_ptr->slider.setSingleStep(milliseconds); } } // namespace Phonon #include "moc_volumeslider.cpp" // vim: sw=4 et <|endoftext|>
<commit_before>/* * Author: Michael Camilleri * * Copyright (c) 2016, University Of Edinburgh * 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 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 <exotica/PlanningProblem.h> #include <exotica/PlanningProblemInitializer.h> #include <exotica/Setup.h> namespace exotica { PlanningProblem::PlanningProblem() : Flags(KIN_FK), N(0) { } std::string PlanningProblem::print(std::string prepend) { std::string ret = Object::print(prepend); ret += "\n" + prepend + " Task definitions:"; for (auto& it : TaskMaps) ret += "\n" + it.second->print(prepend + " "); return ret; } Eigen::VectorXd PlanningProblem::applyStartState() { scene_->setModelState(startState); return scene_->getControlledState(); } void PlanningProblem::preupdate() { for (auto& it : TaskMaps) it.second->preupdate(); } void PlanningProblem::setStartState(Eigen::VectorXdRefConst x) { if (x.rows() == startState.rows()) { startState = x; } else if (x.rows() == scene_->getSolver().getNumControlledJoints()) { std::vector<std::string> jointNames = scene_->getJointNames(); std::vector<std::string> modelNames = scene_->getModelJointNames(); for (int i = 0; i < jointNames.size(); i++) { for (int j = 0; j < modelNames.size(); j++) { if (jointNames[i] == modelNames[j]) startState[j] = x(i); } } } else { throw_named("Wrong start state vector size, expected " << startState.rows() << " got " << x.rows()); } } Eigen::VectorXd PlanningProblem::getStartState() { return startState; } void PlanningProblem::InstantiateBase(const Initializer& init_) { Object::InstatiateObject(init_); PlanningProblemInitializer init(init_); TaskMaps.clear(); Tasks.clear(); // Create the scene scene_.reset(new Scene()); scene_->InstantiateInternal(SceneInitializer(init.PlanningScene)); startState = Eigen::VectorXd::Zero(scene_->getModelJointNames().size()); N = scene_->getSolver().getNumControlledJoints(); if (init.StartState.rows() > 0) { setStartState(init.StartState); } KinematicsRequest Request; Request.Flags = Flags; // Create the maps int id = 0; for (const Initializer& MapInitializer : init.Maps) { TaskMap_ptr NewMap = Setup::createMap(MapInitializer); NewMap->assignScene(scene_); NewMap->ns_ = ns_ + "/" + NewMap->getObjectName(); if (TaskMaps.find(NewMap->getObjectName()) != TaskMaps.end()) { throw_named("Map '" + NewMap->getObjectName() + "' already exists!"); } std::vector<KinematicFrameRequest> frames = NewMap->GetFrames(); NewMap->Kinematics = KinematicSolution(id, frames.size()); id += frames.size(); Request.Frames.insert(Request.Frames.end(), frames.begin(), frames.end()); TaskMaps[NewMap->getObjectName()] = NewMap; Tasks.push_back(NewMap); } std::shared_ptr<KinematicResponse> Response = scene_->RequestKinematics(Request); id = 0; int idJ = 0; for (int i = 0; i < Tasks.size(); i++) { Tasks[i]->Kinematics.Create(Response); Tasks[i]->Id = i; Tasks[i]->Start = id; Tasks[i]->Length = Tasks[i]->taskSpaceDim(); Tasks[i]->StartJ = idJ; Tasks[i]->LengthJ = Tasks[i]->taskSpaceJacobianDim(); id += Tasks[i]->Length; idJ += Tasks[i]->LengthJ; } if (init.Maps.size() == 0) { HIGHLIGHT("No maps were defined!"); } } TaskMap_map& PlanningProblem::getTaskMaps() { return TaskMaps; } TaskMap_vec& PlanningProblem::getTasks() { return Tasks; } Scene_ptr PlanningProblem::getScene() { return scene_; } } <commit_msg>PlanningProblem: Fix setStartState on initialisation<commit_after>/* * Author: Michael Camilleri * * Copyright (c) 2016, University Of Edinburgh * 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 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 <exotica/PlanningProblem.h> #include <exotica/PlanningProblemInitializer.h> #include <exotica/Setup.h> namespace exotica { PlanningProblem::PlanningProblem() : Flags(KIN_FK), N(0) { } std::string PlanningProblem::print(std::string prepend) { std::string ret = Object::print(prepend); ret += "\n" + prepend + " Task definitions:"; for (auto& it : TaskMaps) ret += "\n" + it.second->print(prepend + " "); return ret; } Eigen::VectorXd PlanningProblem::applyStartState() { scene_->setModelState(startState); return scene_->getControlledState(); } void PlanningProblem::preupdate() { for (auto& it : TaskMaps) it.second->preupdate(); } void PlanningProblem::setStartState(Eigen::VectorXdRefConst x) { if (x.rows() == scene_->getSolver().getNumModelJoints()) { startState = x; } else if (x.rows() == scene_->getSolver().getNumControlledJoints()) { std::vector<std::string> jointNames = scene_->getJointNames(); std::vector<std::string> modelNames = scene_->getModelJointNames(); for (int i = 0; i < jointNames.size(); i++) { for (int j = 0; j < modelNames.size(); j++) { if (jointNames[i] == modelNames[j]) startState[j] = x(i); } } } else { throw_named("Wrong start state vector size, expected " << scene_->getSolver().getNumModelJoints() << ", got " << x.rows()); } } Eigen::VectorXd PlanningProblem::getStartState() { return startState; } void PlanningProblem::InstantiateBase(const Initializer& init_) { Object::InstatiateObject(init_); PlanningProblemInitializer init(init_); TaskMaps.clear(); Tasks.clear(); // Create the scene scene_.reset(new Scene()); scene_->InstantiateInternal(SceneInitializer(init.PlanningScene)); startState = Eigen::VectorXd::Zero(scene_->getModelJointNames().size()); N = scene_->getSolver().getNumControlledJoints(); if (init.StartState.rows() > 0) { setStartState(init.StartState); } KinematicsRequest Request; Request.Flags = Flags; // Create the maps int id = 0; for (const Initializer& MapInitializer : init.Maps) { TaskMap_ptr NewMap = Setup::createMap(MapInitializer); NewMap->assignScene(scene_); NewMap->ns_ = ns_ + "/" + NewMap->getObjectName(); if (TaskMaps.find(NewMap->getObjectName()) != TaskMaps.end()) { throw_named("Map '" + NewMap->getObjectName() + "' already exists!"); } std::vector<KinematicFrameRequest> frames = NewMap->GetFrames(); NewMap->Kinematics = KinematicSolution(id, frames.size()); id += frames.size(); Request.Frames.insert(Request.Frames.end(), frames.begin(), frames.end()); TaskMaps[NewMap->getObjectName()] = NewMap; Tasks.push_back(NewMap); } std::shared_ptr<KinematicResponse> Response = scene_->RequestKinematics(Request); id = 0; int idJ = 0; for (int i = 0; i < Tasks.size(); i++) { Tasks[i]->Kinematics.Create(Response); Tasks[i]->Id = i; Tasks[i]->Start = id; Tasks[i]->Length = Tasks[i]->taskSpaceDim(); Tasks[i]->StartJ = idJ; Tasks[i]->LengthJ = Tasks[i]->taskSpaceJacobianDim(); id += Tasks[i]->Length; idJ += Tasks[i]->LengthJ; } if (init.Maps.size() == 0) { HIGHLIGHT("No maps were defined!"); } } TaskMap_map& PlanningProblem::getTaskMaps() { return TaskMaps; } TaskMap_vec& PlanningProblem::getTasks() { return Tasks; } Scene_ptr PlanningProblem::getScene() { return scene_; } } <|endoftext|>
<commit_before>8f12b284-2e4e-11e5-9284-b827eb9e62be<commit_msg>8f17bc34-2e4e-11e5-9284-b827eb9e62be<commit_after>8f17bc34-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>3eb6a052-2e4e-11e5-9284-b827eb9e62be<commit_msg>3ebba9b2-2e4e-11e5-9284-b827eb9e62be<commit_after>3ebba9b2-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>cfae2974-2e4c-11e5-9284-b827eb9e62be<commit_msg>cfb31b32-2e4c-11e5-9284-b827eb9e62be<commit_after>cfb31b32-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>c2e2de8c-2e4d-11e5-9284-b827eb9e62be<commit_msg>c2e7e710-2e4d-11e5-9284-b827eb9e62be<commit_after>c2e7e710-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before><commit_msg>clang scan-build: Dead initialization<commit_after><|endoftext|>
<commit_before>7341811c-2e4d-11e5-9284-b827eb9e62be<commit_msg>734689dc-2e4d-11e5-9284-b827eb9e62be<commit_after>734689dc-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>3c83991a-2e4f-11e5-9284-b827eb9e62be<commit_msg>3c888880-2e4f-11e5-9284-b827eb9e62be<commit_after>3c888880-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>a301650c-2e4d-11e5-9284-b827eb9e62be<commit_msg>a30665e8-2e4d-11e5-9284-b827eb9e62be<commit_after>a30665e8-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>c357eabe-2e4e-11e5-9284-b827eb9e62be<commit_msg>c35ce050-2e4e-11e5-9284-b827eb9e62be<commit_after>c35ce050-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>eefa26f2-2e4c-11e5-9284-b827eb9e62be<commit_msg>eeff20e4-2e4c-11e5-9284-b827eb9e62be<commit_after>eeff20e4-2e4c-11e5-9284-b827eb9e62be<|endoftext|>